file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/11155111/0xf4A9cC47dD427Bc6115f8ecC60e7A9197a442c14/sources/project_/contracts/vesting/VestingContract.sol
Ensure one per address Create schedule
function createVestingSchedule(address _beneficiary, uint256 _amount, uint256 _start, uint256 _durationInDays, uint256 _cliffDurationInDays) external { require(accessControls.hasAdminRole(_msgSender()), "VestingContract.createVestingSchedule: Only admin"); require(_beneficiary != address(0), "VestingContract.createVestingSchedule: Beneficiary cannot be empty"); require(_amount > 0, "VestingContract.createVestingSchedule: Amount cannot be empty"); require(_durationInDays > 0, "VestingContract.createVestingSchedule: Duration cannot be empty"); require(_cliffDurationInDays <= _durationInDays, "VestingContract.createVestingSchedule: Cliff can not be bigger than duration"); require(vestingSchedule[_beneficiary].amount == 0, "VestingContract.createVestingSchedule: Schedule already in flight"); uint256 _durationInSecs = _durationInDays.mul(PERIOD_ONE_DAY_IN_SECONDS); uint256 _cliffDurationInSecs = _cliffDurationInDays.mul(PERIOD_ONE_DAY_IN_SECONDS); vestingSchedule[_beneficiary] = Schedule({ start : _start, end : _start.add(_durationInSecs), cliff : _start.add(_cliffDurationInSecs), amount : _amount, drawDownRate : _amount.div(_durationInSecs) }); emit ScheduleCreated(_beneficiary, _amount, _start, _durationInDays); }
3,534,776
./partial_match/1/0xC6a2A61C8A1c9614085207A2692D08ad78b9E425/sources/_contracts/debt/mozart/MozartCoreV1.sol
Intitialise the protocol with the appropriate parameters. Can only be called once. _collateralDecimals How many decimals does the collateral contain _collateralAddress The address of the collateral to be used _syntheticAddress The address of the synthetic token proxy _oracleAddress Address of the IOracle conforming contract _interestSetter Address which can update interest rates _collateralRatio How much colalteral is needed to borrow _liquidationUserFee How much is a user penalised if they go below their c-ratio _liquidationArcRatio How much of the liquidation profit should ARC take/
function init( uint8 _collateralDecimals, address _collateralAddress, address _syntheticAddress, address _oracleAddress, address _interestSetter, Decimal.D256 memory _collateralRatio, Decimal.D256 memory _liquidationUserFee, Decimal.D256 memory _liquidationArcRatio ) public { require( collateralAsset == address(0), "MozartCoreV1: cannot re-call init()" ); precisionScalar = 10 ** (18 - uint256(_collateralDecimals)); collateralAsset = _collateralAddress; syntheticAsset = _syntheticAddress; borrowIndex = uint256(10**18); indexLastUpdate = currentTimestamp(); setOracle(_oracleAddress); setCollateralRatio(_collateralRatio); setInterestSetter(_interestSetter); setFees( _liquidationUserFee, _liquidationArcRatio ); }
4,056,301
./partial_match/1/0x6d51ff8B487a50Aa0456b4c244545C60DBb69b37/sources/CryptoCoasters.sol
Throws if the sender is not the owner./
function _checkOwner() internal view virtual { require(devOwner == _msgSender(), "Ownable: caller is not the owner"); }
2,747,395
./partial_match/1/0x74866AdD13f40260430832FBafEAb0aF1568edDC/sources/contracts/internal-upgradeable/ERC721BurnableUpgradeable.sol
Burns `tokenId`. See {ERC721-_burn}. Requirements: - The caller must own `tokenId` or be an approved operator./
function burn(uint256 tokenId) public virtual { if (!_isApprovedOrOwner(msg.sender, tokenId)) revert ERC721BurnableUpgradeable__NotOwnerNorApproved(); _burn(tokenId); }
9,369,605
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol"; /// @title IMockGenericIntegratee Interface /// @author Enzyme Council <[email protected]> interface IMockGenericIntegratee { function swap( address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; function swapOnBehalf( address payable, address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; } /// @title MockGenericAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Provides a generic adapter that: /// 1. Provides swapping functions that use various `SpendAssetsTransferType` values /// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`) /// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`) contract MockGenericAdapter is AdapterBase { address public immutable INTEGRATEE; // No need to specify the IntegrationManager constructor(address _integratee) public AdapterBase(address(0)) { INTEGRATEE = _integratee; } function identifier() external pure override returns (string memory) { return "MOCK_GENERIC"; } function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( spendAssets_, maxSpendAssetAmounts_, , incomingAssets_, minIncomingAssetAmounts_, ) = __decodeCallArgs(_callArgs); return ( __getSpendAssetsHandleTypeForSelector(_selector), spendAssets_, maxSpendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified function __getSpendAssetsHandleTypeForSelector(bytes4 _selector) private pure returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_) { if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Remove; } if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.None; } if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Approve; } return IIntegrationManager.SpendAssetsHandleType.Transfer; } function removeOnly( address, bytes calldata, bytes calldata ) external {} function swapA( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapB( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapDirectFromVault( address _vaultProxy, bytes calldata _callArgs, bytes calldata ) external { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); IMockGenericIntegratee(INTEGRATEE).swapOnBehalf( payable(_vaultProxy), spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } function swapViaApproval( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function __decodeCallArgs(bytes memory _callArgs) internal pure returns ( address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory actualSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_, uint256[] memory actualIncomingAssetAmounts_ ) { return abi.decode( _callArgs, (address[], uint256[], uint256[], address[], uint256[], uint256[]) ); } function __decodeCallArgsAndSwap(bytes memory _callArgs) internal { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); for (uint256 i; i < spendAssets.length; i++) { ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]); } IMockGenericIntegratee(INTEGRATEE).swap( spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring assets between /// the fund's VaultProxy and the adapter, by wrapping the adapter action. /// This modifier should be implemented in almost all adapter actions, unless they /// do not move assets or can spend and receive assets directly with the VaultProxy modifier fundAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); // Take custody of spend assets (if necessary) if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) { for (uint256 i = 0; i < spendAssets.length; i++) { ERC20(spendAssets[i]).safeTransferFrom( _vaultProxy, address(this), spendAssetAmounts[i] ); } } // Execute call _; // Transfer remaining assets back to the fund's VaultProxy __transferContractAssetBalancesToFund(_vaultProxy, incomingAssets); __transferContractAssetBalancesToFund(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper for adapters to approve their integratees with the max amount of an asset. /// Since everything is done atomically, and only the balances to-be-used are sent to adapters, /// there is no need to approve exact amounts on every call. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs) internal pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode( _encodedAssetTransferArgs, (IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[]) ); } /// @dev Helper to transfer full contract balances of assets to the specified VaultProxy function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets) private { for (uint256 i = 0; i < _assets.length; i++) { uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this)); if (postCallAmount > 0) { ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount); } } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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.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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function identifier() external pure returns (string memory identifier_); function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4( keccak256("addTrackedAssets(address,bytes,bytes)") ); // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer, Remove} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IZeroExV2.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ZeroExV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to 0xV2 Exchange Contract contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers { using AddressArrayLib for address[]; using SafeMath for uint256; event AllowedMakerAdded(address indexed account); event AllowedMakerRemoved(address indexed account); address private immutable EXCHANGE; mapping(address => bool) private makerToIsAllowed; // Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA, // for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely. constructor( address _integrationManager, address _exchange, address _fundDeployer, address[] memory _allowedMakers ) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) { EXCHANGE = _exchange; if (_allowedMakers.length > 0) { __addAllowedMakers(_allowedMakers); } } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ZERO_EX_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); require( isAllowedMaker(order.makerAddress), "parseAssetsForMethod: Order maker is not allowed" ); require( takerAssetFillAmount <= order.takerAssetAmount, "parseAssetsForMethod: Taker asset fill amount greater than available" ); address makerAsset = __getAssetAddress(order.makerAssetData); address takerAsset = __getAssetAddress(order.takerAssetData); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = makerAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = __calcRelativeQuantity( order.takerAssetAmount, order.makerAssetAmount, takerAssetFillAmount ); if (order.takerFee > 0) { address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA()); uint256 takerFeeFillAmount = __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ); // fee calculated relative to taker fill amount if (takerFeeAsset == makerAsset) { require( order.takerFee < order.makerAssetAmount, "parseAssetsForMethod: Fee greater than makerAssetAmount" ); spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount); } else if (takerFeeAsset == takerAsset) { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount); } else { spendAssets_ = new address[](2); spendAssets_[0] = takerAsset; spendAssets_[1] = takerFeeAsset; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = takerAssetFillAmount; spendAssetAmounts_[1] = takerFeeFillAmount; } } else { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Take an order on 0x /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); // Approve spend assets as needed __approveMaxAsNeeded( __getAssetAddress(order.takerAssetData), __getAssetProxy(order.takerAssetData), takerAssetFillAmount ); // Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity if (order.takerFee > 0) { bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA(); __approveMaxAsNeeded( __getAssetAddress(zrxData), __getAssetProxy(zrxData), __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ) // fee calculated relative to taker fill amount ); } // Execute order (, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs); IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature); } // PRIVATE FUNCTIONS /// @dev Parses user inputs into a ZeroExV2.Order format function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); } /// @dev Decode the parameters of a takeOrder call /// @param _encodedCallArgs Encoded parameters passed from client side /// @return encodedZeroExOrderArgs_ Encoded args of the 0x order /// @return takerAssetFillAmount_ Amount of taker asset to fill function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_) { return abi.decode(_encodedCallArgs, (bytes, uint256)); } /// @dev Decode the parameters of a 0x order /// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order /// @return orderAddresses_ Addresses used in the order /// - [0] 0x Order param: makerAddress /// - [1] 0x Order param: takerAddress /// - [2] 0x Order param: feeRecipientAddress /// - [3] 0x Order param: senderAddress /// @return orderValues_ Values used in the order /// - [0] 0x Order param: makerAssetAmount /// - [1] 0x Order param: takerAssetAmount /// - [2] 0x Order param: makerFee /// - [3] 0x Order param: takerFee /// - [4] 0x Order param: expirationTimeSeconds /// - [5] 0x Order param: salt /// @return orderData_ Bytes data used in the order /// - [0] 0x Order param: makerAssetData /// - [1] 0x Order param: takerAssetData /// @return signature_ Signature of the order function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs) private pure returns ( address[4] memory orderAddresses_, uint256[6] memory orderValues_, bytes[2] memory orderData_, bytes memory signature_ ) { return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes)); } /// @dev Parses the asset address from 0x assetData function __getAssetAddress(bytes memory _assetData) private pure returns (address assetAddress_) { assembly { assetAddress_ := mload(add(_assetData, 36)) } } /// @dev Gets the 0x assetProxy address for an ERC20 token function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) { bytes4 assetProxyId; assembly { assetProxyId := and( mload(add(_assetData, 32)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 ) } assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId); } ///////////////////////////// // ALLOWED MAKERS REGISTRY // ///////////////////////////// /// @notice Adds accounts to the list of allowed 0x order makers /// @param _accountsToAdd Accounts to add function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner { __addAllowedMakers(_accountsToAdd); } /// @notice Removes accounts from the list of allowed 0x order makers /// @param _accountsToRemove Accounts to remove function removeAllowedMakers(address[] calldata _accountsToRemove) external onlyFundDeployerOwner { require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove"); for (uint256 i; i < _accountsToRemove.length; i++) { require( isAllowedMaker(_accountsToRemove[i]), "removeAllowedMakers: Account is not an allowed maker" ); makerToIsAllowed[_accountsToRemove[i]] = false; emit AllowedMakerRemoved(_accountsToRemove[i]); } } /// @dev Helper to add accounts to the list of allowed makers function __addAllowedMakers(address[] memory _accountsToAdd) private { require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd"); for (uint256 i; i < _accountsToAdd.length; i++) { require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set"); makerToIsAllowed[_accountsToAdd[i]] = true; emit AllowedMakerAdded(_accountsToAdd[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable value /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Checks whether an account is an allowed maker of 0x orders /// @param _who The account to check /// @return isAllowedMaker_ True if _who is an allowed maker function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) { return makerToIsAllowed[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @dev Minimal interface for our interactions with the ZeroEx Exchange contract interface IZeroExV2 { struct Order { address makerAddress; address takerAddress; address feeRecipientAddress; address senderAddress; uint256 makerAssetAmount; uint256 takerAssetAmount; uint256 makerFee; uint256 takerFee; uint256 expirationTimeSeconds; uint256 salt; bytes makerAssetData; bytes takerAssetData; } struct OrderInfo { uint8 orderStatus; bytes32 orderHash; uint256 orderTakerAssetFilledAmount; } struct FillResults { uint256 makerAssetFilledAmount; uint256 takerAssetFilledAmount; uint256 makerFeePaid; uint256 takerFeePaid; } function ZRX_ASSET_DATA() external view returns (bytes memory); function filled(bytes32) external view returns (uint256); function cancelled(bytes32) external view returns (bool); function getOrderInfo(Order calldata) external view returns (OrderInfo memory); function getAssetProxy(bytes4) external view returns (address); function isValidSignature( bytes32, address, bytes calldata ) external view returns (bool); function preSign( bytes32, address, bytes calldata ) external; function cancelOrder(Order calldata) external; function fillOrder( Order calldata, uint256, bytes calldata ) external returns (FillResults memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } /// @dev Calculates a rate normalized to 10^18 precision, /// for given base and quote asset decimals and amounts function __calcNormalizedRate( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _quoteAssetAmount ) internal pure returns (uint256 normalizedRate_) { return _quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div( _baseAssetAmount.mul(10**_quoteAssetDecimals) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() external view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { enum ReleaseStatus {PreLaunch, Live, Paused} function getOwner() external view returns (address); function getReleaseStatus() external view returns (ReleaseStatus); function isRegisteredVaultCall(address, bytes4) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin { using EnumerableSet for EnumerableSet.AddressSet; event PolicyDeregistered(address indexed policy, string indexed identifier); event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); event PolicyRegistered( address indexed policy, string indexed identifier, PolicyHook[] implementedHooks ); EnumerableSet.AddressSet private registeredPolicies; mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented; mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies; modifier onlyBuySharesHooks(address _policy) { require( !policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) && !policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration), "onlyBuySharesHooks: Disallowed hook" ); _; } modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) { require( policyIsEnabledForFund(_comptrollerProxy, _policy), "onlyEnabledPolicyForFund: Policy not enabled" ); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. function activateForFund(bool _isMigratedFund) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]); } } } /// @notice Deactivates policies for a fund by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) { comptrollerProxyToPolicies[msg.sender].remove( comptrollerProxyToPolicies[msg.sender].at(i - 1) ); } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { __validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender); comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy); emit PolicyDisabledForFund(_comptrollerProxy, _policy); } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData); __activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _configData Encoded config data /// @dev Only called during init() on ComptrollerProxy deployment function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy); for (uint256 i; i < policies.length; i++) { if (!policyImplementsHook(policies[i], _hook)) { continue; } require( IPolicy(policies[i]).validateRule( _comptrollerProxy, vaultProxy, _hook, _validationData ), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund( address _comptrollerProxy, address _vaultProxy, address _policy ) private { IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData ) private { require( !policyIsEnabledForFund(_comptrollerProxy, _policy), "__enablePolicyForFund: policy already enabled" ); require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered"); // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy comptrollerProxyToPolicies[_comptrollerProxy].add(_policy); emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to validate fund owner. /// Preferred to a modifier because allows gas savings if re-using _vaultProxy. function __validateIsFundOwner(address _vaultProxy, address _who) private view { require( _who == IVault(_vaultProxy).getOwner(), "Only the fund owner can call this function" ); } /////////////////////// // POLICIES REGISTRY // /////////////////////// /// @notice Remove policies from the list of registered policies /// @param _policies Addresses of policies to be registered function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( policyIsRegistered(_policies[i]), "deregisterPolicies: policy is not registered" ); registeredPolicies.remove(_policies[i]); emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier()); } } /// @notice Add policies to the list of registered policies /// @param _policies Addresses of policies to be registered function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "registerPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( !policyIsRegistered(_policies[i]), "registerPolicies: policy already registered" ); registeredPolicies.add(_policies[i]); // Store the hooks that a policy implements for later use. // Fronts the gas for calls to check if a hook is implemented, and guarantees // that the implementsHooks return value does not change post-registration. IPolicy policyContract = IPolicy(_policies[i]); PolicyHook[] memory implementedHooks = policyContract.implementedHooks(); for (uint256 j; j < implementedHooks.length; j++) { policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true; } emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get all registered policies /// @return registeredPoliciesArray_ A list of all registered policy addresses function getRegisteredPolicies() external view returns (address[] memory registeredPoliciesArray_) { registeredPoliciesArray_ = new address[](registeredPolicies.length()); for (uint256 i; i < registeredPoliciesArray_.length; i++) { registeredPoliciesArray_[i] = registeredPolicies.at(i); } } /// @notice Get a list of enabled policies for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledPolicies_ An array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length()); for (uint256 i; i < enabledPolicies_.length; i++) { enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i); } } /// @notice Checks if a policy implements a particular hook /// @param _policy The address of the policy to check /// @param _hook The PolicyHook to check /// @return implementsHook_ True if the policy implements the hook function policyImplementsHook(address _policy, PolicyHook _hook) public view returns (bool implementsHook_) { return policyToHookToIsImplemented[_policy][_hook]; } /// @notice Check if a policy is enabled for the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund to check /// @param _policy The address of the policy to check /// @return isEnabled_ True if the policy is enabled for the fund function policyIsEnabledForFund(address _comptrollerProxy, address _policy) public view returns (bool isEnabled_) { return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy); } /// @notice Check whether a policy is registered /// @param _policy The address of the policy to check /// @return isRegistered_ True if the policy is registered function policyIsRegistered(address _policy) public view returns (bool isRegistered_) { return registeredPolicies.contains(_policy); } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/utils/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault { function addTrackedAsset(address) external; function approveAssetSpender( address, address, uint256 ) external; function burnShares(address, uint256) external; function callOnContract(address, bytes calldata) external; function getAccessor() external view returns (address); function getOwner() external view returns (address); function getTrackedAssets() external view returns (address[] memory); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function removeTrackedAsset(address) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension { mapping(address => address) internal comptrollerProxyToVaultProxy; /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund(bytes calldata) external virtual override { return; } /// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both /// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy(). /// Will revert without reason if the expected interfaces do not exist. function __setValidatedVaultProxy(address _comptrollerProxy) internal returns (address vaultProxy_) { require( comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0), "__setValidatedVaultProxy: Already set" ); vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy(); require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy"); require( _comptrollerProxy == IVault(vaultProxy_).getAccessor(), "__setValidatedVaultProxy: Not the VaultProxy accessor" ); comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_; return vaultProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings( address _comptrollerProxy, address _vaultProxy, bytes calldata _encodedSettings ) external; function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { enum PolicyHook { BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreCallOnIntegration, PostCallOnIntegration } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { enum VaultAction { None, BurnShares, MintShares, TransferShares, ApproveAssetSpender, WithdrawAssetTo, AddTrackedAsset, RemoveTrackedAsset } function activate(address, bool) external; function calcGav(bool) external returns (uint256, bool); function calcGrossShareValue(bool) external returns (uint256, bool); function callOnExtension( address, uint256, bytes calldata ) external; function configureExtensions(bytes calldata, bytes calldata) external; function destruct() external; function getDenominationAsset() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(VaultAction, bytes calldata) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _comptrollerProxy, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund(bytes calldata _configData) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address, address) external virtual override { return; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings( address, address, bytes calldata ) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPostValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns ( address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { return abi.decode( _encodedRuleArgs, (address, bytes4, address[], uint256[], address[], uint256[]) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title MaxConcentration Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that defines a configurable threshold for the concentration of any one asset /// in a fund's holdings contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase { using SafeMath for uint256; event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value); uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100% address private immutable VALUE_INTERPRETER; mapping(address => uint256) private comptrollerProxyToMaxConcentration; constructor(address _policyManager, address _valueInterpreter) public PolicyBase(_policyManager) { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @dev No need to authenticate access, as there are no state transitions function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Max concentration exceeded" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { uint256 maxConcentration = abi.decode(_encodedSettings, (uint256)); require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0"); require( maxConcentration <= ONE_HUNDRED_PERCENT, "addFundSettings: maxConcentration cannot exceed 100%" ); comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration; emit MaxConcentrationSet(_comptrollerProxy, maxConcentration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MAX_CONCENTRATION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes /// @dev The fund's denomination asset is exempt from the policy limit. function passesRule( address _comptrollerProxy, address _vaultProxy, address[] memory _assets ) public returns (bool isValid_) { uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy]; ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); address denominationAsset = comptrollerProxyContract.getDenominationAsset(); // Does not require asset finality, otherwise will fail when incoming asset is a Synth (uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false); if (!gavIsValid) { return false; } for (uint256 i = 0; i < _assets.length; i++) { address asset = _assets[i]; if ( !__rulePassesForAsset( _vaultProxy, denominationAsset, maxConcentration, totalGav, asset ) ) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); if (incomingAssets.length == 0) { return true; } return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets); } /// @dev Helper to check if the rule holds for a particular asset. /// Avoids the stack-too-deep error. function __rulePassesForAsset( address _vaultProxy, address _denominationAsset, uint256 _maxConcentration, uint256 _totalGav, address _incomingAsset ) private returns (bool isValid_) { if (_incomingAsset == _denominationAsset) return true; uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy); (uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset); if ( !assetGavIsValid || assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration ) { return false; } return true; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the maxConcentration for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return maxConcentration_ The maxConcentration function getMaxConcentrationForFund(address _comptrollerProxy) external view returns (uint256 maxConcentration_) { return comptrollerProxyToMaxConcentration[_comptrollerProxy]; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../../utils/AssetFinalityResolver.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, AssetFinalityResolver { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event MigratedSharesDuePaid(uint256 sharesDue); event OverridePauseSet(bool indexed overridePause); event PreRedeemSharesHookFailed( bytes failureReturnData, address redeemer, uint256 sharesQuantity ); event SharesBought( address indexed caller, address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, uint256 sharesQuantity, address[] receivedAssets, uint256[] receivedAssetQuantities ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant SHARES_UNIT = 10**18; address private immutable DISPATCHER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable VALUE_INTERPRETER; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Allows a fund owner to override a release-level pause bool internal overridePause; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock between any "shares actions" (i.e., buy and redeem shares), per-account uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesAction; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyActive() { __assertIsActive(vaultProxy); _; } modifier onlyNotPaused() { __assertNotPaused(); _; } modifier onlyFundDeployer() { __assertIsFundDeployer(msg.sender); _; } modifier onlyOwner() { __assertIsOwner(msg.sender); _; } modifier timelockedSharesAction(address _account) { __assertSharesActionNotTimelocked(_account); _; acctToLastSharesAction[_account] = block.timestamp; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. /// @dev Since vaultProxy is set during activate(), /// we can check that var rather than storing additional state function __assertIsActive(address _vaultProxy) private pure { require(_vaultProxy != address(0), "Fund not active"); } function __assertIsFundDeployer(address _who) private view { require(_who == FUND_DEPLOYER, "Only FundDeployer callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable"); } function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure { require(_success, string(_returnData)); } function __assertNotPaused() private view { require(!__fundIsPaused(), "Fund is paused"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _account) private view { require( block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock, "Shares action timelocked" ); } constructor( address _dispatcher, address _fundDeployer, address _valueInterpreter, address _feeManager, address _integrationManager, address _policyManager, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DISPATCHER = _dispatcher; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; POLICY_MANAGER = _policyManager; VALUE_INTERPRETER = _valueInterpreter; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction { require( _extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER, "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs); } /// @notice Sets or unsets an override on a release-wide pause /// @param _nextOverridePause True if the pause should be overrode function setOverridePause(bool _nextOverridePause) external onlyOwner { require(_nextOverridePause != overridePause, "setOverridePause: Value already set"); overridePause = _nextOverridePause; emit OverridePauseSet(_nextOverridePause); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyNotPaused onlyActive onlyOwner { require( IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector), "vaultCallOnContract: Unregistered" ); IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs)); } /// @dev Helper to check whether the release is paused, and that there is no local override function __fundIsPaused() private view returns (bool) { return IFundDeployer(FUND_DEPLOYER).getReleaseStatus() == IFundDeployer.ReleaseStatus.Paused && !overridePause; } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyNotPaused onlyActive { __assertPermissionedVaultAction(msg.sender, _action); if (_action == VaultAction.AddTrackedAsset) { __vaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __vaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __vaultActionBurnShares(_actionData); } else if (_action == VaultAction.MintShares) { __vaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __vaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __vaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __vaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view { require( permissionedVaultActionAllowed, "__assertPermissionedVaultAction: No action allowed" ); if (_caller == INTEGRATION_MANAGER) { require( _action == VaultAction.ApproveAssetSpender || _action == VaultAction.AddTrackedAsset || _action == VaultAction.RemoveTrackedAsset || _action == VaultAction.WithdrawAssetTo, "__assertPermissionedVaultAction: Not valid for IntegrationManager" ); } else if (_caller == FEE_MANAGER) { require( _action == VaultAction.BurnShares || _action == VaultAction.MintShares || _action == VaultAction.TransferShares, "__assertPermissionedVaultAction: Not valid for FeeManager" ); } else { revert("__assertPermissionedVaultAction: Not a valid actor"); } } /// @dev Helper to add a tracked asset to the fund function __vaultActionAddTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); IVault(vaultProxy).addTrackedAsset(asset); } /// @dev Helper to grant a spender an allowance for a fund's asset function __vaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).approveAssetSpender(asset, target, amount); } /// @dev Helper to burn fund shares for a particular account function __vaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).burnShares(target, amount); } /// @dev Helper to mint fund shares to a particular account function __vaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).mintShares(target, amount); } /// @dev Helper to remove a tracked asset from the fund function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); // Allowing this to fail silently makes it cheaper and simpler // for Extensions to not query for the denomination asset if (asset != denominationAsset) { IVault(vaultProxy).removeTrackedAsset(asset); } } /// @dev Helper to transfer fund shares from one account to another function __vaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).transferShares(from, to, amount); } /// @dev Helper to withdraw an asset from the VaultProxy to a given account function __vaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).withdrawAssetTo(asset, target, amount); } /////////////// // LIFECYCLE // /////////////// /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(denominationAsset == address(0), "init: Already initialized"); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Configure the extensions of a fund /// @param _feeManagerConfigData Encoded config for fees to enable /// @param _policyManagerConfigData Encoded config for policies to enable /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerLib has been deployed, /// giving access to its state and interface function configureExtensions( bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external override onlyFundDeployer { if (_feeManagerConfigData.length > 0) { IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData); } if (_policyManagerConfigData.length > 0) { IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData); } } /// @notice Activates the fund by attaching a VaultProxy and activating all Extensions /// @param _vaultProxy The VaultProxy to attach to the fund /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy); if (sharesDue > 0) { IVault(_vaultProxy).transferShares( _vaultProxy, IVault(_vaultProxy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } // Note: a future release could consider forcing the adding of a tracked asset here, // just in case a fund is migrating from an old configuration where they are not able // to remove an asset to get under the tracked assets limit IVault(_vaultProxy).addTrackedAsset(denominationAsset); // Activate extensions IExtension(FEE_MANAGER).activateForFund(_isMigration); IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration); IExtension(POLICY_MANAGER).activateForFund(_isMigration); } /// @notice Remove the config for a fund /// @dev No need to assert anything beyond FundDeployer access. /// Calling onlyNotPaused here rather than in the FundDeployer allows /// the owner to potentially override the pause and rescue unpaid fees. function destruct() external override onlyFundDeployer onlyNotPaused allowsPermissionedVaultAction { // Failsafe to protect the libs against selfdestruct require(!isLib, "destruct: Only delegate callable"); // Deactivate the extensions IExtension(FEE_MANAGER).deactivateForFund(); IExtension(INTEGRATION_MANAGER).deactivateForFund(); IExtension(POLICY_MANAGER).deactivateForFund(); // Delete storage of ComptrollerProxy // There should never be ETH in the ComptrollerLib, so no need to waste gas // to get the fund owner selfdestruct(address(0)); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @param _requireFinality True if all assets must have exact final balances settled /// @return gav_ The fund GAV /// @return isValid_ True if the conversion rates used to derive the GAV are all valid function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) { address vaultProxyAddress = vaultProxy; address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); if (assets.length == 0) { return (0, true); } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = __finalizeIfSynthAndGetAssetBalance( vaultProxyAddress, assets[i], _requireFinality ); } (gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue( assets, balances, denominationAsset ); return (gav_, isValid_); } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external override returns (uint256 grossShareValue_, bool isValid_) { uint256 gav; (gav, isValid_) = calcGav(_requireFinality); grossShareValue_ = __calcGrossShareValue( gav, ERC20(vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAsset).decimals()) ); return (grossShareValue_, isValid_); } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external onlyNotPaused locksReentrance allowsPermissionedVaultAction returns (uint256[] memory sharesReceivedAmounts_) { require(_buyers.length > 0, "buyShares: Empty _buyers"); require( _buyers.length == _investmentAmounts.length && _buyers.length == _minSharesQuantities.length, "buyShares: Unequal arrays" ); address vaultProxyCopy = vaultProxy; __assertIsActive(vaultProxyCopy); require( !IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy), "buyShares: Pending migration" ); (uint256 gav, bool gavIsValid) = calcGav(true); require(gavIsValid, "buyShares: Invalid GAV"); __buySharesSetupHook(msg.sender, _investmentAmounts, gav); address denominationAssetCopy = denominationAsset; uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); sharesReceivedAmounts_ = new uint256[](_buyers.length); for (uint256 i; i < _buyers.length; i++) { sharesReceivedAmounts_[i] = __buyShares( _buyers[i], _investmentAmounts[i], _minSharesQuantities[i], vaultProxyCopy, sharePrice, gav, denominationAssetCopy ); gav = gav.add(_investmentAmounts[i]); } __buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav); return sharesReceivedAmounts_; } /// @dev Helper to buy shares function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, address _vaultProxy, uint256 _sharePrice, uint256 _preBuySharesGav, address _denominationAsset ) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) { require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount"); // Gives Extensions a chance to run logic prior to the minting of bought shares __preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav); // Calculate the amount of shares to issue with the investment amount uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer); IVault(_vaultProxy).mintShares(_buyer, sharesIssued); // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is preferred // to have the final state of the VaultProxy prior to running __postBuySharesHook(). ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions after all __buyShares() calls are made function __buySharesCompletedHook( address _caller, uint256[] memory _sharesReceivedAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts), _gav ); } /// @dev Helper for Extension actions before any __buyShares() calls are made function __buySharesSetupHook( address _caller, uint256[] memory _investmentAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts), _gav ); } /// @dev Helper for Extension actions immediately prior to issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, uint256 _gav ) private { IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity), _gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav) ); } /// @dev Helper for Extension actions immediately after issuing shares. /// Same comment applies from __preBuySharesHook() above. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares( msg.sender, ERC20(vaultProxy).balanceOf(msg.sender), new address[](0), new address[](0) ); } /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity) private allowsPermissionedVaultAction { try IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesQuantity), 0 ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity); } } /// @dev Helper to redeem shares. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function __redeemShares( address _redeemer, uint256 _sharesQuantity, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0"); require( _additionalAssets.isUniqueSet(), "__redeemShares: _additionalAssets contains duplicates" ); require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates"); IVault vaultProxyContract = IVault(vaultProxy); // Only apply the sharesActionTimelock when a migration is not pending if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) { __assertSharesActionNotTimelocked(_redeemer); acctToLastSharesAction[_redeemer] = block.timestamp; } // When a fund is paused, settling fees will be skipped if (!__fundIsPaused()) { // Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`), // then those fee shares will be transferred from the user's balance rather // than reallocated from the sharesQuantity being redeemed. __preRedeemSharesHook(_redeemer, _sharesQuantity); } // Check the shares quantity against the user's balance after settling fees ERC20 sharesContract = ERC20(address(vaultProxyContract)); require( _sharesQuantity <= sharesContract.balanceOf(_redeemer), "__redeemShares: Insufficient shares" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( vaultProxyContract.getTrackedAssets(), _additionalAssets, _assetsToSkip ); require(payoutAssets_.length > 0, "__redeemShares: No payout assets"); // Destroy the shares. // Must get the shares supply before doing so. uint256 sharesSupply = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, _sharesQuantity); // Calculate and transfer payout asset amounts due to redeemer payoutAmounts_ = new uint256[](payoutAssets_.length); address denominationAssetCopy = denominationAsset; for (uint256 i; i < payoutAssets_.length; i++) { uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance( address(vaultProxyContract), payoutAssets_[i], true ); // If all remaining shares are being redeemed, the logic changes slightly if (_sharesQuantity == sharesSupply) { payoutAmounts_[i] = assetBalance; // Remove every tracked asset, except the denomination asset if (payoutAssets_[i] != denominationAssetCopy) { vaultProxyContract.removeTrackedAsset(payoutAssets_[i]); } } else { payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply); } // Transfer payout asset to redeemer if (payoutAmounts_[i] > 0) { vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]); } } emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_); return (payoutAssets_, payoutAmounts_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the routes for the various contracts used by all funds /// @return dispatcher_ The `DISPATCHER` variable value /// @return feeManager_ The `FEE_MANAGER` variable value /// @return fundDeployer_ The `FUND_DEPLOYER` variable value /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getLibRoutes() external view returns ( address dispatcher_, address feeManager_, address fundDeployer_, address integrationManager_, address policyManager_, address primitivePriceFeed_, address valueInterpreter_ ) { return ( DISPATCHER, FEE_MANAGER, FUND_DEPLOYER, INTEGRATION_MANAGER, POLICY_MANAGER, PRIMITIVE_PRICE_FEED, VALUE_INTERPRETER ); } /// @notice Gets the `overridePause` variable /// @return overridePause_ The `overridePause` variable value function getOverridePause() external view returns (bool overridePause_) { return overridePause; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/vault/VaultLibBase1.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase1 contract VaultLib is VaultLibBase1, IVault { using SafeERC20 for ERC20; // Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider: // 1. The highest tracked assets limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private constant TRACKED_ASSETS_LIMIT = 20; modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } ///////////// // GENERAL // ///////////// /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external { require(msg.sender == owner, "setMigrator: Only the owner can call this function"); address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /////////// // VAULT // /////////// /// @notice Adds a tracked asset to the fund /// @param _asset The asset to add /// @dev Allows addition of already tracked assets to fail silently. function addTrackedAsset(address _asset) external override onlyAccessor { if (!isTrackedAsset(_asset)) { require( trackedAssets.length < TRACKED_ASSETS_LIMIT, "addTrackedAsset: Limit exceeded" ); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @notice Grants an allowance to a spender to use the fund's asset /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function approveAssetSpender( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).approve(_target, _amount); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor { (bool success, bytes memory returnData) = _contract.call(_callData); require(success, string(returnData)); } /// @notice Removes a tracked asset from the fund /// @param _asset The asset to remove function removeTrackedAsset(address _asset) external override onlyAccessor { __removeTrackedAsset(_asset); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove an asset from a fund's tracked assets. /// Allows removal of non-tracked asset to fail silently. function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; uint256 trackedAssetsCount = trackedAssets.length; for (uint256 i = 0; i < trackedAssetsCount; i++) { if (trackedAssets[i] == _asset) { if (i < trackedAssetsCount - 1) { trackedAssets[i] = trackedAssets[trackedAssetsCount - 1]; } trackedAssets.pop(); break; } } emit TrackedAssetRemoved(_asset); } } //////////// // SHARES // //////////// /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } // ERC20 overrides /// @dev Disallows the standard ERC20 approve() function function approve(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract function symbol() public view override returns (string memory symbol_) { return IDispatcher(creator).getSharesTokenSymbol(); } /// @dev Disallows the standard ERC20 transfer() function function transfer(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @dev Disallows the standard ERC20 transferFrom() function function transferFrom( address, address, uint256 ) public override returns (bool) { revert("Unimplemented"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() external view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() external view returns (address migrator_) { return migrator; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } /// @notice Check whether an address is a tracked asset of the fund /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset of the fund function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/IPrimitivePriceFeed.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs /// @dev This contract contains several "live" value calculations, which for this release are simply /// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink) /// is immutable in this contract and only has one type of value. Including the "live" versions of /// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies) /// to explicitly define the types of values that they should (and will) be using in a future release. contract ValueInterpreter is IValueInterpreter { using SafeMath for uint256; address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED; address private immutable PRIMITIVE_PRICE_FEED; constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public { AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } // EXTERNAL FUNCTIONS /// @notice An alias of calcCanonicalAssetsTotalValue function calcLiveAssetsTotalValue( address[] calldata _baseAssets, uint256[] calldata _amounts, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset); } /// @notice An alias of calcCanonicalAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset); } // PUBLIC FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); isValid_ = true; for (uint256 i; i < _baseAssets.length; i++) { (uint256 assetValue, bool assetValueIsValid) = __calcAssetValue( _baseAssets[i], _amounts[i], _quoteAsset ); value_ = value_.add(assetValue); if (!assetValueIsValid) { isValid_ = false; } } return (value_, isValid_); } /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetValue: Unsupported _quoteAsset" ); return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } // Handle case that asset is a primitive if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue( _baseAsset, _amount, _quoteAsset ); } // Handle case that asset is a derivative address derivativePriceFeed = IAggregatedDerivativePriceFeed( AGGREGATED_DERIVATIVE_PRICE_FEED ) .getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); // Let validity be negated if any of the underlying value calculations are invalid isValid_ = true; for (uint256 i = 0; i < underlyings.length; i++) { (uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); if (!underlyingValueIsValid) { isValid_ = false; } value_ = value_.add(underlyingValue); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable /// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value function getAggregatedDerivativePriceFeed() external view returns (address aggregatedDerivativePriceFeed_) { return AGGREGATED_DERIVATIVE_PRICE_FEED; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook { Continuous, BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreRedeemShares } enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IPrimitivePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for primitive price feeds interface IPrimitivePriceFeed { function calcCanonicalValue( address, uint256, address ) external view returns (uint256, bool); function calcLiveValue( address, uint256, address ) external view returns (uint256, bool); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256, bool); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); function calcLiveAssetValue( address, uint256, address ) external returns (uint256, bool); function calcLiveAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../interfaces/ISynthetixAddressResolver.sol"; import "../interfaces/ISynthetixExchanger.sol"; /// @title AssetFinalityResolver Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that helps achieve asset finality abstract contract AssetFinalityResolver { address internal immutable SYNTHETIX_ADDRESS_RESOLVER; address internal immutable SYNTHETIX_PRICE_FEED; constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public { SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; } /// @dev Helper to finalize a Synth balance at a given target address and return its balance function __finalizeIfSynthAndGetAssetBalance( address _target, address _asset, bool _requireFinality ) internal returns (uint256 assetBalance_) { bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth( _asset ); if (currencyKey != 0) { address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER) .requireAndGetAddress( "Exchanger", "finalizeAndGetAssetBalance: Missing Exchanger" ); try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch { require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth"); } } return ERC20(_asset).balanceOf(_target); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable /// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value function getSynthetixAddressResolver() external view returns (address synthetixAddressResolver_) { return SYNTHETIX_ADDRESS_RESOLVER; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../../../../interfaces/ISynthetixAddressResolver.sol"; import "../../../../interfaces/ISynthetixExchangeRates.sol"; import "../../../../interfaces/ISynthetixProxyERC20.sol"; import "../../../../interfaces/ISynthetixSynth.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title SynthetixPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Synthetix oracles as price sources contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event SynthAdded(address indexed synth, bytes32 currencyKey); event SynthCurrencyKeyUpdated( address indexed synth, bytes32 prevCurrencyKey, bytes32 nextCurrencyKey ); uint256 private constant SYNTH_UNIT = 10**18; address private immutable ADDRESS_RESOLVER; address private immutable SUSD; mapping(address => bytes32) private synthToCurrencyKey; constructor( address _dispatcher, address _addressResolver, address _sUSD, address[] memory _synths ) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_RESOLVER = _addressResolver; SUSD = _sUSD; address[] memory sUSDSynths = new address[](1); sUSDSynths[0] = _sUSD; __addSynths(sUSDSynths); __addSynths(_synths); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = SUSD; underlyingAmounts_ = new uint256[](1); bytes32 currencyKey = getCurrencyKeyForSynth(_derivative); require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported"); address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress( "ExchangeRates", "calcUnderlyingValues: Missing ExchangeRates" ); (uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid( currencyKey ); require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid"); underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return getCurrencyKeyForSynth(_asset) != 0; } ///////////////////// // SYNTHS REGISTRY // ///////////////////// /// @notice Adds Synths to the price feed /// @param _synths Synths to add function addSynths(address[] calldata _synths) external onlyDispatcherOwner { require(_synths.length > 0, "addSynths: Empty _synths"); __addSynths(_synths); } /// @notice Updates the cached currencyKey value for specified Synths /// @param _synths Synths to update /// @dev Anybody can call this function function updateSynthCurrencyKeys(address[] calldata _synths) external { require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths"); for (uint256 i; i < _synths.length; i++) { bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]]; require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set"); bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]); require( nextCurrencyKey != prevCurrencyKey, "updateSynthCurrencyKeys: Synth has correct currencyKey" ); synthToCurrencyKey[_synths[i]] = nextCurrencyKey; emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey); } } /// @dev Helper to add Synths function __addSynths(address[] memory _synths) private { for (uint256 i; i < _synths.length; i++) { require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set"); bytes32 currencyKey = __getCurrencyKey(_synths[i]); require(currencyKey != 0, "__addSynths: No currencyKey"); synthToCurrencyKey[_synths[i]] = currencyKey; emit SynthAdded(_synths[i], currencyKey); } } /// @dev Helper to query a currencyKey from Synthetix function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) { return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_RESOLVER` variable /// @return addressResolver_ The `ADDRESS_RESOLVER` variable value function getAddressResolver() external view returns (address) { return ADDRESS_RESOLVER; } /// @notice Gets the currencyKey for multiple given Synths /// @return currencyKeys_ The currencyKey values function getCurrencyKeysForSynths(address[] calldata _synths) external view returns (bytes32[] memory currencyKeys_) { currencyKeys_ = new bytes32[](_synths.length); for (uint256 i; i < _synths.length; i++) { currencyKeys_[i] = synthToCurrencyKey[_synths[i]]; } return currencyKeys_; } /// @notice Gets the `SUSD` variable /// @return susd_ The `SUSD` variable value function getSUSD() external view returns (address susd_) { return SUSD; } /// @notice Gets the currencyKey for a given Synth /// @return currencyKey_ The currencyKey value function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) { return synthToCurrencyKey[_synth]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixAddressResolver Interface /// @author Enzyme Council <[email protected]> interface ISynthetixAddressResolver { function requireAndGetAddress(bytes32, string calldata) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchanger Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchanger { function getAmountsForExchange( uint256, bytes32, bytes32 ) external view returns ( uint256, uint256, uint256 ); function settle(address, bytes32) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetix Interface /// @author Enzyme Council <[email protected]> interface ISynthetix { function exchangeOnBehalfWithTracking( address, bytes32, uint256, bytes32, address, bytes32 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchangeRates Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchangeRates { function rateAndInvalid(bytes32) external view returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixProxyERC20 Interface /// @author Enzyme Council <[email protected]> interface ISynthetixProxyERC20 { function target() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixSynth Interface /// @author Enzyme Council <[email protected]> interface ISynthetixSynth { function currencyKey() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../persistent/dispatcher/IDispatcher.sol"; /// @title DispatcherOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of Dispatcher abstract contract DispatcherOwnerMixin { address internal immutable DISPATCHER; modifier onlyDispatcherOwner() { require( msg.sender == getOwner(), "onlyDispatcherOwner: Only the Dispatcher owner can call this function" ); _; } constructor(address _dispatcher) public { DISPATCHER = _dispatcher; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the Dispatcher contract function getOwner() public view returns (address owner_) { return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[email protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. function __approve( address _owner, address _spender, uint256 _amount ) internal virtual { require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. function __transfer( address _sender, address _recipient, uint256 _amount ) internal virtual { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed { function getPriceFeedForDerivative(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IUniswapV2Pair.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../../../value-interpreter/ValueInterpreter.sol"; import "../../primitives/IPrimitivePriceFeed.sol"; import "../../utils/UniswapV2PoolTokenValueCalculator.sol"; import "../IDerivativePriceFeed.sol"; /// @title UniswapV2PoolPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Uniswap lending pool tokens contract UniswapV2PoolPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin, MathHelpers, UniswapV2PoolTokenValueCalculator { event PoolTokenAdded(address indexed poolToken, address token0, address token1); struct PoolTokenInfo { address token0; address token1; uint8 token0Decimals; uint8 token1Decimals; } uint256 private constant POOL_TOKEN_UNIT = 10**18; address private immutable DERIVATIVE_PRICE_FEED; address private immutable FACTORY; address private immutable PRIMITIVE_PRICE_FEED; address private immutable VALUE_INTERPRETER; mapping(address => PoolTokenInfo) private poolTokenToInfo; constructor( address _dispatcher, address _derivativePriceFeed, address _primitivePriceFeed, address _valueInterpreter, address _factory, address[] memory _poolTokens ) public DispatcherOwnerMixin(_dispatcher) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; FACTORY = _factory; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; VALUE_INTERPRETER = _valueInterpreter; __addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative]; underlyings_ = new address[](2); underlyings_[0] = poolTokenInfo.token0; underlyings_[1] = poolTokenInfo.token1; // Calculate the amounts underlying one unit of a pool token, // taking into account the known, trusted rate between the two underlyings (uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate( poolTokenInfo.token0, poolTokenInfo.token1, poolTokenInfo.token0Decimals, poolTokenInfo.token1Decimals ); ( uint256 token0DenormalizedRate, uint256 token1DenormalizedRate ) = __calcTrustedPoolTokenValue( FACTORY, _derivative, token0TrustedRateAmount, token1TrustedRateAmount ); // Define normalized rates for each underlying underlyingAmounts_ = new uint256[](2); underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT); underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return poolTokenToInfo[_asset].token0 != address(0); } // PRIVATE FUNCTIONS /// @dev Calculates the trusted rate of two assets based on our price feeds. /// Uses the decimals-derived unit for whichever asset is used as the quote asset. function __calcTrustedRate( address _token0, address _token1, uint256 _token0Decimals, uint256 _token1Decimals ) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) { bool rateIsValid; // The quote asset of the value lookup must be a supported primitive asset, // so we cycle through the tokens until reaching a primitive. // If neither is a primitive, will revert at the ValueInterpreter if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) { token1RateAmount_ = 10**_token1Decimals; (token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token1, token1RateAmount_, _token0); } else { token0RateAmount_ = 10**_token0Decimals; (token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token0, token0RateAmount_, _token1); } require(rateIsValid, "__calcTrustedRate: Invalid rate"); return (token0RateAmount_, token1RateAmount_); } ////////////////////////// // POOL TOKENS REGISTRY // ////////////////////////// /// @notice Adds Uniswap pool tokens to the price feed /// @param _poolTokens Uniswap pool tokens to add function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner { require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens"); __addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED); } /// @dev Helper to add Uniswap pool tokens function __addPoolTokens( address[] memory _poolTokens, address _derivativePriceFeed, address _primitivePriceFeed ) private { for (uint256 i; i < _poolTokens.length; i++) { require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken"); require( poolTokenToInfo[_poolTokens[i]].token0 == address(0), "__addPoolTokens: Value already set" ); IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]); address token0 = uniswapV2Pair.token0(); address token1 = uniswapV2Pair.token1(); require( __poolTokenIsSupportable( _derivativePriceFeed, _primitivePriceFeed, token0, token1 ), "__addPoolTokens: Unsupported pool token" ); poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({ token0: token0, token1: token1, token0Decimals: ERC20(token0).decimals(), token1Decimals: ERC20(token1).decimals() }); emit PoolTokenAdded(_poolTokens[i], token0, token1); } } /// @dev Helper to determine if a pool token is supportable, based on whether price feeds are /// available for its underlying feeds. At least one of the underlying tokens must be /// a supported primitive asset, and the other must be a primitive or derivative. function __poolTokenIsSupportable( address _derivativePriceFeed, address _primitivePriceFeed, address _token0, address _token1 ) private view returns (bool isSupportable_) { IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed( _derivativePriceFeed ); IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed); if (primitivePriceFeedContract.isSupportedAsset(_token0)) { if ( primitivePriceFeedContract.isSupportedAsset(_token1) || derivativePriceFeedContract.isSupportedAsset(_token1) ) { return true; } } else if ( derivativePriceFeedContract.isSupportedAsset(_token0) && primitivePriceFeedContract.isSupportedAsset(_token1) ) { return true; } return false; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } } } return ( _reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply), _reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply) ); } /// @dev Calculates the direction and magnitude of the profit-maximizing trade function __calcProfitMaximizingTrade( uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount, uint256 _reserve0, uint256 _reserve1 ) private pure returns (bool token0ToToken1_, uint256 amountIn_) { token0ToToken1_ = _reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount; uint256 leftSide; uint256 rightSide; if (token0ToToken1_) { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div( _token1TrustedRateAmount.mul(997) ) ); rightSide = _reserve0.mul(1000).div(997); } else { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div( _token0TrustedRateAmount.mul(997) ) ); rightSide = _reserve1.mul(1000).div(997); } if (leftSide < rightSide) { return (false, 0); } // Calculate the amount that must be sent to move the price to the profit-maximizing price amountIn_ = leftSide.sub(rightSide); return (token0ToToken1_, amountIn_); } /// @dev Calculates the pool reserves after an arbitrage moves the price to /// the profit-maximizing rate, given an externally-observed trusted rate /// between the two pooled assets function __calcReservesAfterArbitrage( address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) private view returns (uint256 reserve0_, uint256 reserve1_) { (reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves(); // Skip checking whether the reserve is 0, as this is extremely unlikely given how // initial pool liquidity is locked, and since we maintain a list of registered pool tokens // Calculate how much to swap to arb to the trusted price (bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade( _token0TrustedRateAmount, _token1TrustedRateAmount, reserve0_, reserve1_ ); if (amountIn == 0) { return (reserve0_, reserve1_); } // Adjust the reserves to account for the arb trade to the trusted price if (token0ToToken1) { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_); reserve0_ = reserve0_.add(amountIn); reserve1_ = reserve1_.sub(amountOut); } else { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_); reserve1_ = reserve1_.add(amountIn); reserve0_ = reserve0_.sub(amountOut); } return (reserve0_, reserve1_); } /// @dev Uniswap square root function. See: /// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) { if (_y > 3) { z_ = _y; uint256 x = _y / 2 + 1; while (x < z_) { z_ = x; x = (_y / x + x) / 2; } } else if (_y != 0) { z_ = 1; } // else z_ = 0 return z_; } /// @dev Simplified version of UniswapV2Library's getAmountOut() function. See: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50 function __uniswapV2GetAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut ) private pure returns (uint256 amountOut_) { uint256 amountInWithFee = _amountIn.mul(997); uint256 numerator = amountInWithFee.mul(_reserveOut); uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee); return numerator.div(denominator); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Factory Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract interface IUniswapV2Factory { function feeTo() external view returns (address); function getPair(address, address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IChainlinkAggregator.sol"; import "../../../../utils/MakerDaoMath.sol"; import "../IDerivativePriceFeed.sol"; /// @title WdgldPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for WDGLD <https://dgld.ch/> contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath { using SafeMath for uint256; address private immutable XAU_AGGREGATOR; address private immutable ETH_AGGREGATOR; address private immutable WDGLD; address private immutable WETH; // GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas uint256 private constant GTR_CONSTANT = 999990821653213975346065101; uint256 private constant GTR_PRECISION = 10**27; uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000; constructor( address _wdgld, address _weth, address _ethAggregator, address _xauAggregator ) public { WDGLD = _wdgld; WETH = _weth; ETH_AGGREGATOR = _ethAggregator; XAU_AGGREGATOR = _xauAggregator; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH; underlyingAmounts_ = new uint256[](1); // Get price rates from xau and eth aggregators int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer(); int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer(); require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid"); uint256 wdgldToXauRate = calcWdgldToXauRate(); // 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION underlyingAmounts_[0] = _derivativeAmount .mul(wdgldToXauRate) .mul(uint256(xauToUsdRate)) .div(uint256(ethToUsdRate)) .div(10**17); return (underlyings_, underlyingAmounts_); } /// @notice Calculates the rate of WDGLD to XAU. /// @return wdgldToXauRate_ The current rate of WDGLD to XAU /// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf> function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) { return __rpow( GTR_CONSTANT, ((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods) GTR_PRECISION ) .div(10); } /// @notice Checks if an asset is supported by this price feed /// @param _asset The asset to check /// @return isSupported_ True if supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == WDGLD; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ETH_AGGREGATOR` address /// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address function getEthAggregator() external view returns (address ethAggregatorAddress_) { return ETH_AGGREGATOR; } /// @notice Gets the `WDGLD` token address /// @return wdgld_ The `WDGLD` token address function getWdgld() external view returns (address wdgld_) { return WDGLD; } /// @notice Gets the `WETH` token address /// @return weth_ The `WETH` token address function getWeth() external view returns (address weth_) { return WETH; } /// @notice Gets the `XAU_AGGREGATOR` address /// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address function getXauAggregator() external view returns (address xauAggregatorAddress_) { return XAU_AGGREGATOR; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.12; /// @title MakerDaoMath Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for math operations adapted from MakerDao contracts abstract contract MakerDaoMath { /// @dev Performs scaled, fixed-point exponentiation. /// Verbatim code, adapted to our style guide for variable naming only, see: /// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105 // prettier-ignore function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) { assembly { switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}} default { switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x } let half := div(_base, 2) for { _n := div(_n, 2) } _n { _n := div(_n,2) } { let xx := mul(_x, _x) if iszero(eq(div(xx, _x), _x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } _x := div(xxRound, _base) if mod(_n,2) { let zx := mul(z_, _x) if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z_ := div(zxRound, _base) } } } } return z_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../core/fund/vault/VaultLib.sol"; import "../../../utils/MakerDaoMath.sol"; import "./utils/FeeBase.sol"; /// @title ManagementFee Contract /// @author Enzyme Council <[email protected]> /// @notice A management fee with a configurable annual rate contract ManagementFee is FeeBase, MakerDaoMath { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate); event Settled( address indexed comptrollerProxy, uint256 sharesQuantity, uint256 secondsSinceSettlement ); struct FeeInfo { uint256 scaledPerSecondRate; uint256 lastSettled; } uint256 private constant RATE_SCALE_BASE = 10**27; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyFeeManager { // It is only necessary to set `lastSettled` for a migrated fund if (VaultLib(_vaultProxy).totalSupply() > 0) { comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; } } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the fee for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256)); require( scaledPerSecondRate > 0, "addFundSettings: scaledPerSecondRate must be greater than 0" ); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ scaledPerSecondRate: scaledPerSecondRate, lastSettled: 0 }); emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "MANAGEMENT"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settle the fee and calculate shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // If this fee was settled in the current block, we can return early uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled); if (secondsSinceSettlement == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } // If there are shares issued for the fund, calculate the shares due VaultLib vaultProxyContract = VaultLib(_vaultProxy); uint256 sharesSupply = vaultProxyContract.totalSupply(); if (sharesSupply > 0) { // This assumes that all shares in the VaultProxy are shares outstanding, // which is fine for this release. Even if they are not, they are still shares that // are only claimable by the fund owner. uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy)); if (netSharesSupply > 0) { sharesDue_ = netSharesSupply .mul( __rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE) .sub(RATE_SCALE_BASE) ) .div(RATE_SCALE_BASE); } } // Must settle even when no shares are due, for the case that settlement is being // done when there are no shares in the fund (i.e. at the first investment, or at the // first investment after all shares have been redeemed) comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } return (IFeeManager.SettlementType.Mint, address(0), sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IFee.sol"; /// @title FeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all fees abstract contract FeeBase is IFee { address internal immutable FEE_MANAGER; modifier onlyFeeManager { require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call"); _; } constructor(address _feeManager) public { FEE_MANAGER = _feeManager; } /// @notice Allows Fee to run logic during fund activation /// @dev Unimplemented by default, may be overrode. function activateForFund(address, address) external virtual override { return; } /// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type /// @dev Returns false by default, can be overridden by fee function payout(address, address) external virtual override returns (bool) { return false; } /// @notice Update fee state after all settlement has occurred during a given fee hook /// @dev Unimplemented by default, can be overridden by fee function update( address, address, IFeeManager.FeeHook, bytes calldata, uint256 ) external virtual override { return; } /// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook function __decodePreBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook function __decodePreRedeemSharesSettlementData(bytes memory _settlementData) internal pure returns (address redeemer_, uint256 sharesQuantity_) { return abi.decode(_settlementData, (address, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook function __decodePostBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesBought_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IFeeManager.sol"; /// @title Fee Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all fees interface IFee { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ); function payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../core/fund/comptroller/ComptrollerLib.sol"; import "../FeeManager.sol"; import "./utils/FeeBase.sol"; /// @title PerformanceFee Contract /// @author Enzyme Council <[email protected]> /// @notice A performance-based fee with configurable rate and crystallization period, using /// a high watermark /// @dev This contract assumes that all shares in the VaultProxy are shares outstanding, /// which is fine for this release. Even if they are not, they are still shares that /// are only claimable by the fund owner. contract PerformanceFee is FeeBase { using SafeMath for uint256; using SignedSafeMath for int256; event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark); event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period); event LastSharePriceUpdated( address indexed comptrollerProxy, uint256 prevSharePrice, uint256 nextSharePrice ); event PaidOut( address indexed comptrollerProxy, uint256 prevHighWaterMark, uint256 nextHighWaterMark, uint256 aggregateValueDue ); event PerformanceUpdated( address indexed comptrollerProxy, uint256 prevAggregateValueDue, uint256 nextAggregateValueDue, int256 sharesOutstandingDiff ); struct FeeInfo { uint256 rate; uint256 period; uint256 activated; uint256 lastPaid; uint256 highWaterMark; uint256 lastSharePrice; uint256 aggregateValueDue; } uint256 private constant RATE_DIVISOR = 10**18; uint256 private constant SHARE_UNIT = 10**18; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // We must not force asset finality, otherwise funds that have Synths as tracked assets // would be susceptible to a DoS attack when attempting to migrate to a release that uses // this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy // as the recipient, thus causing `calcGrossShareValue(true)` to fail. (uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy) .calcGrossShareValue(false); require(sharePriceIsValid, "activateForFund: Invalid share price"); feeInfo.highWaterMark = grossSharePrice; feeInfo.lastSharePrice = grossSharePrice; feeInfo.activated = block.timestamp; emit ActivatedForFund(_comptrollerProxy, grossSharePrice); } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for the fund /// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { (uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256)); require(feeRate > 0, "addFundSettings: feeRate must be greater than 0"); require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0"); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ rate: feeRate, period: feePeriod, activated: 0, lastPaid: 0, highWaterMark: 0, lastSharePrice: 0, aggregateValueDue: 0 }); emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "PERFORMANCE"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3); implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted; implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true); } /// @notice Checks whether the shares outstanding for the fee can be paid out, and updates /// the info for the fee's last payout /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return isPayable_ True if shares outstanding can be paid out function payout(address _comptrollerProxy, address) external override onlyFeeManager returns (bool isPayable_) { if (!payoutAllowed(_comptrollerProxy)) { return false; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; feeInfo.lastPaid = block.timestamp; uint256 prevHighWaterMark = feeInfo.highWaterMark; uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark); uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; // Update state as necessary if (prevAggregateValueDue > 0) { feeInfo.aggregateValueDue = 0; } if (nextHighWaterMark > prevHighWaterMark) { feeInfo.highWaterMark = nextHighWaterMark; } emit PaidOut( _comptrollerProxy, prevHighWaterMark, nextHighWaterMark, prevAggregateValueDue ); return true; } /// @notice Settles the fee and calculates shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _gav The GAV of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 _gav ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { if (_gav == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } int256 settlementSharesDue = __settleAndUpdatePerformance( _comptrollerProxy, _vaultProxy, _gav ); if (settlementSharesDue == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } else if (settlementSharesDue > 0) { // Settle by minting shares outstanding for custody return ( IFeeManager.SettlementType.MintSharesOutstanding, address(0), uint256(settlementSharesDue) ); } else { // Settle by burning from shares outstanding return ( IFeeManager.SettlementType.BurnSharesOutstanding, address(0), uint256(-settlementSharesDue) ); } } /// @notice Updates the fee state after all fees have finished settle() /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _hook The FeeHook being executed /// @param _settlementData Encoded args to use in calculating the settlement /// @param _gav The GAV of the fund function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override onlyFeeManager { uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice; uint256 nextSharePrice = __calcNextSharePrice( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (nextSharePrice == prevSharePrice) { return; } comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice; emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice); } // PUBLIC FUNCTIONS /// @notice Checks whether the shares outstanding can be paid out /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return payoutAllowed_ True if the fee payment is due /// @dev Payout is allowed if fees have not yet been settled in a crystallization period, /// and at least 1 crystallization period has passed since activation function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) { FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 period = feeInfo.period; uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated); // Check if at least 1 crystallization period has passed since activation if (timeSinceActivated < period) { return false; } // Check that a full crystallization period has passed since the last payout uint256 timeSincePeriodStart = timeSinceActivated % period; uint256 periodStart = block.timestamp.sub(timeSincePeriodStart); return feeInfo.lastPaid < periodStart; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the aggregated value accumulated to a fund since the last /// settlement (happening at investment/redemption) /// Validated: /// _netSharesSupply > 0 /// _sharePriceWithoutPerformance != _prevSharePrice function __calcAggregateValueDue( uint256 _netSharesSupply, uint256 _sharePriceWithoutPerformance, uint256 _prevSharePrice, uint256 _prevAggregateValueDue, uint256 _feeRate, uint256 _highWaterMark ) private pure returns (uint256) { int256 superHWMValueSinceLastSettled = ( int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub( int256(__calcUint256Max(_highWaterMark, _prevSharePrice)) ) ) .mul(int256(_netSharesSupply)) .div(int256(SHARE_UNIT)); int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div( int256(RATE_DIVISOR) ); return uint256( __calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled)) ); } /// @dev Helper to calculate the max of two int values function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to calculate the next `lastSharePrice` value function __calcNextSharePrice( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private view returns (uint256 nextSharePrice_) { uint256 denominationAssetUnit = 10 ** uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals()); if (_gav == 0) { return denominationAssetUnit; } // Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply ERC20 vaultProxyContract = ERC20(_vaultProxy); uint256 totalSharesSupply = vaultProxyContract.totalSupply(); uint256 nextNetSharesSupply = totalSharesSupply.sub( vaultProxyContract.balanceOf(_vaultProxy) ); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } uint256 nextGav = _gav; // For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change, // we only need additional calculations for PreRedeemShares if (_hook == IFeeManager.FeeHook.PreRedeemShares) { (, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData); // Shares have not yet been burned nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } // Assets have not yet been withdrawn uint256 gavDecrease = sharesDecrease .mul(_gav) .mul(SHARE_UNIT) .div(totalSharesSupply) .div(denominationAssetUnit); nextGav = nextGav.sub(gavDecrease); if (nextGav == 0) { return denominationAssetUnit; } } return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply); } /// @dev Helper to calculate the performance metrics for a fund. /// Validated: /// _totalSharesSupply > 0 /// _gav > 0 /// _totalSharesSupply != _totalSharesOutstanding function __calcPerformance( address _comptrollerProxy, uint256 _totalSharesSupply, uint256 _totalSharesOutstanding, uint256 _prevAggregateValueDue, FeeInfo memory feeInfo, uint256 _gav ) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) { // Use the 'shares supply net shares outstanding' for performance calcs. // Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding); uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply); // If gross share price has not changed, can exit early uint256 prevSharePrice = feeInfo.lastSharePrice; if (sharePriceWithoutPerformance == prevSharePrice) { return (_prevAggregateValueDue, 0); } nextAggregateValueDue_ = __calcAggregateValueDue( netSharesSupply, sharePriceWithoutPerformance, prevSharePrice, _prevAggregateValueDue, feeInfo.rate, feeInfo.highWaterMark ); sharesDue_ = __calcSharesDue( _comptrollerProxy, netSharesSupply, _gav, nextAggregateValueDue_ ); return (nextAggregateValueDue_, sharesDue_); } /// @dev Helper to calculate sharesDue during settlement. /// Validated: /// _netSharesSupply > 0 /// _gav > 0 function __calcSharesDue( address _comptrollerProxy, uint256 _netSharesSupply, uint256 _gav, uint256 _nextAggregateValueDue ) private view returns (int256 sharesDue_) { // If _nextAggregateValueDue > _gav, then no shares can be created. // This is a known limitation of the model, which is only reached for unrealistically // high performance fee rates (> 100%). A revert is allowed in such a case. uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div( _gav.sub(_nextAggregateValueDue) ); // Shares due is the +/- diff or the total shares outstanding already minted return int256(sharesDueForAggregateValueDue).sub( int256( FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund( _comptrollerProxy, address(this) ) ) ); } /// @dev Helper to calculate the max of two uint values function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to settle the fee and update performance state. /// Validated: /// _gav > 0 function __settleAndUpdatePerformance( address _comptrollerProxy, address _vaultProxy, uint256 _gav ) private returns (int256 sharesDue_) { ERC20 sharesTokenContract = ERC20(_vaultProxy); uint256 totalSharesSupply = sharesTokenContract.totalSupply(); if (totalSharesSupply == 0) { return 0; } uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy); if (totalSharesOutstanding == totalSharesSupply) { return 0; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; uint256 nextAggregateValueDue; (nextAggregateValueDue, sharesDue_) = __calcPerformance( _comptrollerProxy, totalSharesSupply, totalSharesOutstanding, prevAggregateValueDue, feeInfo, _gav ); if (nextAggregateValueDue == prevAggregateValueDue) { return 0; } // Update fee state feeInfo.aggregateValueDue = nextAggregateValueDue; emit PerformanceUpdated( _comptrollerProxy, prevAggregateValueDue, nextAggregateValueDue, sharesDue_ ); return sharesDue_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _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; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages fees for funds contract FeeManager is IFeeManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AllSharesOutstandingForcePaidForFund( address indexed comptrollerProxy, address payee, uint256 sharesDue ); event FeeDeregistered(address indexed fee, string indexed identifier); event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); event FeeRegistered( address indexed fee, string indexed identifier, FeeHook[] implementedHooksForSettle, FeeHook[] implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ); event FeeSettledForFund( address indexed comptrollerProxy, address indexed fee, SettlementType indexed settlementType, address payer, address payee, uint256 sharesDue ); event SharesOutstandingPaidForFund( address indexed comptrollerProxy, address indexed fee, uint256 sharesDue ); event FeesRecipientSetForFund( address indexed comptrollerProxy, address prevFeesRecipient, address nextFeesRecipient ); EnumerableSet.AddressSet private registeredFees; mapping(address => bool) private feeToUsesGavOnSettle; mapping(address => bool) private feeToUsesGavOnUpdate; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate; mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); address[] memory enabledFees = comptrollerProxyToFees[msg.sender]; for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev msg.sender is validated during __invokeHook() function deactivateForFund() external override { // Settle continuous fees one last time, but without calling Fee.update() __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false); // Force payout of remaining shares outstanding __forcePayoutAllSharesOutstanding(msg.sender); // Clean up storage __deleteFundStorage(msg.sender); } /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _actionId An ID representing the desired action /// @param _callArgs Encoded arguments specific to the _actionId /// @dev This is the only way to call a function on this contract that updates VaultProxy state. /// For both of these actions, any caller is allowed, so we don't use the caller param. function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { // Settle and update all continuous fees __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); } else if (_actionId == 1) { __payoutSharesOutstandingForFees(msg.sender, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @notice Enable and configure fees for use in the calling fund /// @param _configData Encoded config data /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. /// The order of `fees` determines the order in which fees of the same FeeHook will be applied. /// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise /// PerformanceFee calcs. function setConfigForFund(bytes calldata _configData) external override { (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity checks require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); // Enable each fee with settings for (uint256 i; i < fees.length; i++) { require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered"); // Set fund config on fee IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[msg.sender].push(fees[i]); emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]); } } /// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic /// @param _hook The FeeHook to invoke /// @param _settlementData The encoded settlement parameters specific to the FeeHook /// @param _gav The GAV for a fund if known in the invocating code, otherwise 0 function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } // PRIVATE FUNCTIONS /// @dev Helper to destroy local storage to get gas refund, /// and to prevent further calls to fee manager function __deleteFundStorage(address _comptrollerProxy) private { delete comptrollerProxyToFees[_comptrollerProxy]; delete comptrollerProxyToVaultProxy[_comptrollerProxy]; } /// @dev Helper to force the payout of shares outstanding across all fees. /// For the current release, all shares in the VaultProxy are assumed to be /// shares outstanding from fees. If not, then they were sent there by mistake /// and are otherwise unrecoverable. We can therefore take the VaultProxy's /// shares balance as the totalSharesOutstanding to payout to the fund owner. function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy); if (totalSharesOutstanding == 0) { return; } // Destroy any shares outstanding storage address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; for (uint256 i; i < fees.length; i++) { delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; } // Distribute all shares outstanding to the fees recipient address payee = IVault(vaultProxy).getOwner(); __transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding); emit AllSharesOutstandingForcePaidForFund( _comptrollerProxy, payee, totalSharesOutstanding ); } /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary( address _comptrollerProxy, address _fee, uint256 _gavOrZero ) private returns (uint256 gav_) { if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) { // Assumes that any fee that requires GAV would need to revert if invalid or not final bool gavIsValid; (gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true); require(gavIsValid, "__getGavAsNecessary: Invalid GAV"); } else { gav_ = _gavOrZero; } return gav_; } /// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to /// optionally run update() on the same fees. This order allows fees an opportunity to update /// their local state after all VaultProxy state transitions (i.e., minting, burning, /// transferring shares) have finished. To optimize for the expensive operation of calculating /// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees. /// Assumes that _gav is either 0 or has already been validated. function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); // This check isn't strictly necessary, but its cost is insignificant, // and helps to preserve data integrity. require(vaultProxy != address(0), "__invokeHook: Fund is not active"); // First, allow all fees to implement settle() uint256 gav = __settleFees( _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); // Second, allow fees to implement update() // This function does not allow any further altering of VaultProxy state // (i.e., burning, minting, or transferring shares) if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } /// @dev Helper to payout the shares outstanding for the specified fees. /// Does not call settle() on fees. /// Only callable via ComptrollerProxy.callOnExtension(). function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); uint256 sharesOutstandingDue; for (uint256 i; i < fees.length; i++) { if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { continue; } uint256 sharesOutstandingForFee = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; if (sharesOutstandingForFee == 0) { continue; } sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee); // Delete shares outstanding and distribute from VaultProxy to the fees recipient comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0; emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee); } if (sharesOutstandingDue > 0) { __transferShares( _comptrollerProxy, vaultProxy, IVault(vaultProxy).getOwner(), sharesOutstandingDue ); } } /// @dev Helper to settle a fee function __settleFee( address _comptrollerProxy, address _vaultProxy, address _fee, FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private { (SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (settlementType == SettlementType.None) { return; } address payee; if (settlementType == SettlementType.Direct) { payee = IVault(_vaultProxy).getOwner(); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = IVault(_vaultProxy).getOwner(); __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.Burn) { __burnShares(_comptrollerProxy, payer, sharesDue); } else if (settlementType == SettlementType.MintSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.BurnSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); } else { revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } /// @dev Helper to settle fees that implement a given fee hook function __settleFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private returns (uint256 gav_) { gav_ = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeSettlesOnHook(_fees[i], _hook)) { continue; } gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_); __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } /// @dev Helper to update fees that implement a given fee hook function __updateFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private { uint256 gav = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeUpdatesOnHook(_fees[i], _hook)) { continue; } gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav); IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // FEES REGISTRY // /////////////////// /// @notice Remove fees from the list of registered fees /// @param _fees Addresses of fees to be deregistered function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "deregisterFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered"); registeredFees.remove(_fees[i]); emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier()); } } /// @notice Add fees to the list of registered fees /// @param _fees Addresses of fees to be registered /// @dev Stores the hooks that a fee implements and whether each implementation uses GAV, /// which fronts the gas for calls to check if a hook is implemented, and guarantees /// that these hook implementation return values do not change post-registration. function registerFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "registerFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered"); registeredFees.add(_fees[i]); IFee feeContract = IFee(_fees[i]); ( FeeHook[] memory implementedHooksForSettle, FeeHook[] memory implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ) = feeContract.implementedHooks(); // Stores the hooks for which each fee implements settle() and update() for (uint256 j; j < implementedHooksForSettle.length; j++) { feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true; } for (uint256 j; j < implementedHooksForUpdate.length; j++) { feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true; } // Stores whether each fee requires GAV during its implementations for settle() and update() if (usesGavOnSettle) { feeToUsesGavOnSettle[_fees[i]] = true; } if (usesGavOnUpdate) { feeToUsesGavOnUpdate[_fees[i]] = true; } emit FeeRegistered( _fees[i], feeContract.identifier(), implementedHooksForSettle, implementedHooksForUpdate, usesGavOnSettle, usesGavOnUpdate ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled fees for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledFees_ An array of enabled fee addresses function getEnabledFeesForFund(address _comptrollerProxy) external view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } /// @notice Get the amount of shares outstanding for a particular fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fee The fee address /// @return sharesOutstanding_ The amount of shares outstanding function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) external view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } /// @notice Get all registered fees /// @return registeredFees_ A list of all registered fee addresses function getRegisteredFees() external view returns (address[] memory registeredFees_) { registeredFees_ = new address[](registeredFees.length()); for (uint256 i; i < registeredFees_.length; i++) { registeredFees_[i] = registeredFees.at(i); } return registeredFees_; } /// @notice Checks if a fee implements settle() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return settlesOnHook_ True if the fee settles on the given hook function feeSettlesOnHook(address _fee, FeeHook _hook) public view returns (bool settlesOnHook_) { return feeToHookToImplementsSettle[_fee][_hook]; } /// @notice Checks if a fee implements update() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return updatesOnHook_ True if the fee updates on the given hook function feeUpdatesOnHook(address _fee, FeeHook _hook) public view returns (bool updatesOnHook_) { return feeToHookToImplementsUpdate[_fee][_hook]; } /// @notice Checks if a fee uses GAV in its settle() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during settle() implementation function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnSettle[_fee]; } /// @notice Checks if a fee uses GAV in its update() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during update() implementation function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnUpdate[_fee]; } /// @notice Check whether a fee is registered /// @param _fee The address of the fee to check /// @return isRegisteredFee_ True if the fee is registered function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) { return registeredFees.contains(_fee); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; /// @title PermissionedVaultActionMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for extensions that can make permissioned vault calls abstract contract PermissionedVaultActionMixin { /// @notice Adds a tracked asset to the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.AddTrackedAsset, abi.encode(_asset) ); } /// @notice Grants an allowance to a spender to use a fund's asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function __approveAssetSpender( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.ApproveAssetSpender, abi.encode(_asset, _target, _amount) ); } /// @notice Burns fund shares for a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function __burnShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Mints fund shares to a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account to which to mint shares /// @param _amount The amount of shares to mint function __mintShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes a tracked asset from the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.RemoveTrackedAsset, abi.encode(_asset) ); } /// @notice Transfers fund shares from one account to another /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function __transferShares( address _comptrollerProxy, address _from, address _to, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.TransferShares, abi.encode(_from, _to, _amount) ); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function __withdrawAssetTo( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.WithdrawAssetTo, abi.encode(_asset, _target, _amount) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IWETH.sol"; import "../core/fund/comptroller/ComptrollerLib.sol"; import "../extensions/fee-manager/FeeManager.sol"; /// @title FundActionsWrapper Contract /// @author Enzyme Council <[email protected]> /// @notice Logic related to wrapping fund actions, not necessary in the core protocol contract FundActionsWrapper { using SafeERC20 for ERC20; address private immutable FEE_MANAGER; address private immutable WETH_TOKEN; mapping(address => bool) private accountToHasMaxWethAllowance; constructor(address _feeManager, address _weth) public { FEE_MANAGER = _feeManager; WETH_TOKEN = _weth; } /// @dev Needed in case WETH not fully used during exchangeAndBuyShares, /// to unwrap into ETH and refund receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return netShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Accounts for fees outstanding. This is a convenience function for external consumption /// that can be used to determine the cost of purchasing shares at any given point in time. /// It essentially just bundles settling all fees that implement the Continuous hook and then /// looking up the gross share value. function calcNetShareValueForFund(address _comptrollerProxy) external returns (uint256 netShareValue_, bool isValid_) { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); return comptrollerProxyContract.calcGrossShareValue(false); } /// @notice Exchanges ETH into a fund's denomination asset and then buys shares /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _buyer The account for which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH /// @param _exchange The exchange on which to execute the swap to the denomination asset /// @param _exchangeApproveTarget The address that should be given an allowance of WETH /// for the given _exchange /// @param _exchangeData The data with which to call the exchange to execute the swap /// to the denomination asset /// @param _minInvestmentAmount The minimum amount of the denomination asset /// to receive in the trade for investment (not necessary for WETH) /// @return sharesReceivedAmount_ The actual amount of shares received /// @dev Use a reasonable _minInvestmentAmount always, in case the exchange /// does not perform as expected (low incoming asset amount, blend of assets, etc). /// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData, /// and _minInvestmentAmount will be ignored. function exchangeAndBuyShares( address _comptrollerProxy, address _denominationAsset, address _buyer, uint256 _minSharesQuantity, address _exchange, address _exchangeApproveTarget, bytes calldata _exchangeData, uint256 _minInvestmentAmount ) external payable returns (uint256 sharesReceivedAmount_) { // Wrap ETH into WETH IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}(); // If denominationAsset is WETH, can just buy shares directly if (_denominationAsset == WETH_TOKEN) { __approveMaxWethAsNeeded(_comptrollerProxy); return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity); } // Exchange ETH to the fund's denomination asset __approveMaxWethAsNeeded(_exchangeApproveTarget); (bool success, bytes memory returnData) = _exchange.call(_exchangeData); require(success, string(returnData)); // Confirm the amount received in the exchange is above the min acceptable amount uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this)); require( investmentAmount >= _minInvestmentAmount, "exchangeAndBuyShares: _minInvestmentAmount not met" ); // Give the ComptrollerProxy max allowance for its denomination asset as necessary __approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount); // Buy fund shares sharesReceivedAmount_ = __buyShares( _comptrollerProxy, _buyer, investmentAmount, _minSharesQuantity ); // Unwrap and refund any remaining WETH not used in the exchange uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this)); if (remainingWeth > 0) { IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth); (success, returnData) = msg.sender.call{value: remainingWeth}(""); require(success, string(returnData)); } return sharesReceivedAmount_; } /// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout /// any shares outstanding on those fees /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fees The fees for which to run these actions /// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence. /// The caller must pass in the fees that they want to run this logic on. function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund( address _comptrollerProxy, address[] calldata _fees ) external { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees)); } // PUBLIC FUNCTIONS /// @notice Gets all fees that implement the `Continuous` fee hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return continuousFees_ The fees that implement the `Continuous` fee hook function getContinuousFeesForFund(address _comptrollerProxy) public view returns (address[] memory continuousFees_) { FeeManager feeManagerContract = FeeManager(FEE_MANAGER); address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy); // Count the continuous fees uint256 continuousFeesCount; bool[] memory implementsContinuousHook = new bool[](fees.length); for (uint256 i; i < fees.length; i++) { if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) { continuousFeesCount++; implementsContinuousHook[i] = true; } } // Return early if no continuous fees if (continuousFeesCount == 0) { return new address[](0); } // Create continuous fees array continuousFees_ = new address[](continuousFeesCount); uint256 continuousFeesIndex; for (uint256 i; i < fees.length; i++) { if (implementsContinuousHook[i]) { continuousFees_[continuousFeesIndex] = fees[i]; continuousFeesIndex++; } } return continuousFees_; } // PRIVATE FUNCTIONS /// @dev Helper to approve a target with the max amount of an asset, only when necessary function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to approve a target with the max amount of weth, only when necessary. /// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this /// once per target. function __approveMaxWethAsNeeded(address _target) internal { if (!accountHasMaxWethAllowance(_target)) { ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max); accountToHasMaxWethAllowance[_target] = true; } } /// @dev Helper for buying shares function __buyShares( address _comptrollerProxy, address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) private returns (uint256 sharesReceivedAmount_) { address[] memory buyers = new address[](1); buyers[0] = _buyer; uint256[] memory investmentAmounts = new uint256[](1); investmentAmounts[0] = _investmentAmount; uint256[] memory minSharesQuantities = new uint256[](1); minSharesQuantities[0] = _minSharesQuantity; return ComptrollerLib(_comptrollerProxy).buyShares( buyers, investmentAmounts, minSharesQuantities )[0]; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Checks whether an account has the max allowance for WETH /// @param _who The account to check /// @return hasMaxWethAllowance_ True if the account has the max allowance function accountHasMaxWethAllowance(address _who) public view returns (bool hasMaxWethAllowance_) { return accountToHasMaxWethAllowance[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorLib Contract /// @author Enzyme Council <[email protected]> /// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances, /// in which shares requests are manually executed by a permissioned user /// @dev This will not work with a `denominationAsset` that does not transfer /// the exact expected amount or has an elastic supply. contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor { using SafeERC20 for ERC20; using SafeMath for uint256; event RequestCanceled( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestCreated( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecuted( address indexed caller, address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecutorAdded(address indexed account); event RequestExecutorRemoved(address indexed account); struct RequestInfo { uint256 investmentAmount; uint256 minSharesQuantity; } uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes; address private comptrollerProxy; address private denominationAsset; address private fundOwner; mapping(address => RequestInfo) private ownerToRequestInfo; mapping(address => bool) private acctToIsRequestExecutor; mapping(address => uint256) private ownerToLastRequestCancellation; modifier onlyFundOwner() { require(msg.sender == fundOwner, "Only fund owner callable"); _; } /// @notice Initializes a proxy instance that uses this library /// @dev Serves as a per-proxy pseudo-constructor function init(address _comptrollerProxy) external override { require(comptrollerProxy == address(0), "init: Already initialized"); comptrollerProxy = _comptrollerProxy; // Cache frequently-used values that require external calls ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); denominationAsset = comptrollerProxyContract.getDenominationAsset(); fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner(); } /// @notice Cancels the shares request of the caller function cancelRequest() external { RequestInfo memory request = ownerToRequestInfo[msg.sender]; require(request.investmentAmount > 0, "cancelRequest: Request does not exist"); // Delete the request, start the cooldown period, and return the investment asset delete ownerToRequestInfo[msg.sender]; ownerToLastRequestCancellation[msg.sender] = block.timestamp; ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount); emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity); } /// @notice Creates a shares request for the caller /// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external { require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0"); require( ownerToRequestInfo[msg.sender].investmentAmount == 0, "createRequest: The request owner can only create one request before executed or canceled" ); require( ownerToLastRequestCancellation[msg.sender] < block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK), "createRequest: Cannot create request during cancellation cooldown period" ); // Create the Request and take custody of investment asset ownerToRequestInfo[msg.sender] = RequestInfo({ investmentAmount: _investmentAmount, minSharesQuantity: _minSharesQuantity }); ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount); emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity); } /// @notice Executes multiple shares requests /// @param _requestOwners The owners of the pending shares requests function executeRequests(address[] calldata _requestOwners) external { require( msg.sender == fundOwner || isRequestExecutor(msg.sender), "executeRequests: Invalid caller" ); require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty"); ( address[] memory buyers, uint256[] memory investmentAmounts, uint256[] memory minSharesQuantities, uint256 totalInvestmentAmount ) = __convertRequestsToBuySharesParams(_requestOwners); // Since ComptrollerProxy instances are fully trusted, // we can approve them with the max amount of the denomination asset, // and only top the approval back to max if ever necessary. address comptrollerProxyCopy = comptrollerProxy; ERC20 denominationAssetContract = ERC20(denominationAsset); if ( denominationAssetContract.allowance(address(this), comptrollerProxyCopy) < totalInvestmentAmount ) { denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max); } ComptrollerLib(comptrollerProxyCopy).buyShares( buyers, investmentAmounts, minSharesQuantities ); } /// @dev Helper to convert raw shares requests into the format required by buyShares(). /// It also removes any empty requests, which is necessary to prevent a DoS attack where a user /// cancels their request earlier in the same block (can be repeated from multiple accounts). /// This function also removes shares requests and fires success events as it loops through them. function __convertRequestsToBuySharesParams(address[] memory _requestOwners) private returns ( address[] memory buyers_, uint256[] memory investmentAmounts_, uint256[] memory minSharesQuantities_, uint256 totalInvestmentAmount_ ) { uint256 existingRequestsCount = _requestOwners.length; uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length); // Loop through once to get the count of existing requests for (uint256 i; i < _requestOwners.length; i++) { allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount; if (allInvestmentAmounts[i] == 0) { existingRequestsCount--; } } // Loop through a second time to format requests for buyShares(), // and to delete the requests and emit events early so no further looping is needed. buyers_ = new address[](existingRequestsCount); investmentAmounts_ = new uint256[](existingRequestsCount); minSharesQuantities_ = new uint256[](existingRequestsCount); uint256 existingRequestsIndex; for (uint256 i; i < _requestOwners.length; i++) { if (allInvestmentAmounts[i] == 0) { continue; } buyers_[existingRequestsIndex] = _requestOwners[i]; investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i]; minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]] .minSharesQuantity; totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]); delete ownerToRequestInfo[_requestOwners[i]]; emit RequestExecuted( msg.sender, buyers_[existingRequestsIndex], investmentAmounts_[existingRequestsIndex], minSharesQuantities_[existingRequestsIndex] ); existingRequestsIndex++; } return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_); } /////////////////////////////// // REQUEST EXECUTOR REGISTRY // /////////////////////////////// /// @notice Adds accounts to request executors /// @param _requestExecutors Accounts to add function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( !isRequestExecutor(_requestExecutors[i]), "addRequestExecutors: Value already set" ); require( _requestExecutors[i] != fundOwner, "addRequestExecutors: The fund owner cannot be added" ); acctToIsRequestExecutor[_requestExecutors[i]] = true; emit RequestExecutorAdded(_requestExecutors[i]); } } /// @notice Removes accounts from request executors /// @param _requestExecutors Accounts to remove function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( isRequestExecutor(_requestExecutors[i]), "removeRequestExecutors: Account is not a request executor" ); acctToIsRequestExecutor[_requestExecutors[i]] = false; emit RequestExecutorRemoved(_requestExecutors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of `comptrollerProxy` variable /// @return comptrollerProxy_ The `comptrollerProxy` variable value function getComptrollerProxy() external view returns (address comptrollerProxy_) { return comptrollerProxy; } /// @notice Gets the value of `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the value of `fundOwner` variable /// @return fundOwner_ The `fundOwner` variable value function getFundOwner() external view returns (address fundOwner_) { return fundOwner; } /// @notice Gets the request info of a user /// @param _requestOwner The address of the user that creates the request /// @return requestInfo_ The request info created by the user function getSharesRequestInfoForOwner(address _requestOwner) external view returns (RequestInfo memory requestInfo_) { return ownerToRequestInfo[_requestOwner]; } /// @notice Checks whether an account is a request executor /// @param _who The account to check /// @return isRequestExecutor_ True if _who is a request executor function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) { return acctToIsRequestExecutor[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAuthUserExecutedSharesRequestor Interface /// @author Enzyme Council <[email protected]> interface IAuthUserExecutedSharesRequestor { function init(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./AuthUserExecutedSharesRequestorProxy.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances contract AuthUserExecutedSharesRequestorFactory { event SharesRequestorProxyDeployed( address indexed comptrollerProxy, address sharesRequestorProxy ); address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; address private immutable DISPATCHER; mapping(address => address) private comptrollerProxyToSharesRequestorProxy; constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public { AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib; DISPATCHER = _dispatcher; } /// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance /// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy /// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy function deploySharesRequestorProxy(address _comptrollerProxy) external returns (address sharesRequestorProxy_) { // Confirm fund is genuine VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy()); require( vaultProxyContract.getAccessor() == _comptrollerProxy, "deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy" ); require( IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) != address(0), "deploySharesRequestorProxy: Not a genuine fund" ); // Validate that the caller is the fund owner require( msg.sender == vaultProxyContract.getOwner(), "deploySharesRequestorProxy: Only fund owner callable" ); // Validate that a proxy does not already exist require( comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0), "deploySharesRequestorProxy: Proxy already exists" ); // Deploy the proxy bytes memory constructData = abi.encodeWithSelector( IAuthUserExecutedSharesRequestor.init.selector, _comptrollerProxy ); sharesRequestorProxy_ = address( new AuthUserExecutedSharesRequestorProxy( constructData, AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB ) ); comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_; emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_); return sharesRequestorProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable /// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value function getAuthUserExecutedSharesRequestorLib() external view returns (address authUserExecutedSharesRequestorLib_) { return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; } /// @notice Gets the value of the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy /// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy) external view returns (address sharesRequestorProxy_) { return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/Proxy.sol"; contract AuthUserExecutedSharesRequestorProxy is Proxy { constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib) public Proxy(_constructData, _authUserExecutedSharesRequestorLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Proxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all Proxy instances /// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract Proxy { constructor(bytes memory _constructData, address _contractLogic) public { assembly { sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } fallback() external payable { assembly { let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/Proxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is Proxy { constructor(bytes memory _constructData, address _comptrollerLib) public Proxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/utils/IMigrationHookHandler.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler { event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData, bool indexed forMigration ); event NewFundCreated( address indexed creator, address comptrollerProxy, address vaultProxy, address indexed fundOwner, string fundName, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData ); event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus); event VaultCallDeregistered(address indexed contractAddress, bytes4 selector); event VaultCallRegistered(address indexed contractAddress, bytes4 selector); // Constants address private immutable CREATOR; address private immutable DISPATCHER; address private immutable VAULT_LIB; // Pseudo-constants (can only be set once) address private comptrollerLib; // Storage ReleaseStatus private releaseStatus; mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall; mapping(address => address) private pendingComptrollerProxyToCreator; modifier onlyLiveRelease() { require(releaseStatus == ReleaseStatus.Live, "Release is not Live"); _; } modifier onlyMigrator(address _vaultProxy) { require( IVault(_vaultProxy).canMigrate(msg.sender), "Only a permissioned migrator can call this function" ); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) { require( msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy], "Only the ComptrollerProxy creator can call this function" ); _; } constructor( address _dispatcher, address _vaultLib, address[] memory _vaultCallContracts, bytes4[] memory _vaultCallSelectors ) public { if (_vaultCallContracts.length > 0) { __registerVaultCalls(_vaultCallContracts, _vaultCallSelectors); } CREATOR = msg.sender; DISPATCHER = _dispatcher; VAULT_LIB = _vaultLib; } ///////////// // GENERAL // ///////////// /// @notice Sets the comptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address /// @dev Can only be set once function setComptrollerLib(address _comptrollerLib) external onlyOwner { require( comptrollerLib == address(0), "setComptrollerLib: This value can only be set once" ); comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the status of the protocol to a new state /// @param _nextStatus The next status state to set function setReleaseStatus(ReleaseStatus _nextStatus) external { require( msg.sender == IDispatcher(DISPATCHER).getOwner(), "setReleaseStatus: Only the Dispatcher owner can call this function" ); require( _nextStatus != ReleaseStatus.PreLaunch, "setReleaseStatus: Cannot return to PreLaunch status" ); require( comptrollerLib != address(0), "setReleaseStatus: Can only set the release status when comptrollerLib is set" ); ReleaseStatus prevStatus = releaseStatus; require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status"); releaseStatus = _nextStatus; emit ReleaseStatusSet(prevStatus, _nextStatus); } /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the /// contract's deployer, for convenience in setting up configuration. /// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council) /// sets the releaseStatus to `Live`. function getOwner() public view override returns (address owner_) { if (releaseStatus == ReleaseStatus.PreLaunch) { return CREATOR; } return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous /// release can migrate in a subsequent step /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigratedFundConfig( address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_) { comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, true ); pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender; return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { return __createNewFund( _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); } /// @dev Helper to avoid the stack-too-deep error during createNewFund function __createNewFund( address _fundOwner, string memory _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private returns (address comptrollerProxy_, address vaultProxy_) { require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty"); comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, false ); vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy( VAULT_LIB, _fundOwner, comptrollerProxy_, _fundName ); IComptroller(comptrollerProxy_).activate(vaultProxy_, false); emit NewFundCreated( msg.sender, comptrollerProxy_, vaultProxy_, _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); return (comptrollerProxy_, vaultProxy_); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty" ); bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib)); if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) { IComptroller(comptrollerProxy_).configureExtensions( _feeManagerConfigData, _policyManagerConfigData ); } emit ComptrollerProxyDeployed( msg.sender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, _forMigration ); return comptrollerProxy_; } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); } /// @notice Cancels fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigrationEmergency(address _vaultProxy) external { __cancelMigration(_vaultProxy, true); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigration(address _vaultProxy) external { __executeMigration(_vaultProxy, false); } /// @notice Executes fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigrationEmergency(address _vaultProxy) external { __executeMigration(_vaultProxy, true); } /// @dev Unimplemented function invokeMigrationInCancelHook( address, address, address, address ) external virtual override { return; } /// @notice Signal a fund migration /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigration(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, false); } /// @notice Signal a fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, true); } /// @dev Helper to cancel a migration function __cancelMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure); } /// @dev Helper to execute a migration function __executeMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(DISPATCHER); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassFailure); IComptroller(comptrollerProxy).activate(_vaultProxy, true); delete pendingComptrollerProxyToCreator[comptrollerProxy]; } /// @dev Helper to signal a migration function __signalMigration( address _vaultProxy, address _comptrollerProxy, bool _bypassFailure ) private onlyLiveRelease onlyPendingComptrollerProxyCreator(_comptrollerProxy) onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).signalMigration( _vaultProxy, _comptrollerProxy, VAULT_LIB, _bypassFailure ); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override { if (_hook != MigrationOutHook.PreMigrate) { return; } require( msg.sender == DISPATCHER, "postMigrateOriginHook: Only Dispatcher can call this function" ); // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config IComptroller(comptrollerProxy).destruct(); } ////////////// // REGISTRY // ////////////// /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i]), "deregisterVaultCalls: Call not registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); __registerVaultCalls(_contracts, _selectors); } /// @dev Helper to register allowed vault calls function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i]), "__registerVaultCalls: Call already registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() external view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() external view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the creator of a pending ComptrollerProxy /// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator function getPendingComptrollerProxyCreator(address _comptrollerProxy) external view returns (address pendingComptrollerProxyCreator_) { return pendingComptrollerProxyToCreator[_comptrollerProxy]; } /// @notice Gets the `releaseStatus` variable value /// @return status_ The `releaseStatus` variable value function getReleaseStatus() external view override returns (ReleaseStatus status_) { return releaseStatus; } /// @notice Gets the `VAULT_LIB` variable value /// @return vaultLib_ The `VAULT_LIB` variable value function getVaultLib() external view returns (address vaultLib_) { return VAULT_LIB; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall(address _contract, bytes4 _selector) public view override returns (bool isRegistered_) { return contractToSelectorToIsRegisteredVaultCall[_contract][_selector]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[email protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../utils/AddressArrayLib.sol"; import "../../utils/AssetFinalityResolver.sol"; import "../policy-manager/IPolicyManager.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./integrations/IIntegrationAdapter.sol"; import "./IIntegrationManager.sol"; /// @title IntegrationManager /// @author Enzyme Council <[email protected]> /// @notice Extension to handle DeFi integration actions for funds contract IntegrationManager is IIntegrationManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin, AssetFinalityResolver { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AdapterDeregistered(address indexed adapter, string indexed identifier); event AdapterRegistered(address indexed adapter, string indexed identifier); event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account); event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account); event CallOnIntegrationExecutedForFund( address indexed comptrollerProxy, address vaultProxy, address caller, address indexed adapter, bytes4 indexed selector, bytes integrationData, address[] incomingAssets, uint256[] incomingAssetAmounts, address[] outgoingAssets, uint256[] outgoingAssetAmounts ); address private immutable DERIVATIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; EnumerableSet.AddressSet private registeredAdapters; mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser; constructor( address _fundDeployer, address _policyManager, address _derivativePriceFeed, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public FundDeployerOwnerMixin(_fundDeployer) AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; POLICY_MANAGER = _policyManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } ///////////// // GENERAL // ///////////// /// @notice Activates the extension by storing the VaultProxy function activateForFund(bool) external override { __setValidatedVaultProxy(msg.sender); } /// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The user to authorize function addAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, true); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true; emit AuthUserAddedForFund(_comptrollerProxy, _who); } /// @notice Deactivate the extension by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; } /// @notice Removes an authorized user from the IntegrationManager for the given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The authorized user to remove function removeAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, false); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false; emit AuthUserRemovedForFund(_comptrollerProxy, _who); } /// @notice Checks whether an account is an authorized IntegrationManager user for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The account to check /// @return isAuthUser_ True if the account is an authorized user or the fund owner function isAuthUserForFund(address _comptrollerProxy, address _who) public view returns (bool isAuthUser_) { return comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] || _who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); } /// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser function __validateSetAuthUser( address _comptrollerProxy, address _who, bool _nextIsAuthUser ) private view { require( comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0), "__validateSetAuthUser: Fund has not been activated" ); address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); require( msg.sender == fundOwner, "__validateSetAuthUser: Only the fund owner can call this function" ); require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner"); if (_nextIsAuthUser) { require( !comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is already an authorized user" ); } else { require( comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is not an authorized user" ); } } /////////////////////////////// // CALL-ON-EXTENSION ACTIONS // /////////////////////////////// /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _caller The user who called for this action /// @param _actionId An ID representing the desired action /// @param _callArgs The encoded args for the action function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external override { // Since we validate and store the ComptrollerProxy-VaultProxy pairing during // activateForFund(), this function does not require further validation of the // sending ComptrollerProxy address vaultProxy = comptrollerProxyToVaultProxy[msg.sender]; require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active"); require( isAuthUserForFund(msg.sender, _caller), "receiveCallFromComptroller: Not an authorized user" ); // Dispatch the action if (_actionId == 0) { __callOnIntegration(_caller, vaultProxy, _callArgs); } else if (_actionId == 1) { __addZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else if (_actionId == 2) { __removeZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @dev Adds assets with a zero balance as tracked assets of the fund function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); for (uint256 i; i < assets.length; i++) { require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__addZeroBalanceTrackedAssets: Balance is not zero" ); __addTrackedAsset(msg.sender, assets[i]); } } /// @dev Removes assets with a zero balance from tracked assets of the fund function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); address denominationAsset = IComptroller(msg.sender).getDenominationAsset(); for (uint256 i; i < assets.length; i++) { require( assets[i] != denominationAsset, "__removeZeroBalanceTrackedAssets: Cannot remove denomination asset" ); require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__removeZeroBalanceTrackedAssets: Balance is not zero" ); __removeTrackedAsset(msg.sender, assets[i]); } } ///////////////////////// // CALL ON INTEGRATION // ///////////////////////// /// @notice Universal method for calling third party contract functions through adapters /// @param _caller The caller of this function via the ComptrollerProxy /// @param _vaultProxy The VaultProxy of the fund /// @param _callArgs The encoded args for this function /// - _adapter Adapter of the integration on which to execute a call /// - _selector Method selector of the adapter method to execute /// - _integrationData Encoded arguments specific to the adapter /// @dev msg.sender is the ComptrollerProxy. /// Refer to specific adapter to see how to encode its arguments. function __callOnIntegration( address _caller, address _vaultProxy, bytes memory _callArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); __preCoIHook(adapter, selector); /// Passing decoded _callArgs leads to stack-too-deep error ( address[] memory incomingAssets, uint256[] memory incomingAssetAmounts, address[] memory outgoingAssets, uint256[] memory outgoingAssetAmounts ) = __callOnIntegrationInner(_vaultProxy, _callArgs); __postCoIHook( adapter, selector, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); __emitCoIEvent( _vaultProxy, _caller, adapter, selector, integrationData, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); } /// @dev Helper to execute the bulk of logic of callOnIntegration. /// Avoids the stack-too-deep-error. function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { ( address[] memory expectedIncomingAssets, uint256[] memory preCallIncomingAssetBalances, uint256[] memory minIncomingAssetAmounts, SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory maxSpendAssetAmounts, uint256[] memory preCallSpendAssetBalances ) = __preProcessCoI(vaultProxy, _callArgs); __executeCoI( vaultProxy, _callArgs, abi.encode( spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, expectedIncomingAssets ) ); ( incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_ ) = __postProcessCoI( vaultProxy, expectedIncomingAssets, preCallIncomingAssetBalances, minIncomingAssetAmounts, spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, preCallSpendAssetBalances ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to decode CoI args function __decodeCallOnIntegrationArgs(bytes memory _callArgs) private pure returns ( address adapter_, bytes4 selector_, bytes memory integrationData_ ) { return abi.decode(_callArgs, (address, bytes4, bytes)); } /// @dev Helper to emit the CallOnIntegrationExecuted event. /// Avoids stack-too-deep error. function __emitCoIEvent( address _vaultProxy, address _caller, address _adapter, bytes4 _selector, bytes memory _integrationData, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { emit CallOnIntegrationExecutedForFund( msg.sender, _vaultProxy, _caller, _adapter, _selector, _integrationData, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ); } /// @dev Helper to execute a call to an integration /// @dev Avoids stack-too-deep error function __executeCoI( address _vaultProxy, bytes memory _callArgs, bytes memory _encodedAssetTransferArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); (bool success, bytes memory returnData) = adapter.call( abi.encodeWithSelector( selector, _vaultProxy, integrationData, _encodedAssetTransferArgs ) ); require(success, string(returnData)); } /// @dev Helper to get the vault's balance of a particular asset function __getVaultAssetBalance(address _vaultProxy, address _asset) private view returns (uint256) { return ERC20(_asset).balanceOf(_vaultProxy); } /// @dev Helper to check if an asset is supported function __isSupportedAsset(address _asset) private view returns (bool isSupported_) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) || IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset); } /// @dev Helper for the actions to take on external contracts prior to executing CoI function __preCoIHook(address _adapter, bytes4 _selector) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PreCallOnIntegration, abi.encode(_adapter, _selector) ); } /// @dev Helper for the internal actions to take prior to executing CoI function __preProcessCoI(address _vaultProxy, bytes memory _callArgs) private returns ( address[] memory expectedIncomingAssets_, uint256[] memory preCallIncomingAssetBalances_, uint256[] memory minIncomingAssetAmounts_, SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory preCallSpendAssetBalances_ ) { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered"); // Note that expected incoming and spend assets are allowed to overlap // (e.g., a fee for the incomingAsset charged in a spend asset) ( spendAssetsHandleType_, spendAssets_, maxSpendAssetAmounts_, expectedIncomingAssets_, minIncomingAssetAmounts_ ) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData); require( spendAssets_.length == maxSpendAssetAmounts_.length, "__preProcessCoI: Spend assets arrays unequal" ); require( expectedIncomingAssets_.length == minIncomingAssetAmounts_.length, "__preProcessCoI: Incoming assets arrays unequal" ); require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset"); require( expectedIncomingAssets_.isUniqueSet(), "__preProcessCoI: Duplicate incoming asset" ); IVault vaultProxyContract = IVault(_vaultProxy); preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length); for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) { require( expectedIncomingAssets_[i] != address(0), "__preProcessCoI: Empty incoming asset address" ); require( minIncomingAssetAmounts_[i] > 0, "__preProcessCoI: minIncomingAssetAmount must be >0" ); require( __isSupportedAsset(expectedIncomingAssets_[i]), "__preProcessCoI: Non-receivable incoming asset" ); // Get pre-call balance of each incoming asset. // If the asset is not tracked by the fund, allow the balance to default to 0. if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) { // We do not require incoming asset finality, but we attempt to finalize so that // the final incoming asset amount is more accurate. There is no need to finalize // post-tx. preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, expectedIncomingAssets_[i], false ); } } // Get pre-call balances of spend assets and grant approvals to adapter preCallSpendAssetBalances_ = new uint256[](spendAssets_.length); for (uint256 i = 0; i < spendAssets_.length; i++) { require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset"); require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount"); // A spend asset must either be a tracked asset of the fund or a supported asset, // in order to prevent seeding the fund with a malicious token and performing arbitrary // actions within an adapter. require( vaultProxyContract.isTrackedAsset(spendAssets_[i]) || __isSupportedAsset(spendAssets_[i]), "__preProcessCoI: Non-spendable spend asset" ); // If spend asset is also an incoming asset, no need to record its balance if (!expectedIncomingAssets_.contains(spendAssets_[i])) { // By requiring spend asset finality before CoI, we will know whether or // not the asset balance was entirely spent during the call. There is no need // to finalize post-tx. preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, spendAssets_[i], true ); } // Grant spend assets access to the adapter. // Note that spendAssets_ is already asserted to a unique set. if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) { // Use exact approve amount rather than increasing allowances, // because all adapters finish their actions atomically. __approveAssetSpender( msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i] ); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) { __withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) { __removeTrackedAsset(msg.sender, spendAssets_[i]); } } } /// @dev Helper for the actions to take on external contracts after executing CoI function __postCoIHook( address _adapter, bytes4 _selector, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PostCallOnIntegration, abi.encode( _adapter, _selector, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ) ); } /// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI function __postProcessCoI( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { address[] memory increasedSpendAssets; uint256[] memory increasedSpendAssetAmounts; ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets, increasedSpendAssetAmounts ) = __reconcileCoISpendAssets( _vaultProxy, _spendAssetsHandleType, _spendAssets, _maxSpendAssetAmounts, _preCallSpendAssetBalances ); (incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets( _vaultProxy, _expectedIncomingAssets, _preCallIncomingAssetBalances, _minIncomingAssetAmounts, increasedSpendAssets, increasedSpendAssetAmounts ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to process incoming asset balance changes. /// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets". function __reconcileCoIIncomingAssets( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, address[] memory _increasedSpendAssets, uint256[] memory _increasedSpendAssetAmounts ) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) { // Incoming assets = expected incoming assets + spend assets with increased balances uint256 incomingAssetsCount = _expectedIncomingAssets.length.add( _increasedSpendAssets.length ); // Calculate and validate incoming asset amounts incomingAssets_ = new address[](incomingAssetsCount); incomingAssetAmounts_ = new uint256[](incomingAssetsCount); for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) { uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i]) .sub(_preCallIncomingAssetBalances[i]); require( balanceDiff >= _minIncomingAssetAmounts[i], "__reconcileCoIAssets: Received incoming asset less than expected" ); // Even if the asset's previous balance was >0, it might not have been tracked __addTrackedAsset(msg.sender, _expectedIncomingAssets[i]); incomingAssets_[i] = _expectedIncomingAssets[i]; incomingAssetAmounts_[i] = balanceDiff; } // Append increaseSpendAssets to incomingAsset vars if (_increasedSpendAssets.length > 0) { uint256 incomingAssetIndex = _expectedIncomingAssets.length; for (uint256 i = 0; i < _increasedSpendAssets.length; i++) { incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i]; incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i]; incomingAssetIndex++; } } return (incomingAssets_, incomingAssetAmounts_); } /// @dev Helper to process spend asset balance changes. /// "outgoingAssets" are the spend assets with a decrease in balance. /// "increasedSpendAssets" are the spend assets with an unexpected increase in balance. /// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of /// the spendAsset, which would be transferred to the fund at the end of the tx. function __reconcileCoISpendAssets( address _vaultProxy, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_, address[] memory increasedSpendAssets_, uint256[] memory increasedSpendAssetAmounts_ ) { // Determine spend asset balance changes uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length); uint256 outgoingAssetsCount; uint256 increasedSpendAssetsCount; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssetsCount++; continue; } // Determine if the asset is outgoing or incoming, and store the post-balance for later use postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]); // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { outgoingAssetsCount++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetsCount++; } } // Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance) outgoingAssets_ = new address[](outgoingAssetsCount); outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount); increasedSpendAssets_ = new address[](increasedSpendAssetsCount); increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount); uint256 outgoingAssetsIndex; uint256 increasedSpendAssetsIndex; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset. if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately. // No need to validate the max spend asset amount. if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; outgoingAssetsIndex++; continue; } // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { if (postCallSpendAssetBalances[i] == 0) { __removeTrackedAsset(msg.sender, _spendAssets[i]); outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; } else { outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub( postCallSpendAssetBalances[i] ); } require( outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i], "__reconcileCoISpendAssets: Spent amount greater than expected" ); outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetsIndex++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i] .sub(_preCallSpendAssetBalances[i]); increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i]; increasedSpendAssetsIndex++; } } return ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets_, increasedSpendAssetAmounts_ ); } /////////////////////////// // INTEGRATIONS REGISTRY // /////////////////////////// /// @notice Remove integration adapters from the list of registered adapters /// @param _adapters Addresses of adapters to be deregistered function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require( adapterIsRegistered(_adapters[i]), "deregisterAdapters: Adapter is not registered" ); registeredAdapters.remove(_adapters[i]); emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /// @notice Add integration adapters to the list of registered adapters /// @param _adapters Addresses of adapters to be registered function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty"); require( !adapterIsRegistered(_adapters[i]), "registerAdapters: Adapter already registered" ); registeredAdapters.add(_adapters[i]); emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks if an integration adapter is registered /// @param _adapter The adapter to check /// @return isRegistered_ True if the adapter is registered function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) { return registeredAdapters.contains(_adapter); } /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets all registered integration adapters /// @return registeredAdaptersArray_ A list of all registered integration adapters function getRegisteredAdapters() external view returns (address[] memory registeredAdaptersArray_) { registeredAdaptersArray_ = new address[](registeredAdapters.length()); for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) { registeredAdaptersArray_[i] = registeredAdapters.at(i); } return registeredAdaptersArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../utils/AdapterBase.sol"; /// @title SynthetixAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Synthetix contract SynthetixAdapter is AdapterBase { address private immutable ORIGINATOR; address private immutable SYNTHETIX; address private immutable SYNTHETIX_PRICE_FEED; bytes32 private immutable TRACKING_CODE; constructor( address _integrationManager, address _synthetixPriceFeed, address _originator, address _synthetix, bytes32 _trackingCode ) public AdapterBase(_integrationManager) { ORIGINATOR = _originator; SYNTHETIX = _synthetix; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; TRACKING_CODE = _trackingCode; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "SYNTHETIX"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Synthetix /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address incomingAsset, , address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address[] memory synths = new address[](2); synths[0] = outgoingAsset; synths[1] = incomingAsset; bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED) .getCurrencyKeysForSynths(synths); ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking( _vaultProxy, currencyKeys[0], outgoingAssetAmount, currencyKeys[1], ORIGINATOR, TRACKING_CODE ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ORIGINATOR` variable /// @return originator_ The `ORIGINATOR` variable value function getOriginator() external view returns (address originator_) { return ORIGINATOR; } /// @notice Gets the `SYNTHETIX` variable /// @return synthetix_ The `SYNTHETIX` variable value function getSynthetix() external view returns (address synthetix_) { return SYNTHETIX; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } /// @notice Gets the `TRACKING_CODE` variable /// @return trackingCode_ The `TRACKING_CODE` variable value function getTrackingCode() external view returns (bytes32 trackingCode_) { return TRACKING_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; import "../../utils/DispatcherOwnerMixin.sol"; import "./IPrimitivePriceFeed.sol"; /// @title ChainlinkPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); event PrimitiveUpdated( address indexed primitive, address prevAggregator, address nextAggregator ); event StalePrimitiveRemoved(address indexed primitive); event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; address private immutable WETH_TOKEN; address private ethUsdAggregator; uint256 private staleRateThreshold; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor( address _dispatcher, address _wethToken, address _ethUsdAggregator, address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) public DispatcherOwnerMixin(_dispatcher) { WETH_TOKEN = _wethToken; staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer __setEthUsdAggregator(_ethUsdAggregator); if (_primitives.length > 0) { __addPrimitives(_primitives, _aggregators, _rateAssets); } } // EXTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid function calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) public view override returns (uint256 quoteAssetAmount_, bool isValid_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); if (baseAssetRate <= 0) { return (0, false); } int256 quoteAssetRate = __getLatestRateData(_quoteAsset); if (quoteAssetRate <= 0) { return (0, false); } (quoteAssetAmount_, isValid_) = __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); return (quoteAssetAmount_, isValid_); } /// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid /// @dev Live and canonical values are the same for Chainlink function calcLiveValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) external view override returns (uint256 quoteAssetAmount_, bool isValid_) { return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_, bool isValid_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return ( __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ), true ); } int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer(); if (ethPerUsdRate <= 0) { return (0, false); } // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return ( __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return ( __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == WETH_TOKEN) { return int256(ETH_UNIT); } address aggregator = primitiveToAggregatorInfo[_primitive].aggregator; require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); return IChainlinkAggregator(aggregator).latestAnswer(); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) private { address prevEthUsdAggregator = ethUsdAggregator; require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyDispatcherOwner { require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty"); __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner { require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0), "removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } /// @notice Removes stale primitives from the feed /// @param _primitives The stale primitives to remove /// @dev Callable by anybody function removeStalePrimitives(address[] calldata _primitives) external { require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive"); require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale"); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit StalePrimitiveRemoved(_primitives[i]); } } /// @notice Sets the `staleRateThreshold` variable /// @param _nextStaleRateThreshold The next `staleRateThreshold` value function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner { uint256 prevStaleRateThreshold = staleRateThreshold; require( _nextStaleRateThreshold != prevStaleRateThreshold, "__setStaleRateThreshold: Value already set" ); staleRateThreshold = _nextStaleRateThreshold; emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold); } /// @notice Updates the aggregators for given primitives /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators) external onlyDispatcherOwner { require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty"); require( _primitives.length == _aggregators.length, "updatePrimitives: Unequal _primitives and _aggregators array lengths" ); for (uint256 i; i < _primitives.length; i++) { address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added"); require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set"); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i]; emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]); } } /// @notice Checks whether the current rate is considered stale for the specified aggregator /// @param _aggregator The Chainlink aggregator of which to check staleness /// @return rateIsStale_ True if the rate is considered stale function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) { return IChainlinkAggregator(_aggregator).latestTimestamp() < block.timestamp.sub(staleRateThreshold); } /// @dev Helper to add primitives to the feed function __addPrimitives( address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) private { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i = 0; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { require(_aggregator != address(0), "__validateAggregator: Empty _aggregator"); require( IChainlinkAggregator(_aggregator).latestAnswer() > 0, "__validateAggregator: No rate detected" ); require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregatorInfo variable value for a primitive /// @param _primitive The primitive asset for which to get the aggregatorInfo value /// @return aggregatorInfo_ The aggregatorInfo value function getAggregatorInfoForPrimitive(address _primitive) external view returns (AggregatorInfo memory aggregatorInfo_) { return primitiveToAggregatorInfo[_primitive]; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() external view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the `staleRateThreshold` variable value /// @return staleRateThreshold_ The `staleRateThreshold` variable value function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) { return staleRateThreshold; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == WETH_TOKEN) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == WETH_TOKEN) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; /// @dev This contract acts as a centralized rate provider for mocks. /// Suited for a dev environment, it doesn't take into account gas costs. contract CentralizedRateProvider is Ownable { using SafeMath for uint256; address private immutable WETH; uint256 private maxDeviationPerSender; // Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env). address private valueInterpreter; address private aggregateDerivativePriceFeed; address private primitivePriceFeed; constructor(address _weth, uint256 _maxDeviationPerSender) public { maxDeviationPerSender = _maxDeviationPerSender; WETH = _weth; } /// @dev Calculates the value of a _baseAsset relative to a _quoteAsset. /// Label to ValueInterprete's calcLiveAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public returns (uint256 value_) { uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals()); uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals()); // 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) { (value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, _amount, _quoteAsset ); return value_; } // 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) { (uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, 10**uint256(ERC20(_quoteAsset).decimals()), _baseAsset ); uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate); value_ = _amount.mul(rate).div(baseDecimalsRate); return value_; } // 3. If both assets are derivatives, calculate the rate against ETH. (uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, baseDecimalsRate, WETH ); (uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, quoteDecimalsRate, WETH ); value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div( baseDecimalsRate ); return value_; } /// @dev Calculates a randomized live value of an asset /// Aggregation of two randomization seeds: msg.sender, and by block.number. function calcLiveAssetValueRandomized( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); // Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)] uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress( liveAssetValue, msg.sender, maxDeviationPerSender ); // Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)] value_ = __calcValueRandomizedByUint( senderRandomizedValue_, block.number, _maxDeviationPerBlock ); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness function calcLiveAssetValueRandomizedByBlockNumber( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness function calcLiveAssetValueRandomizedBySender( address _baseAsset, uint256 _amount, address _quoteAsset ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender); return value_; } function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner { maxDeviationPerSender = _maxDeviationPerSender; } /// @dev Connector from release environment, inject price variables into the provider. function setReleasePriceAddresses( address _valueInterpreter, address _aggregateDerivativePriceFeed, address _primitivePriceFeed ) external onlyOwner { valueInterpreter = _valueInterpreter; aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed; primitivePriceFeed = _primitivePriceFeed; } // PRIVATE FUNCTIONS /// @dev Calculates a a pseudo-randomized value as a seed an address function __calcValueRandomizedByAddress( uint256 _meanValue, address _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Value between [0, 100] uint256 senderRandomFactor = uint256(uint8(_seed)) .mul(100) .div(256) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation); return value_; } /// @dev Calculates a a pseudo-randomized value as a seed an uint256 function __calcValueRandomizedByUint( uint256 _meanValue, uint256 _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Depending on the _seed number, it will be one of {20, 40, 60, 80, 100} uint256 randomFactor = (_seed.mod(2).mul(20)) .add((_seed.mod(3).mul(40))) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation); return value_; } /// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation) /// TODO: Refactor to use 18 decimal precision function __calcDeviatedValue( uint256 _meanValue, uint256 _offset, uint256 _maxDeviation ) private pure returns (uint256 value_) { return _meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub( _meanValue.mul(_maxDeviation).div(uint256(100)) ); } /////////////////// // STATE GETTERS // /////////////////// function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) { return maxDeviationPerSender; } function getValueInterpreter() public view returns (address valueInterpreter_) { return valueInterpreter; } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IUniswapV2Pair.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; /// @dev This price source mocks the integration with Uniswap Pair /// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/> contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) { using SafeMath for uint256; address private immutable TOKEN_0; address private immutable TOKEN_1; address private immutable CENTRALIZED_RATE_PROVIDER; constructor( address _centralizedRateProvider, address _token0, address _token1 ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; TOKEN_0 = _token0; TOKEN_1 = _token1; } /// @dev returns reserves for each token on the Uniswap Pair /// Reserves will be used to calculate the pair price /// Inherited from IUniswapV2Pair function getReserves() external returns ( uint112 reserve0_, uint112 reserve1_, uint32 blockTimestampLast_ ) { uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this)); reserve0_ = uint112(baseAmount); reserve1_ = uint112( CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN_0, baseAmount, TOKEN_1 ) ); return (reserve0_, reserve1_, blockTimestampLast_); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Inherited from IUniswapV2Pair function token0() public view returns (address) { return TOKEN_0; } /// @dev Inherited from IUniswapV2Pair function token1() public view returns (address) { return TOKEN_1; } /// @dev Inherited from IUniswapV2Pair function kLast() public pure returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MockToken is ERC20Burnable, Ownable { using SafeMath for uint256; mapping(address => bool) private addressToIsMinter; modifier onlyMinter() { require( addressToIsMinter[msg.sender] || owner() == msg.sender, "msg.sender is not owner or minter" ); _; } constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); _mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals))); } function mintFor(address _who, uint256 _amount) external onlyMinter { _mint(_who, _amount); } function mint(uint256 _amount) external onlyMinter { _mint(msg.sender, _amount); } function addMinters(address[] memory _minters) public onlyOwner { for (uint256 i = 0; i < _minters.length; i++) { addressToIsMinter[_minters[i]] = true; } } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../release/core/fund/comptroller/ComptrollerLib.sol"; import "./MockToken.sol"; /// @title MockReentrancyToken Contract /// @author Enzyme Council <[email protected]> /// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) { bool public bad; address public comptrollerProxy; function makeItReentracyToken(address _comptrollerProxy) external { bad = true; comptrollerProxy = _comptrollerProxy; } function transfer(address recipient, uint256 amount) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).redeemShares(); } else { _transfer(_msgSender(), recipient, amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).buyShares( new address[](0), new uint256[](0), new uint256[](0) ); } else { _transfer(sender, recipient, amount); } return true; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixProxyERC20.sol"; import "./../../release/interfaces/ISynthetixSynth.sol"; import "./MockToken.sol"; contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken { using SafeMath for uint256; bytes32 public override currencyKey; uint256 public constant WAITING_PERIOD_SECS = 3 * 60; mapping(address => uint256) public timelockByAccount; constructor( string memory _name, string memory _symbol, uint8 _decimals, bytes32 _currencyKey ) public MockToken(_name, _symbol, _decimals) { currencyKey = _currencyKey; } function setCurrencyKey(bytes32 _currencyKey) external onlyOwner { currencyKey = _currencyKey; } function _isLocked(address account) internal view returns (bool) { return timelockByAccount[account] >= now; } function _beforeTokenTransfer( address from, address, uint256 ) internal override { require(!_isLocked(from), "Cannot settle during waiting period"); } function target() external view override returns (address) { return address(this); } function isLocked(address account) external view returns (bool) { return _isLocked(account); } function burnFrom(address account, uint256 amount) public override { _burn(account, amount); } function lock(address account) public { timelockByAccount[account] = now.add(WAITING_PERIOD_SECS); } function unlock(address account) public { timelockByAccount[account] = 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IUniswapV2Factory.sol"; import "../../../../interfaces/IUniswapV2Router2.sol"; import "../utils/AdapterBase.sol"; /// @title UniswapV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Uniswap v2 contract UniswapV2Adapter is AdapterBase { using SafeMath for uint256; address private immutable FACTORY; address private immutable ROUTER; constructor( address _integrationManager, address _router, address _factory ) public AdapterBase(_integrationManager) { FACTORY = _factory; ROUTER = _router; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "UNISWAP_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, , uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); spendAssets_ = new address[](2); spendAssets_[0] = outgoingAssets[0]; spendAssets_[1] = outgoingAssets[1]; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0]; spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1]; incomingAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair( outgoingAssets[0], outgoingAssets[1] ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair( incomingAssets[0], incomingAssets[1] ); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](2); incomingAssets_[0] = incomingAssets[0]; incomingAssets_[1] = incomingAssets[1]; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0]; minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1]; } else if (_selector == TAKE_ORDER_SELECTOR) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2"); spendAssets_ = new address[](1); spendAssets_[0] = path[0]; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = path[path.length - 1]; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, uint256[2] memory minOutgoingAssetAmounts, ) = __decodeLendCallArgs(_encodedCallArgs); __lend( _vaultProxy, outgoingAssets[0], outgoingAssets[1], maxOutgoingAssetAmounts[0], maxOutgoingAssetAmounts[1], minOutgoingAssetAmounts[0], minOutgoingAssetAmounts[1] ); } /// @notice Redeems pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); // More efficient to parse pool token from _encodedAssetTransferArgs than external call (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __redeem( _vaultProxy, spendAssets[0], outgoingAssetAmount, incomingAssets[0], incomingAssets[1], minIncomingAssetAmounts[0], minIncomingAssetAmounts[1] ); } /// @notice Trades assets on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); __takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path); } // PRIVATE FUNCTIONS /// @dev Helper to decode the lend encoded call arguments function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[2] memory outgoingAssets_, uint256[2] memory maxOutgoingAssetAmounts_, uint256[2] memory minOutgoingAssetAmounts_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256)); } /// @dev Helper to decode the redeem encoded call arguments function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, address[2] memory incomingAssets_, uint256[2] memory minIncomingAssetAmounts_ ) { return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2])); } /// @dev Helper to decode the take order encoded call arguments function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[] memory path_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[], uint256, uint256)); } /// @dev Helper to execute lend. Avoids stack-too-deep error. function __lend( address _vaultProxy, address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired); __approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired); // Execute lend on Uniswap IUniswapV2Router2(ROUTER).addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute redeem. Avoids stack-too-deep error. function __redeem( address _vaultProxy, address _poolToken, uint256 _poolTokenAmount, address _tokenA, address _tokenB, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount); // Execute redeem on Uniswap IUniswapV2Router2(ROUTER).removeLiquidity( _tokenA, _tokenB, _poolTokenAmount, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, uint256 _outgoingAssetAmount, uint256 _minIncomingAssetAmount, address[] memory _path ) private { __approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount); // Execute fill IUniswapV2Router2(ROUTER).swapExactTokensForTokens( _outgoingAssetAmount, _minIncomingAssetAmount, _path, _vaultProxy, block.timestamp.add(1) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FACTORY` variable /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `ROUTER` variable /// @return router_ The `ROUTER` variable value function getRouter() external view returns (address router_) { return ROUTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title UniswapV2Router2 Interface /// @author Enzyme Council <[email protected]> /// @dev Minimal interface for our interactions with Uniswap V2's Router2 interface IUniswapV2Router2 { function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ); function removeLiquidity( address, address, uint256, uint256, uint256, address, uint256 ) external returns (uint256, uint256); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeToken.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CurvePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Curve pool tokens contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event DerivativeAdded( address indexed derivative, address indexed pool, address indexed invariantProxyAsset, uint256 invariantProxyAssetDecimals ); event DerivativeRemoved(address indexed derivative); // Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes. // We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools. struct DerivativeInfo { address pool; address invariantProxyAsset; uint256 invariantProxyAssetDecimals; } uint256 private constant VIRTUAL_PRICE_UNIT = 10**18; address private immutable ADDRESS_PROVIDER; mapping(address => DerivativeInfo) private derivativeToInfo; constructor(address _dispatcher, address _addressProvider) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_PROVIDER = _addressProvider; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) public override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative]; require( derivativeInfo.pool != address(0), "calcUnderlyingValues: _derivative is not supported" ); underlyings_ = new address[](1); underlyings_[0] = derivativeInfo.invariantProxyAsset; underlyingAmounts_ = new uint256[](1); if (derivativeInfo.invariantProxyAssetDecimals == 18) { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .div(VIRTUAL_PRICE_UNIT); } else { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .mul(10**derivativeInfo.invariantProxyAssetDecimals) .div(VIRTUAL_PRICE_UNIT.mul(2)); } return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return derivativeToInfo[_asset].pool != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add /// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants, /// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools function addDerivatives( address[] calldata _derivatives, address[] calldata _invariantProxyAssets ) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require( _derivatives.length == _invariantProxyAssets.length, "addDerivatives: Unequal arrays" ); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require( _invariantProxyAssets[i] != address(0), "addDerivatives: Empty invariantProxyAsset" ); require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set"); // First, try assuming that the derivative is an LP token ICurveRegistry curveRegistryContract = ICurveRegistry( ICurveAddressProvider(ADDRESS_PROVIDER).get_registry() ); address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]); // If the derivative is not a valid LP token, try to treat it as a liquidity gauge token if (pool == address(0)) { // We cannot confirm whether a liquidity gauge token is a valid token // for a particular liquidity gauge, due to some pools using // old liquidity gauge contracts that did not incorporate a token pool = curveRegistryContract.get_pool_from_lp_token( ICurveLiquidityGaugeToken(_derivatives[i]).lp_token() ); // Likely unreachable as above calls will revert on Curve, but doesn't hurt require( pool != address(0), "addDerivatives: Not a valid LP token or liquidity gauge token" ); } uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals(); derivativeToInfo[_derivatives[i]] = DerivativeInfo({ pool: pool, invariantProxyAsset: _invariantProxyAssets[i], invariantProxyAssetDecimals: invariantProxyAssetDecimals }); // Confirm that a non-zero price can be returned for the registered derivative (, uint256[] memory underlyingAmounts) = calcUnderlyingValues( _derivatives[i], 1 ether ); require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price"); emit DerivativeAdded( _derivatives[i], pool, _invariantProxyAssets[i], invariantProxyAssetDecimals ); } } /// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative"); require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set"); delete derivativeToInfo[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `DerivativeInfo` for a given derivative /// @param _derivative The derivative for which to get the `DerivativeInfo` /// @return derivativeInfo_ The `DerivativeInfo` value function getDerivativeInfo(address _derivative) external view returns (DerivativeInfo memory derivativeInfo_) { return derivativeToInfo[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[email protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeToken interface /// @author Enzyme Council <[email protected]> /// @notice Common interface functions for all Curve liquidity gauge token contracts interface ICurveLiquidityGaugeToken { function lp_token() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityPool interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityPool { function coins(uint256) external view returns (address); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistry interface /// @author Enzyme Council <[email protected]> interface ICurveRegistry { function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); function get_pool_from_lp_token(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../../interfaces/ICurveStableSwapSteth.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase2.sol"; /// @title CurveLiquidityStethAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth) contract CurveLiquidityStethAdapter is AdapterBase2 { int128 private constant POOL_INDEX_ETH = 0; int128 private constant POOL_INDEX_STETH = 1; address private immutable LIQUIDITY_GAUGE_TOKEN; address private immutable LP_TOKEN; address private immutable POOL; address private immutable STETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _liquidityGaugeToken, address _lpToken, address _pool, address _stethToken, address _wethToken ) public AdapterBase2(_integrationManager) { LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken; LP_TOKEN = _lpToken; POOL = _pool; STETH_TOKEN = _stethToken; WETH_TOKEN = _wethToken; // Max approve contracts to spend relevant tokens ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max); ERC20(_stethToken).safeApprove(_pool, type(uint256).max); } /// @dev Needed to receive ETH from redemption and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_LIQUIDITY_STETH"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); if (outgoingWethAmount > 0 && outgoingStethAmount > 0) { spendAssets_ = new address[](2); spendAssets_[0] = WETH_TOKEN; spendAssets_[1] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingWethAmount; spendAssetAmounts_[1] = outgoingStethAmount; } else if (outgoingWethAmount > 0) { spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingWethAmount; } else { spendAssets_ = new address[](1); spendAssets_[0] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStethAmount; } incomingAssets_ = new address[](1); if (_selector == LEND_SELECTOR) { incomingAssets_[0] = LP_TOKEN; } else { incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); if (_selector == REDEEM_SELECTOR) { spendAssets_[0] = LP_TOKEN; } else { spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; if (receiveSingleAsset) { incomingAssets_ = new address[](1); minIncomingAssetAmounts_ = new uint256[](1); if (minIncomingWethAmount == 0) { require( minIncomingStethAmount > 0, "parseAssetsForMethod: No min asset amount specified for receiveSingleAsset" ); incomingAssets_[0] = STETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingStethAmount; } else { require( minIncomingStethAmount == 0, "parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset" ); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingWethAmount; } } else { incomingAssets_ = new address[](2); incomingAssets_[0] = WETH_TOKEN; incomingAssets_[1] = STETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingWethAmount; minIncomingAssetAmounts_[1] = minIncomingStethAmount; } } else if (_selector == STAKE_SELECTOR) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLPTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLPTokenAmount; } else if (_selector == UNSTAKE_SELECTOR) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); } /// @notice Lends assets for steth LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); __stake(ERC20(LP_TOKEN).balanceOf(address(this))); } /// @notice Redeems steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLPTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __redeem( outgoingLPTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } /// @notice Stakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function stake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); __stake(outgoingLPTokenAmount); } /// @notice Unstakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); } /// @notice Unstakes steth LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstakeAndRedeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); __redeem( outgoingLiquidityGaugeTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } // PRIVATE FUNCTIONS /// @dev Helper to execute lend function __lend( uint256 _outgoingWethAmount, uint256 _outgoingStethAmount, uint256 _minIncomingLPTokenAmount ) private { if (_outgoingWethAmount > 0) { IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount); } ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}( [_outgoingWethAmount, _outgoingStethAmount], _minIncomingLPTokenAmount ); } /// @dev Helper to execute redeem function __redeem( uint256 _outgoingLPTokenAmount, uint256 _minIncomingWethAmount, uint256 _minIncomingStethAmount, bool _redeemSingleAsset ) private { if (_redeemSingleAsset) { // "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been // validated in parseAssetsForMethod() if (_minIncomingWethAmount > 0) { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_ETH, _minIncomingWethAmount ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } else { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_STETH, _minIncomingStethAmount ); } } else { ICurveStableSwapSteth(POOL).remove_liquidity( _outgoingLPTokenAmount, [_minIncomingWethAmount, _minIncomingStethAmount] ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } /// @dev Helper to execute stake function __stake(uint256 _lpTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this)); } /// @dev Helper to execute unstake function __unstake(uint256 _liquidityGaugeTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingWethAmount_, uint256 outgoingStethAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256)); } /// @dev Helper to decode the encoded call arguments for redeeming. /// If `receiveSingleAsset_` is `true`, then one (and only one) of /// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0 /// to indicate which asset is to be received. function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, uint256 minIncomingWethAmount_, uint256 minIncomingStethAmount_, bool receiveSingleAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLPTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable /// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) { return LIQUIDITY_GAUGE_TOKEN; } /// @notice Gets the `LP_TOKEN` variable /// @return lpToken_ The `LP_TOKEN` variable value function getLPToken() external view returns (address lpToken_) { return LP_TOKEN; } /// @notice Gets the `POOL` variable /// @return pool_ The `POOL` variable value function getPool() external view returns (address pool_) { return POOL; } /// @notice Gets the `STETH_TOKEN` variable /// @return stethToken_ The `STETH_TOKEN` variable value function getStethToken() external view returns (address stethToken_) { return STETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityGaugeV2 { function deposit(uint256, address) external; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveStableSwapSteth interface /// @author Enzyme Council <[email protected]> interface ICurveStableSwapSteth { function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./AdapterBase.sol"; /// @title AdapterBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters that extends AdapterBase /// @dev This is a temporary contract that will be merged into AdapterBase with the next release abstract contract AdapterBase2 is AdapterBase { /// @dev Provides a standard implementation for transferring incoming assets and /// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action modifier postActionAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; ( , address[] memory spendAssets, , address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); __transferFullAssetBalances(_vaultProxy, incomingAssets); __transferFullAssetBalances(_vaultProxy, spendAssets); } /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, spendAssets); } constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @dev Helper to transfer full asset balances of current contract to the specified target function __transferFullAssetBalances(address _target, address[] memory _assets) internal { for (uint256 i = 0; i < _assets.length; i++) { uint256 balance = ERC20(_assets[i]).balanceOf(address(this)); if (balance > 0) { ERC20(_assets[i]).safeTransfer(_target, balance); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IParaSwapAugustusSwapper.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title ParaSwapAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with ParaSwap contract ParaSwapAdapter is AdapterBase { using SafeMath for uint256; string private constant REFERRER = "enzyme"; address private immutable EXCHANGE; address private immutable TOKEN_TRANSFER_PROXY; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _tokenTransferProxy, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; TOKEN_TRANSFER_PROXY = _tokenTransferProxy; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH refund from sent network fees receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "PARASWAP"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; // Format outgoing assets depending on if there are network fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { // We are not performing special logic if the incomingAsset is the fee asset if (outgoingAsset == WETH_TOKEN) { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees); } else { spendAssets_ = new address[](2); spendAssets_[0] = outgoingAsset; spendAssets_[1] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingAssetAmount; spendAssetAmounts_[1] = totalNetworkFees; } } else { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on ParaSwap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __takeOrder(_vaultProxy, _encodedCallArgs); } // PRIVATE FUNCTIONS /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to decode the encoded callOnIntegration call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics address outgoingAsset_, uint256 outgoingAssetAmount_, IParaSwapAugustusSwapper.Path[] memory paths_ ) { return abi.decode( _encodedCallArgs, (address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[]) ); } /// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata. /// Avoids the stack-too-deep error. function __encodeMultiSwapCallData( address _vaultProxy, address _incomingAsset, uint256 _minIncomingAssetAmount, uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics address _outgoingAsset, uint256 _outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private pure returns (bytes memory multiSwapCallData) { return abi.encodeWithSelector( IParaSwapAugustusSwapper.multiSwap.selector, _outgoingAsset, // fromToken _incomingAsset, // toToken _outgoingAssetAmount, // fromAmount _minIncomingAssetAmount, // toAmount _expectedIncomingAssetAmount, // expectedAmount _paths, // path 0, // mintPrice payable(_vaultProxy), // beneficiary 0, // donationPercentage REFERRER // referrer ); } /// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call. /// Avoids the stack-too-deep error. function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees) private { (bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}( _multiSwapCallData ); require(success, string(returnData)); } /// @dev Helper for the inner takeOrder() logic. /// Avoids the stack-too-deep error. function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private { ( address incomingAsset, uint256 minIncomingAssetAmount, uint256 expectedIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount); // If there are network fees, unwrap enough WETH to cover the fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { __unwrapWeth(totalNetworkFees); } // Get the callData for the low-level multiSwap() call bytes memory multiSwapCallData = __encodeMultiSwapCallData( _vaultProxy, incomingAsset, minIncomingAssetAmount, expectedIncomingAssetAmount, outgoingAsset, outgoingAssetAmount, paths ); // Execute the trade on ParaSwap __executeMultiSwap(multiSwapCallData, totalNetworkFees); // If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned if (totalNetworkFees > 0) { __wrapEth(); } } /// @dev Helper to unwrap specified amount of WETH into ETH. /// Avoids the stack-too-deep error. function __unwrapWeth(uint256 _amount) private { IWETH(payable(WETH_TOKEN)).withdraw(_amount); } /// @dev Helper to wrap all ETH in contract as WETH. /// Avoids the stack-too-deep error. function __wrapEth() private { uint256 ethBalance = payable(address(this)).balance; if (ethBalance > 0) { IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}(); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `TOKEN_TRANSFER_PROXY` variable /// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value function getTokenTransferProxy() external view returns (address tokenTransferProxy_) { return TOKEN_TRANSFER_PROXY; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title ParaSwap IAugustusSwapper interface interface IParaSwapAugustusSwapper { struct Route { address payable exchange; address targetExchange; uint256 percent; bytes payload; uint256 networkFee; } struct Path { address to; uint256 totalNetworkFee; Route[] routes; } function multiSwap( address, address, uint256, uint256, uint256, Path[] calldata, uint256, address payable, uint256, string calldata ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IParaSwapAugustusSwapper.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockParaSwapIntegratee is SwapperBase { using SafeMath for uint256; address private immutable MOCK_CENTRALIZED_RATE_PROVIDER; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public { MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Must be `public` to avoid error function multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, uint256, // toAmount (min received amount) uint256, // expectedAmount IParaSwapAugustusSwapper.Path[] memory _paths, uint256, // mintPrice address, // beneficiary uint256, // donationPercentage string memory // referrer ) public payable returns (uint256) { return __multiSwap(_fromToken, _toToken, _fromAmount, _paths); } /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to avoid the stack-too-deep error function __multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private returns (uint256) { address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _toToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation); uint256 totalNetworkFees = __calcTotalNetworkFees(_paths); address[] memory assetsToIntegratee; uint256[] memory assetsToIntegrateeAmounts; if (totalNetworkFees > 0) { assetsToIntegratee = new address[](2); assetsToIntegratee[1] = ETH_ADDRESS; assetsToIntegrateeAmounts = new uint256[](2); assetsToIntegrateeAmounts[1] = totalNetworkFees; } else { assetsToIntegratee = new address[](1); assetsToIntegrateeAmounts = new uint256[](1); } assetsToIntegratee[0] = _fromToken; assetsToIntegrateeAmounts[0] = _fromAmount; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } /////////////////// // STATE GETTERS // /////////////////// function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) { return blockNumberDeviation; } function getCentralizedRateProvider() external view returns (address centralizedRateProvider_) { return MOCK_CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract SwapperBase is EthConstantMixin { receive() external payable {} function __swapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken, uint256 _actualRate ) internal returns (uint256 destAmount_) { address[] memory assetsToIntegratee = new address[](1); assetsToIntegratee[0] = _srcToken; uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); assetsToIntegrateeAmounts[0] = _srcAmount; address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _destToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = _actualRate; __swap( _trader, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } function __swap( address payable _trader, address[] memory _assetsToIntegratee, uint256[] memory _assetsToIntegrateeAmounts, address[] memory _assetsFromIntegratee, uint256[] memory _assetsFromIntegrateeAmounts ) internal { // Take custody of incoming assets for (uint256 i = 0; i < _assetsToIntegratee.length; i++) { address asset = _assetsToIntegratee[i]; uint256 amount = _assetsToIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsToIntegratee"); require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts"); // Incoming ETH amounts can be ignored if (asset == ETH_ADDRESS) { continue; } ERC20(asset).transferFrom(_trader, address(this), amount); } // Distribute outgoing assets for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) { address asset = _assetsFromIntegratee[i]; uint256 amount = _assetsFromIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsFromIntegratee"); require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts"); if (asset == ETH_ADDRESS) { _trader.transfer(amount); } else { ERC20(asset).transfer(_trader, amount); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; abstract contract EthConstantMixin { address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/NormalizedRateProviderBase.sol"; import "../../utils/SwapperBase.sol"; abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public NormalizedRateProviderBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRate(address _baseAsset, address _quoteAsset) internal view override returns (uint256) { // 1. Return constant if base asset is quote asset if (_baseAsset == _quoteAsset) { return 10**RATE_PRECISION; } // 2. Check for a direct rate uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset]; if (directRate > 0) { return directRate; } // 3. Check for inverse direct rate uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset]; if (iDirectRate > 0) { return 10**(RATE_PRECISION.mul(2)).div(iDirectRate); } // 4. Else return 1 return 10**RATE_PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./RateProviderBase.sol"; abstract contract NormalizedRateProviderBase is RateProviderBase { using SafeMath for uint256; uint256 public immutable RATE_PRECISION; constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public RateProviderBase(_specialAssets, _specialAssetDecimals) { RATE_PRECISION = _ratePrecision; for (uint256 i = 0; i < _defaultRateAssets.length; i++) { for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) { assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] = 10**_ratePrecision; assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] = 10**_ratePrecision; } } } // TODO: move to main contracts' utils for use with prices function __calcDenormalizedQuoteAssetAmount( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _rate ) internal view returns (uint256) { return _rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div( 10**(RATE_PRECISION.add(_baseAssetDecimals)) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract RateProviderBase is EthConstantMixin { mapping(address => mapping(address => uint256)) public assetToAssetRate; // Handles non-ERC20 compliant assets like ETH and USD mapping(address => uint8) public specialAssetToDecimals; constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public { require( _specialAssets.length == _specialAssetDecimals.length, "constructor: _specialAssets and _specialAssetDecimals are uneven lengths" ); for (uint256 i = 0; i < _specialAssets.length; i++) { specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i]; } specialAssetToDecimals[ETH_ADDRESS] = 18; } function __getDecimalsForAsset(address _asset) internal view returns (uint256) { uint256 decimals = specialAssetToDecimals[_asset]; if (decimals == 0) { decimals = uint256(ERC20(_asset).decimals()); } return decimals; } function __getRate(address _baseAsset, address _quoteAsset) internal view virtual returns (uint256) { return assetToAssetRate[_baseAsset][_quoteAsset]; } function setRates( address[] calldata _baseAssets, address[] calldata _quoteAssets, uint256[] calldata _rates ) external { require( _baseAssets.length == _quoteAssets.length, "setRates: _baseAssets and _quoteAssets are uneven lengths" ); require( _baseAssets.length == _rates.length, "setRates: _baseAssets and _rates are uneven lengths" ); for (uint256 i = 0; i < _baseAssets.length; i++) { assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i]; } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title AssetUnitCacheMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin to store a cache of asset units abstract contract AssetUnitCacheMixin { event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit); mapping(address => uint256) private assetToUnit; /// @notice Caches the decimal-relative unit for a given asset /// @param _asset The asset for which to cache the decimal-relative unit /// @dev Callable by any account function cacheAssetUnit(address _asset) public { uint256 prevUnit = getCachedUnitForAsset(_asset); uint256 nextUnit = 10**uint256(ERC20(_asset).decimals()); if (nextUnit != prevUnit) { assetToUnit[_asset] = nextUnit; emit AssetUnitCached(_asset, prevUnit, nextUnit); } } /// @notice Caches the decimal-relative units for multiple given assets /// @param _assets The assets for which to cache the decimal-relative units /// @dev Callable by any account function cacheAssetUnits(address[] memory _assets) public { for (uint256 i; i < _assets.length; i++) { cacheAssetUnit(_assets[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the cached decimal-relative unit for a given asset /// @param _asset The asset for which to get the cached decimal-relative unit /// @return unit_ The cached decimal-relative unit function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) { return assetToUnit[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; /// @title SinglePeggedDerivativePriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed { address private immutable DERIVATIVE; address private immutable UNDERLYING; constructor(address _derivative, address _underlying) public { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "constructor: Unequal decimals" ); DERIVATIVE = _derivative; UNDERLYING = _underlying; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = UNDERLYING; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == DERIVATIVE; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE` variable value /// @return derivative_ The `DERIVATIVE` variable value function getDerivative() external view returns (address derivative_) { return DERIVATIVE; } /// @notice Gets the `UNDERLYING` variable value /// @return underlying_ The `UNDERLYING` variable value function getUnderlying() external view returns (address underlying_) { return UNDERLYING; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SinglePeggedDerivativePriceFeedBase contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _derivative, address _underlying) public SinglePeggedDerivativePriceFeedBase(_derivative, _underlying) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title StakehoundEthPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]yme.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title LidoStethPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/) contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IKyberNetworkProxy.sol"; import "../../../../interfaces/IWETH.sol"; import "../../../../utils/MathHelpers.sol"; import "../utils/AdapterBase.sol"; /// @title KyberAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Kyber Network contract KyberAdapter is AdapterBase, MathHelpers { address private immutable EXCHANGE; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "KYBER_NETWORK"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require( incomingAsset != outgoingAsset, "parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same" ); require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Kyber /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); uint256 minExpectedRate = __calcNormalizedRate( ERC20(outgoingAsset).decimals(), outgoingAssetAmount, ERC20(incomingAsset).decimals(), minIncomingAssetAmount ); if (outgoingAsset == WETH_TOKEN) { __swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate); } else if (incomingAsset == WETH_TOKEN) { __swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate); } else { __swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate); } } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /// @dev Executes a swap of ETH to ERC20 function __swapNativeAssetToToken( address _incomingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}( _incomingAsset, _minExpectedRate ); } /// @dev Executes a swap of ERC20 to ETH function __swapTokenToNativeAsset( address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToEther( _outgoingAsset, _outgoingAssetAmount, _minExpectedRate ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } /// @dev Executes a swap of ERC20 to ERC20 function __swapTokenToToken( address _incomingAsset, address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToToken( _outgoingAsset, _outgoingAssetAmount, _incomingAsset, _minExpectedRate ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Kyber Network interface interface IKyberNetworkProxy { function swapEtherToToken(address, uint256) external payable returns (uint256); function swapTokenToEther( address, uint256, uint256 ) external returns (uint256); function swapTokenToToken( address, uint256, address, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/utils/MathHelpers.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers { using SafeMath for uint256; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable WETH; uint256 private constant PRECISION = 18; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address _centralizedRateProvider, address _weth, uint256 _blockNumberDeviation ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; WETH = _weth; blockNumberDeviation = _blockNumberDeviation; } function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation); __swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount); return msg.value; } function swapTokenToEther( address _srcToken, uint256 _srcAmount, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount); return _srcAmount; } function swapTokenToToken( address _srcToken, uint256 _srcAmount, address _destToken, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount); return _srcAmount; } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } function getExpectedRate( address _srcToken, address _destToken, uint256 _amount ) external returns (uint256 rate_, uint256 worstRate_) { if (_srcToken == ETH_ADDRESS) { _srcToken = WETH; } if (_destToken == ETH_ADDRESS) { _destToken = WETH; } uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken); rate_ = __calcNormalizedRate( ERC20(_srcToken).decimals(), _amount, ERC20(_destToken).decimals(), destAmount ); worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100); } /////////////////// // STATE GETTERS // /////////////////// function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getWeth() public view returns (address) { return WETH; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/MockChainlinkPriceSource.sol"; /// @dev This price source offers two different options getting prices /// The first one is getting a fixed rate, which can be useful for tests /// The second approach calculates dinamically the rate making use of a chainlink price source /// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates } contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates { using SafeMath for uint256; mapping(bytes32 => uint256) private fixedRate; mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator; enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } constructor(address _ethUsdAggregator) public { currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({ aggregator: _ethUsdAggregator, rateAsset: RateAsset.USD }); } function setPriceSourcesForCurrencyKeys( bytes32[] calldata _currencyKeys, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyOwner { require( _currencyKeys.length == _aggregators.length && _rateAssets.length == _aggregators.length ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); } } function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner { fixedRate[_currencyKey] = _rate; } /// @dev Calculates the rate from a currency key against USD function rateAndInvalid(bytes32 _currencyKey) external view override returns (uint256 rate_, bool isInvalid_) { uint256 storedRate = getFixedRate(_currencyKey); if (storedRate != 0) { rate_ = storedRate; } else { AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey); address aggregator = aggregatorInfo.aggregator; if (aggregator == address(0)) { rate_ = 0; isInvalid_ = true; return (rate_, isInvalid_); } uint256 decimals = MockChainlinkPriceSource(aggregator).decimals(); rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul( 10**(uint256(18).sub(decimals)) ); if (aggregatorInfo.rateAsset == RateAsset.ETH) { uint256 ethToUsd = uint256( MockChainlinkPriceSource( getAggregatorFromCurrencyKey(bytes32("ETH")) .aggregator ) .latestAnswer() ); rate_ = rate_.mul(ethToUsd).div(10**8); } } isInvalid_ = (rate_ == 0); return (rate_, isInvalid_); } /////////////////// // STATE GETTERS // /////////////////// function getAggregatorFromCurrencyKey(bytes32 _currencyKey) public view returns (AggregatorInfo memory _aggregator) { return currencyKeyToAggregator[_currencyKey]; } function getFixedRate(bytes32 _currencyKey) public view returns (uint256) { return fixedRate[_currencyKey]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; contract MockChainlinkPriceSource { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); uint256 public DECIMALS; int256 public latestAnswer; uint256 public latestTimestamp; uint256 public roundId; address public aggregator; constructor(uint256 _decimals) public { DECIMALS = _decimals; latestAnswer = int256(10**_decimals); latestTimestamp = now; roundId = 1; aggregator = address(this); } function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external { latestAnswer = _nextAnswer; latestTimestamp = _nextTimestamp; roundId = roundId + 1; emit AnswerUpdated(latestAnswer, roundId, latestTimestamp); } function setAggregator(address _nextAggregator) external { aggregator = _nextAggregator; } function decimals() public view returns (uint256) { return DECIMALS; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockSynthetixToken.sol"; /// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts /// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals /// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts> contract MockSynthetixIntegratee is Ownable, MockToken { using SafeMath for uint256; mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval; mapping(bytes32 => address) private currencyKeyToSynth; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable EXCHANGE_RATES; uint256 private immutable FEE; uint256 private constant UNIT_FEE = 1000; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _centralizedRateProvider, address _exchangeRates, uint256 _fee ) public MockToken(_name, _symbol, _decimals) { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; EXCHANGE_RATES = address(_exchangeRates); FEE = _fee; } receive() external payable {} function exchangeOnBehalfWithTracking( address _exchangeForAddress, bytes32 _srcCurrencyKey, uint256 _srcAmount, bytes32 _destinationCurrencyKey, address, bytes32 ) external returns (uint256 amountReceived_) { require( canExchangeFor(_exchangeForAddress, msg.sender), "exchangeOnBehalfWithTracking: Not approved to act on behalf" ); amountReceived_ = __calculateAndSwap( _exchangeForAddress, _srcAmount, _srcCurrencyKey, _destinationCurrencyKey ); return amountReceived_; } function getAmountsForExchange( uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) public returns ( uint256 amountReceived_, uint256 fee_, uint256 exchangeFeeRate_ ) { address srcToken = currencyKeyToSynth[_srcCurrencyKey]; address destToken = currencyKeyToSynth[_destCurrencyKey]; require( currencyKeyToSynth[_srcCurrencyKey] != address(0) && currencyKeyToSynth[_destCurrencyKey] != address(0), "getAmountsForExchange: Currency key doesn't have an associated synth" ); uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken); exchangeFeeRate_ = FEE; amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE); fee_ = destAmount.sub(amountReceived_); return (amountReceived_, fee_, exchangeFeeRate_); } function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths) external { require( _currencyKeys.length == _synths.length, "setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths" ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToSynth[_currencyKeys[i]] = _synths[i]; } } function approveExchangeOnBehalf(address _delegate) external { authorizerToDelegateToApproval[msg.sender][_delegate] = true; } function __calculateAndSwap( address _exchangeForAddress, uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) private returns (uint256 amountReceived_) { MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]); MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]); require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed"); require( address(destSynth) != address(0), "__calculateAndSwap: Destination synth is not listed" ); require( !srcSynth.isLocked(_exchangeForAddress), "__calculateAndSwap: Cannot settle during waiting period" ); (amountReceived_, , ) = getAmountsForExchange( _srcAmount, _srcCurrencyKey, _destCurrencyKey ); srcSynth.burnFrom(_exchangeForAddress, _srcAmount); destSynth.mintFor(_exchangeForAddress, amountReceived_); destSynth.lock(_exchangeForAddress); return amountReceived_; } function requireAndGetAddress(bytes32 _name, string calldata) external view returns (address resolvedAddress_) { if (_name == "ExchangeRates") { return EXCHANGE_RATES; } return address(this); } function settle(address, bytes32) external returns ( uint256, uint256, uint256 ) {} /////////////////// // STATE GETTERS // /////////////////// function canExchangeFor(address _authorizer, address _delegate) public view returns (bool canExchange_) { return authorizerToDelegateToApproval[_authorizer][_delegate]; } function getExchangeRates() public view returns (address exchangeRates_) { return EXCHANGE_RATES; } function getFee() public view returns (uint256 fee_) { return FEE; } function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) { return currencyKeyToSynth[_currencyKey]; } function getUnitFee() public pure returns (uint256 fee_) { return UNIT_FEE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../prices/CentralizedRateProvider.sol"; import "./utils/SimpleMockIntegrateeBase.sol"; /// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/> /// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/> contract MockUniswapV2Integratee is SwapperBase, Ownable { using SafeMath for uint256; mapping(address => mapping(address => address)) private assetToAssetToPair; address private immutable CENTRALIZED_RATE_PROVIDER; uint256 private constant PRECISION = 18; // Set in %, defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair, address _centralizedRateProvider, uint256 _blockNumberDeviation ) public { addPair(_listOfToken0, _listOfToken1, _listOfPair); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Adds the maximum possible value from {_amountADesired _amountBDesired} /// Makes use of the value interpreter to perform those calculations function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ) { __addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired); } /// @dev Removes the specified amount of liquidity /// Returns 50% of the incoming liquidity value on each token. function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256, uint256, address, uint256 ) public returns (uint256, uint256) { __removeLiquidity(_tokenA, _tokenB, _liquidity); } function swapExactTokensForTokens( uint256 amountIn, uint256, address[] calldata path, address, uint256 ) external returns (uint256[] memory) { uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation); __swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut); } /// @dev We don't calculate any intermediate values here because they aren't actually used /// Returns the randomized by sender value of the edge path assets function getAmountsOut(uint256 _amountIn, address[] calldata _path) external returns (uint256[] memory amounts_) { require(_path.length >= 2, "getAmountsOut: path must be >= 2"); address assetIn = _path[0]; address assetOut = _path[_path.length - 1]; uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut); amounts_ = new uint256[](_path.length); amounts_[0] = _amountIn; amounts_[_path.length - 1] = amountOut; return amounts_; } function addPair( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair ) public onlyOwner { require( _listOfPair.length == _listOfToken0.length, "constructor: _listOfPair and _listOfToken0 have an unequal length" ); require( _listOfPair.length == _listOfToken1.length, "constructor: _listOfPair and _listOfToken1 have an unequal length" ); for (uint256 i; i < _listOfPair.length; i++) { address token0 = _listOfToken0[i]; address token1 = _listOfToken1[i]; address pair = _listOfPair[i]; assetToAssetToPair[token0][token1] = pair; assetToAssetToPair[token1][token0] = pair; } } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } // PRIVATE FUNCTIONS /// Avoids stack-too-deep error. function __addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired ) private { address pair = getPair(_tokenA, _tokenB); uint256 amountA; uint256 amountB; uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenA, _amountADesired, _tokenB); uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA); if (amountBFromA >= _amountBDesired) { amountA = amountAFromB; amountB = _amountBDesired; } else { amountA = _amountADesired; amountB = amountBFromA; } uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA); // Calculate the inverse rate to know the amount of LPToken to return from a unit of token uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken); // Total liquidity can be calculated as 2x liquidity from amount A uint256 totalLiquidity = uint256(2).mul( amountA.mul(inverseRate).div(uint256(10**PRECISION)) ); require( ERC20(pair).balanceOf(address(this)) >= totalLiquidity, "__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount" ); address[] memory assetsToIntegratee = new address[](2); uint256[] memory assetsToIntegrateeAmounts = new uint256[](2); address[] memory assetsFromIntegratee = new address[](1); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsToIntegratee[0] = _tokenA; assetsToIntegrateeAmounts[0] = amountA; assetsToIntegratee[1] = _tokenB; assetsToIntegrateeAmounts[1] = amountB; assetsFromIntegratee[0] = pair; assetsFromIntegrateeAmounts[0] = totalLiquidity; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /// Avoids stack-too-deep error. function __removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity ) private { address pair = assetToAssetToPair[_tokenA][_tokenB]; require(pair != address(0), "__removeLiquidity: this pair doesn't exist"); uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenA) .div(uint256(2)); uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenB) .div(uint256(2)); address[] memory assetsToIntegratee = new address[](1); uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); address[] memory assetsFromIntegratee = new address[](2); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2); assetsToIntegratee[0] = pair; assetsToIntegrateeAmounts[0] = _liquidity; assetsFromIntegratee[0] = _tokenA; assetsFromIntegrateeAmounts[0] = amountA; assetsFromIntegratee[1] = _tokenB; assetsFromIntegrateeAmounts[1] = amountB; require( ERC20(_tokenA).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount" ); require( ERC20(_tokenB).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount" ); __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /////////////////// // STATE GETTERS // /////////////////// /// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue function feeTo() external pure returns (address) { return address(0); } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } function getPair(address _token0, address _token1) public view returns (address) { return assetToAssetToPair[_token0][_token1]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockIntegrateeBase.sol"; abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public MockIntegrateeBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRateAndSwapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken ) internal returns (uint256 destAmount_) { uint256 actualRate = __getRate(_srcToken, _destToken); __swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate); return actualRate; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../../prices/CentralizedRateProvider.sol"; import "../../utils/SwapperBase.sol"; contract MockCTokenBase is ERC20, SwapperBase, Ownable { address internal immutable TOKEN; address internal immutable CENTRALIZED_RATE_PROVIDER; uint256 internal rate; mapping(address => mapping(address => uint256)) internal _allowances; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); TOKEN = _token; CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; rate = _initialRate; } function approve(address _spender, uint256 _amount) public virtual override returns (bool) { _allowances[msg.sender][_spender] = _amount; return true; } /// @dev Overriden `allowance` function, give the integratee infinite approval by default function allowance(address _owner, address _spender) public view override returns (uint256) { if (_spender == address(this) || _owner == _spender) { return 2**256 - 1; } else { return _allowances[_owner][_spender]; } } /// @dev Necessary as this contract doesn't directly inherit from MockToken function mintFor(address _who, uint256 _amount) external onlyOwner { _mint(_who, _amount); } /// @dev Necessary to allow updates on persistent deployments (e.g Kovan) function setRate(uint256 _rate) public onlyOwner { rate = _rate; } function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual override returns (bool) { _transfer(_sender, _recipient, _amount); return true; } // INTERNAL FUNCTIONS /// @dev Calculates the cTokenAmount given a tokenAmount /// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) { uint256 tokenDecimals = ERC20(TOKEN).decimals(); uint256 cTokenDecimals = decimals(); // Result in Token Decimals uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN); // Result in cToken decimals uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div( tokenPerCTokenUnit ); // Amount in token decimals, result in cToken decimals cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Part of ICERC20 token interface function underlying() public view returns (address) { return TOKEN; } /// @dev Part of ICERC20 token interface. /// Called from CompoundPriceFeed, returns the actual Rate cToken/Token function exchangeRateStored() public view returns (uint256) { return rate; } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCTokenIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate) {} function mint(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN, _amount, address(this) ); __swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount); return _amount; } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCEtherIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _weth, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate) {} function mint() external payable { uint256 amount = msg.value; uint256 destAmount = __calcCTokenAmount(amount); __swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount); } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveSwapsERC20.sol"; import "../../../../interfaces/ICurveSwapsEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CurveExchangeAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for swapping assets on Curve <https://www.curve.fi/> contract CurveExchangeAdapter is AdapterBase { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private immutable ADDRESS_PROVIDER; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _addressProvider, address _wethToken ) public AdapterBase(_integrationManager) { ADDRESS_PROVIDER = _addressProvider; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_EXCHANGE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require(pool != address(0), "parseAssetsForMethod: No pool address provided"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Curve /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2); __takeOrder( _vaultProxy, swaps, pool, outgoingAsset, outgoingAssetAmount, incomingAsset, minIncomingAssetAmount ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the take order encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address pool_, address outgoingAsset_, uint256 outgoingAssetAmount_, address incomingAsset_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256)); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, address _swaps, address _pool, address _outgoingAsset, uint256 _outgoingAssetAmount, address _incomingAsset, uint256 _minIncomingAssetAmount ) private { if (_outgoingAsset == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount); ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}( _pool, ETH_ADDRESS, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } else if (_incomingAsset == WETH_TOKEN) { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, ETH_ADDRESS, _outgoingAssetAmount, _minIncomingAssetAmount, address(this) ); // wrap received ETH and send back to the vault uint256 receivedAmount = payable(address(this)).balance; IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}(); ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount); } else { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsERC20 Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsERC20 { function exchange( address, address, address, uint256, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsEther Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsEther { function exchange( address, address, address, uint256, uint256, address ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; import "./SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title PeggedDerivativesPriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings, /// and have the same decimals as their underlying abstract contract PeggedDerivativesPriceFeedBase is IDerivativePriceFeed, SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address underlying = getUnderlyingForDerivative(_derivative); require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = underlying; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return getUnderlyingForDerivative(_asset) != address(0); } /// @dev Provides validation that the derivative and underlying have the same decimals. /// Can be overrode by the inheriting price feed using super() to implement further validation. function __validateDerivative(address _derivative, address _underlying) internal virtual override { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "__validateDerivative: Unequal decimals" ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/DispatcherOwnerMixin.sol"; /// @title SingleUnderlyingDerivativeRegistryMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin for derivative price feeds that handle multiple derivatives /// that each have a single underlying asset abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address indexed underlying); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToUnderlying; constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {} /// @notice Adds derivatives with corresponding underlyings to the price feed /// @param _derivatives The derivatives to add /// @param _underlyings The corresponding underlyings to add function addDerivatives(address[] memory _derivatives, address[] memory _underlyings) external virtual onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require(_underlyings[i] != address(0), "addDerivatives: Empty underlying"); require( getUnderlyingForDerivative(_derivatives[i]) == address(0), "addDerivatives: Value already set" ); __validateDerivative(_derivatives[i], _underlyings[i]); derivativeToUnderlying[_derivatives[i]] = _underlyings[i]; emit DerivativeAdded(_derivatives[i], _underlyings[i]); } } /// @notice Removes derivatives from the price feed /// @param _derivatives The derivatives to remove function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require( getUnderlyingForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Value not set" ); delete derivativeToUnderlying[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair function __validateDerivative(address, address) internal virtual { // UNIMPLEMENTED } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the underlying asset for a given derivative /// @param _derivative The derivative for which to get the underlying asset /// @return underlying_ The underlying asset function getUnderlyingForDerivative(address _derivative) public view returns (address underlying_) { return derivativeToUnderlying[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of PeggedDerivativesPriceFeedBase contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase { constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAaveProtocolDataProvider.sol"; import "./utils/PeggedDerivativesPriceFeedBase.sol"; /// @title AavePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Aave contract AavePriceFeed is PeggedDerivativesPriceFeedBase { address private immutable PROTOCOL_DATA_PROVIDER; constructor(address _dispatcher, address _protocolDataProvider) public PeggedDerivativesPriceFeedBase(_dispatcher) { PROTOCOL_DATA_PROVIDER = _protocolDataProvider; } function __validateDerivative(address _derivative, address _underlying) internal override { super.__validateDerivative(_derivative, _underlying); (address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER) .getReserveTokensAddresses(_underlying); require( aTokenAddress == _derivative, "__validateDerivative: Invalid aToken or token provided" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value /// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value function getProtocolDataProvider() external view returns (address protocolDataProvider_) { return PROTOCOL_DATA_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveProtocolDataProvider interface /// @author Enzyme Council <[email protected]> interface IAaveProtocolDataProvider { function getReserveTokensAddresses(address) external view returns ( address, address, address ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol"; import "../../../../interfaces/IAaveLendingPool.sol"; import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol"; import "../utils/AdapterBase.sol"; /// @title AaveAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Aave Lending <https://aave.com/> contract AaveAdapter is AdapterBase { address private immutable AAVE_PRICE_FEED; address private immutable LENDING_POOL_ADDRESS_PROVIDER; uint16 private constant REFERRAL_CODE = 158; constructor( address _integrationManager, address _lendingPoolAddressProvider, address _aavePriceFeed ) public AdapterBase(_integrationManager) { LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider; AAVE_PRICE_FEED = _aavePriceFeed; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "AAVE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = aToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else if (_selector == REDEEM_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = aToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).deposit( spendAssets[0], spendAssetAmounts[0], _vaultProxy, REFERRAL_CODE ); } /// @notice Redeems an amount of aTokens from AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).withdraw( incomingAssets[0], spendAssetAmounts[0], _vaultProxy ); } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address aToken, uint256 amount) { return abi.decode(_encodedCallArgs, (address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AAVE_PRICE_FEED` variable /// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value function getAavePriceFeed() external view returns (address aavePriceFeed_) { return AAVE_PRICE_FEED; } /// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable /// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value function getLendingPoolAddressProvider() external view returns (address lendingPoolAddressProvider_) { return LENDING_POOL_ADDRESS_PROVIDER; } /// @notice Gets the `REFERRAL_CODE` variable /// @return referralCode_ The `REFERRAL_CODE` variable value function getReferralCode() external pure returns (uint16 referralCode_) { return REFERRAL_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPool interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPool { function deposit( address, uint256, address, uint16 ) external; function withdraw( address, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPoolAddressProvider interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPoolAddressProvider { function getLendingPool() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Non-whitelisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Must whitelist denominationAsset" ); __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (!isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /// @title AddressListPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice An abstract mixin contract for policies that use an address list abstract contract AddressListPolicyMixin { using EnumerableSet for EnumerableSet.AddressSet; event AddressesAdded(address indexed comptrollerProxy, address[] items); event AddressesRemoved(address indexed comptrollerProxy, address[] items); mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList; // EXTERNAL FUNCTIONS /// @notice Get all addresses in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @return list_ The addresses in the fund's list function getList(address _comptrollerProxy) external view returns (address[] memory list_) { list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length()); for (uint256 i = 0; i < list_.length; i++) { list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i); } return list_; } // PUBLIC FUNCTIONS /// @notice Check if an address is in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _item The address to check against the list /// @return isInList_ True if the address is in the list function isInList(address _comptrollerProxy, address _item) public view returns (bool isInList_) { return comptrollerProxyToList[_comptrollerProxy].contains(_item); } // INTERNAL FUNCTIONS /// @dev Helper to add addresses to the calling fund's list function __addToList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__addToList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].add(_items[i]), "__addToList: Address already exists in list" ); } emit AddressesAdded(_comptrollerProxy, _items); } /// @dev Helper to remove addresses from the calling fund's list function __removeFromList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__removeFromList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].remove(_items[i]), "__removeFromList: Address does not exist in list" ); } emit AddressesRemoved(_comptrollerProxy, _items); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Blacklisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( !assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Cannot blacklist denominationAsset" ); __addToList(_comptrollerProxy, assets); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of adapters for use by a fund contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPreValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns (address adapter_, bytes4 selector_) { return abi.decode(_encodedRuleArgs, (address, bytes4)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title GuaranteedRedemption Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that guarantees that shares will either be continuously redeemable or /// redeemable within a predictable daily window by preventing trading during a configurable daily period contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin { using SafeMath for uint256; event AdapterAdded(address adapter); event AdapterRemoved(address adapter); event FundSettingsSet( address indexed comptrollerProxy, uint256 startTimestamp, uint256 duration ); event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer); struct RedemptionWindow { uint256 startTimestamp; uint256 duration; } uint256 private constant ONE_DAY = 24 * 60 * 60; mapping(address => bool) private adapterToCanBlockRedemption; mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow; uint256 private redemptionWindowBuffer; constructor( address _policyManager, address _fundDeployer, uint256 _redemptionWindowBuffer, address[] memory _redemptionBlockingAdapters ) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) { redemptionWindowBuffer = _redemptionWindowBuffer; __addRedemptionBlockingAdapters(_redemptionBlockingAdapters); } // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { (uint256 startTimestamp, uint256 duration) = abi.decode( _encodedSettings, (uint256, uint256) ); if (startTimestamp == 0) { require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0"); return; } // Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer require( duration > 0 && duration <= 23 hours, "addFundSettings: duration must be between 1 second and 23 hours" ); comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp; comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration; emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "GUARANTEED_REDEMPTION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { if (!adapterCanBlockRedemption(_adapter)) { return true; } RedemptionWindow memory redemptionWindow = comptrollerProxyToRedemptionWindow[_comptrollerProxy]; // If no RedemptionWindow is set, the fund can never use redemption-blocking adapters if (redemptionWindow.startTimestamp == 0) { return false; } uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart( redemptionWindow.startTimestamp ); // A fund can't trade during its redemption window, nor in the buffer beforehand. // The lower bound is only relevant when the startTimestamp is in the future, // so we check it last. if ( block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) || block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer) ) { return true; } return false; } /// @notice Sets a new value for the redemptionWindowBuffer variable /// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer /// @dev The redemptionWindowBuffer is added to the beginning of the redemption window, /// and should always be >= the longest potential block on redemption amongst all adapters. /// (e.g., Synthetix blocks token transfers during a timelock after trading synths) function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer) external onlyFundDeployerOwner { uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer; require( _nextRedemptionWindowBuffer != prevRedemptionWindowBuffer, "setRedemptionWindowBuffer: Value already set" ); redemptionWindowBuffer = _nextRedemptionWindowBuffer; emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } // PUBLIC FUNCTIONS /// @notice Calculates the start of the most recent redemption window /// @param _startTimestamp The initial startTimestamp for the redemption window /// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window function calcLatestRedemptionWindowStart(uint256 _startTimestamp) public view returns (uint256 latestRedemptionWindowStart_) { if (block.timestamp <= _startTimestamp) { return _startTimestamp; } uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp); uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY); return block.timestamp.sub(timeSincePeriodStart); } /////////////////////////////////////////// // REDEMPTION-BLOCKING ADAPTERS REGISTRY // /////////////////////////////////////////// /// @notice Add adapters which can block shares redemption /// @param _adapters The addresses of adapters to be added function addRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "__addRedemptionBlockingAdapters: _adapters cannot be empty" ); __addRedemptionBlockingAdapters(_adapters); } /// @notice Remove adapters which can block shares redemption /// @param _adapters The addresses of adapters to be removed function removeRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "removeRedemptionBlockingAdapters: _adapters cannot be empty" ); for (uint256 i; i < _adapters.length; i++) { require( adapterCanBlockRedemption(_adapters[i]), "removeRedemptionBlockingAdapters: adapter is not added" ); adapterToCanBlockRedemption[_adapters[i]] = false; emit AdapterRemoved(_adapters[i]); } } /// @dev Helper to mark adapters that can block shares redemption function __addRedemptionBlockingAdapters(address[] memory _adapters) private { for (uint256 i; i < _adapters.length; i++) { require( _adapters[i] != address(0), "__addRedemptionBlockingAdapters: adapter cannot be empty" ); require( !adapterCanBlockRedemption(_adapters[i]), "__addRedemptionBlockingAdapters: adapter already added" ); adapterToCanBlockRedemption[_adapters[i]] = true; emit AdapterAdded(_adapters[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `redemptionWindowBuffer` variable /// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) { return redemptionWindowBuffer; } /// @notice Gets the RedemptionWindow settings for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return redemptionWindow_ The RedemptionWindow settings function getRedemptionWindowForFund(address _comptrollerProxy) external view returns (RedemptionWindow memory redemptionWindow_) { return comptrollerProxyToRedemptionWindow[_comptrollerProxy]; } /// @notice Checks whether an adapter can block shares redemption /// @param _adapter The address of the adapter to check /// @return canBlockRedemption_ True if the adapter can block shares redemption function adapterCanBlockRedemption(address _adapter) public view returns (bool canBlockRedemption_) { return adapterToCanBlockRedemption[_adapter]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of adapters from use by a fund contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return !isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title InvestorWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "INVESTOR_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investor The investor for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _investor) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _investor); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address buyer, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, buyer); } /// @dev Helper to update the investor whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreBuyShares policy hook abstract contract PreBuySharesValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256, uint256, uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title MinMaxInvestment Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that restricts the amount of the fund's denomination asset that a user can /// send in a single call to buy shares in a fund contract MinMaxInvestment is PreBuySharesValidatePolicyBase { event FundSettingsSet( address indexed comptrollerProxy, uint256 minInvestmentAmount, uint256 maxInvestmentAmount ); struct FundSettings { uint256 minInvestmentAmount; uint256 maxInvestmentAmount; } mapping(address => FundSettings) private comptrollerProxyToFundSettings; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MIN_MAX_INVESTMENT"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investmentAmount The investment amount for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, uint256 _investmentAmount) public view returns (bool isValid_) { uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount; uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount; // Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund // temporarily if (minInvestmentAmount == 0) { return _investmentAmount <= maxInvestmentAmount; } else if (maxInvestmentAmount == 0) { return _investmentAmount >= minInvestmentAmount; } return _investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, investmentAmount); } /// @dev Helper to set the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private { (uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode( _encodedSettings, (uint256, uint256) ); require( maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount, "__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount" ); comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount = minInvestmentAmount; comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount = maxInvestmentAmount; emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the min and max investment amount for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return fundSettings_ The fund settings function getFundSettings(address _comptrollerProxy) external view returns (FundSettings memory fundSettings_) { return comptrollerProxyToFundSettings[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/BuySharesSetupPolicyBase.sol"; /// @title BuySharesCallerWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "BUY_SHARES_CALLER_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _buySharesCaller The buyShares caller for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _buySharesCaller) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _buySharesCaller); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address caller, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, caller); } /// @dev Helper to update the whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesSetupPolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook abstract contract BuySharesSetupPolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address caller_, uint256[] memory investmentAmounts_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/vault/VaultLib.sol"; import "../utils/AdapterBase.sol"; /// @title TrackedAssetsAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops) contract TrackedAssetsAdapter is AdapterBase { constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @notice Add multiple assets to the Vault's list of tracked assets /// @dev No need to perform any validation or implement any logic function addTrackedAssets( address, bytes calldata, bytes calldata ) external view {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "TRACKED_ASSETS"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require( _selector == ADD_TRACKED_ASSETS_SELECTOR, "parseAssetsForMethod: _selector invalid" ); incomingAssets_ = __decodeCallArgs(_encodedCallArgs); minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length); for (uint256 i; i < minIncomingAssetAmounts_.length; i++) { minIncomingAssetAmounts_[i] = 1; } return ( spendAssetsHandleType_, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address[] memory incomingAssets_) { return abi.decode(_encodedCallArgs, (address[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/ProxiableVaultLib.sol"; /// @title VaultProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822 /// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract VaultProxy { constructor(bytes memory _constructData, address _vaultLib) public { // "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to // `bytes32(keccak256('mln.proxiable.vaultlib'))` require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_vaultLib).proxiableUUID(), "constructor: _vaultLib not compatible" ); assembly { // solium-disable-line sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib) } (bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line require(success, string(returnData)); } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigrationHookHandler.sol"; import "../utils/IMigratableVault.sol"; import "../vault/VaultProxy.sol"; import "./IDispatcher.sol"; /// @title Dispatcher Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract linking multiple releases. /// It handles the deployment of new VaultProxy instances, /// and the regulation of fund migration from a previous release to the current one. /// It can also be referred to for access-control based on this contract's owner. /// @dev DO NOT EDIT CONTRACT contract Dispatcher is IDispatcher { event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer); event MigrationCancelled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationExecuted( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationSignaled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock); event NominatedOwnerSet(address indexed nominatedOwner); event NominatedOwnerRemoved(address indexed nominatedOwner); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event MigrationInCancelHookFailed( bytes failureReturnData, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event MigrationOutHookFailed( bytes failureReturnData, IMigrationHookHandler.MigrationOutHook hook, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event SharesTokenSymbolSet(string _nextSymbol); event VaultProxyDeployed( address indexed fundDeployer, address indexed owner, address vaultProxy, address indexed vaultLib, address vaultAccessor, string fundName ); struct MigrationRequest { address nextFundDeployer; address nextVaultAccessor; address nextVaultLib; uint256 executableTimestamp; } address private currentFundDeployer; address private nominatedOwner; address private owner; uint256 private migrationTimelock; string private sharesTokenSymbol; mapping(address => address) private vaultProxyToFundDeployer; mapping(address => MigrationRequest) private vaultProxyToMigrationRequest; modifier onlyCurrentFundDeployer() { require( msg.sender == currentFundDeployer, "Only the current FundDeployer can call this function" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the contract owner can call this function"); _; } constructor() public { migrationTimelock = 2 days; owner = msg.sender; sharesTokenSymbol = "ENZF"; } ///////////// // GENERAL // ///////////// /// @notice Sets a new `symbol` value for VaultProxy instances /// @param _nextSymbol The symbol value to set function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner { sharesTokenSymbol = _nextSymbol; emit SharesTokenSymbolSet(_nextSymbol); } //////////////////// // ACCESS CONTROL // //////////////////// /// @notice Claim ownership of the contract function claimOwnership() external override { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external override onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Set a new FundDeployer for use within the contract /// @param _nextFundDeployer The address of the FundDeployer contract function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner { require( _nextFundDeployer != address(0), "setCurrentFundDeployer: _nextFundDeployer cannot be empty" ); require( __isContract(_nextFundDeployer), "setCurrentFundDeployer: Non-contract _nextFundDeployer" ); address prevFundDeployer = currentFundDeployer; require( _nextFundDeployer != prevFundDeployer, "setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer" ); currentFundDeployer = _nextFundDeployer; emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } /// @dev Helper to check whether an address is a deployed contract function __isContract(address _who) private view returns (bool isContract_) { uint256 size; assembly { size := extcodesize(_who) } return size > 0; } //////////////// // DEPLOYMENT // //////////////// /// @notice Deploys a VaultProxy /// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy /// @param _owner The account to set as the VaultProxy's owner /// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor /// @param _fundName The name of the fund /// @dev Input validation should be handled by the VaultProxy during deployment function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external override onlyCurrentFundDeployer returns (address vaultProxy_) { require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor"); bytes memory constructData = abi.encodeWithSelector( IMigratableVault.init.selector, _owner, _vaultAccessor, _fundName ); vaultProxy_ = address(new VaultProxy(constructData, _vaultLib)); address fundDeployer = msg.sender; vaultProxyToFundDeployer[vaultProxy_] = fundDeployer; emit VaultProxyDeployed( fundDeployer, _owner, vaultProxy_, _vaultLib, _vaultAccessor, _fundName ); return vaultProxy_; } //////////////// // MIGRATIONS // //////////////// /// @notice Cancels a pending migration request /// @param _vaultProxy The VaultProxy contract for which to cancel the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored /// @dev Because this function must also be callable by a permissioned migrator, it has an /// extra migration hook to the nextFundDeployer for the case where cancelMigration() /// is called directly (rather than via the nextFundDeployer). function cancelMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require(nextFundDeployer != address(0), "cancelMigration: No migration request exists"); // TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works. require( msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender), "cancelMigration: Not an allowed caller" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; uint256 executableTimestamp = request.executableTimestamp; delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostCancel, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); __invokeMigrationInCancelHook( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationCancelled( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Executes a pending migration request /// @param _vaultProxy The VaultProxy contract for which to execute the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored function executeMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require( nextFundDeployer != address(0), "executeMigration: No migration request exists for _vaultProxy" ); require( msg.sender == nextFundDeployer, "executeMigration: Only the target FundDeployer can call this function" ); require( nextFundDeployer == currentFundDeployer, "executeMigration: The target FundDeployer is no longer the current FundDeployer" ); uint256 executableTimestamp = request.executableTimestamp; require( block.timestamp >= executableTimestamp, "executeMigration: The migration timelock has not elapsed" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); // Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib); IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor); // Update the FundDeployer that migrated the VaultProxy vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer; // Remove the migration request delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationExecuted( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Sets a new migration timelock /// @param _nextTimelock The number of seconds for the new timelock function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner { uint256 prevTimelock = migrationTimelock; require( _nextTimelock != prevTimelock, "setMigrationTimelock: _nextTimelock is the current timelock" ); migrationTimelock = _nextTimelock; emit MigrationTimelockSet(prevTimelock, _nextTimelock); } /// @notice Signals a migration by creating a migration request /// @param _vaultProxy The VaultProxy contract for which to signal migration /// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy /// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy /// @param _bypassFailure True if a failure in either migration hook should be ignored function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external override onlyCurrentFundDeployer { require( __isContract(_nextVaultAccessor), "signalMigration: Non-contract _nextVaultAccessor" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist"); address nextFundDeployer = msg.sender; require( nextFundDeployer != prevFundDeployer, "signalMigration: Can only migrate to a new FundDeployer" ); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); uint256 executableTimestamp = block.timestamp + migrationTimelock; vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({ nextFundDeployer: nextFundDeployer, nextVaultAccessor: _nextVaultAccessor, nextVaultLib: _nextVaultLib, executableTimestamp: executableTimestamp }); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); emit MigrationSignaled( _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, executableTimestamp ); } /// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to, /// which can optionally be implemented on the FundDeployer function __invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _nextFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationInCancelHook.selector, _vaultProxy, _prevFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked("MigrationOutCancelHook: ", returnData)) ); emit MigrationInCancelHookFailed( returnData, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of, /// which can optionally be implemented on the FundDeployer function __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook _hook, address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _prevFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationOutHook.selector, _hook, _vaultProxy, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData)) ); emit MigrationOutHookFailed( returnData, _hook, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to return a revert reason string prefix for a given MigrationOutHook function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook) private pure returns (string memory failureReasonPrefix_) { if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) { return "MigrationOutHook.PreSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) { return "MigrationOutHook.PostSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) { return "MigrationOutHook.PreMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) { return "MigrationOutHook.PostMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) { return "MigrationOutHook.PostCancel: "; } return ""; } /////////////////// // STATE GETTERS // /////////////////// // Provides several potentially helpful getters that are not strictly necessary /// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds /// @return currentFundDeployer_ The current FundDeployer contract address function getCurrentFundDeployer() external view override returns (address currentFundDeployer_) { return currentFundDeployer; } /// @notice Gets the FundDeployer with which a given VaultProxy is associated /// @param _vaultProxy The VaultProxy instance /// @return fundDeployer_ The FundDeployer contract address function getFundDeployerForVaultProxy(address _vaultProxy) external view override returns (address fundDeployer_) { return vaultProxyToFundDeployer[_vaultProxy]; } /// @notice Gets the details of a pending migration request for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return nextFundDeployer_ The FundDeployer contract address from which the migration /// request was made /// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy /// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy /// @return executableTimestamp_ The timestamp at which the migration request can be executed function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view override returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ) { MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy]; if (r.executableTimestamp > 0) { return ( r.nextFundDeployer, r.nextVaultAccessor, r.nextVaultLib, r.executableTimestamp ); } } /// @notice Gets the amount of time that must pass between signaling and executing a migration /// @return migrationTimelock_ The timelock value (in seconds) function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) { return migrationTimelock; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view override returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the owner of this contract /// @return owner_ The account that is the owner function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the shares token `symbol` value for use in VaultProxy instances /// @return sharesTokenSymbol_ The `symbol` value function getSharesTokenSymbol() external view override returns (string memory sharesTokenSymbol_) { return sharesTokenSymbol; } /// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed /// @param _vaultProxy The VaultProxy instance /// @return secondsRemaining_ The number of seconds remaining on the timelock function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view override returns (uint256 secondsRemaining_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; if (executableTimestamp == 0) { return 0; } if (block.timestamp >= executableTimestamp) { return 0; } return executableTimestamp - block.timestamp; } /// @notice Checks whether a migration request that is executable exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasExecutableRequest_ True if a migration request exists and is executable function hasExecutableMigrationRequest(address _vaultProxy) external view override returns (bool hasExecutableRequest_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; return executableTimestamp > 0 && block.timestamp >= executableTimestamp; } /// @notice Checks whether a migration request exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasMigrationRequest_ True if a migration request exists function hasMigrationRequest(address _vaultProxy) external view override returns (bool hasMigrationRequest_) { return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../persistent/vault/VaultLibBaseCore.sol"; /// @title MockVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A mock VaultLib implementation that only extends VaultLibBaseCore contract MockVaultLib is VaultLibBaseCore { function getAccessor() external view returns (address) { return accessor; } function getCreator() external view returns (address) { return creator; } function getMigrator() external view returns (address) { return migrator; } function getOwner() external view returns (address) { return owner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ICERC20 Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound tokens (cTokens) interface ICERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256) external returns (uint256); function redeem(uint256) external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CompoundPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Compound Tokens (cTokens) contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event CTokenAdded(address indexed cToken, address indexed token); uint256 private constant CTOKEN_RATE_DIVISOR = 10**18; mapping(address => address) private cTokenToToken; constructor( address _dispatcher, address _weth, address _ceth, address[] memory cERC20Tokens ) public DispatcherOwnerMixin(_dispatcher) { // Set cEth cTokenToToken[_ceth] = _weth; emit CTokenAdded(_ceth, _weth); // Set any other cTokens if (cERC20Tokens.length > 0) { __addCERC20Tokens(cERC20Tokens); } } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = cTokenToToken[_derivative]; require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative"); underlyingAmounts_ = new uint256[](1); // Returns a rate scaled to 10^18 underlyingAmounts_[0] = _derivativeAmount .mul(ICERC20(_derivative).exchangeRateStored()) .div(CTOKEN_RATE_DIVISOR); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return cTokenToToken[_asset] != address(0); } ////////////////////// // CTOKENS REGISTRY // ////////////////////// /// @notice Adds cTokens to the price feed /// @param _cTokens cTokens to add /// @dev Only allows CERC20 tokens. CEther is set in the constructor. function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner { __addCERC20Tokens(_cTokens); } /// @dev Helper to add cTokens function __addCERC20Tokens(address[] memory _cTokens) private { require(_cTokens.length > 0, "__addCTokens: Empty _cTokens"); for (uint256 i; i < _cTokens.length; i++) { require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set"); address token = ICERC20(_cTokens[i]).underlying(); cTokenToToken[_cTokens[i]] = token; emit CTokenAdded(_cTokens[i], token); } } //////////////////// // STATE GETTERS // /////////////////// /// @notice Returns the underlying asset of a given cToken /// @param _cToken The cToken for which to get the underlying asset /// @return token_ The underlying token function getTokenFromCToken(address _cToken) public view returns (address token_) { return cTokenToToken[_cToken]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../../interfaces/ICEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CompoundAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Compound <https://compound.finance/> contract CompoundAdapter is AdapterBase { address private immutable COMPOUND_PRICE_FEED; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _compoundPriceFeed, address _wethToken ) public AdapterBase(_integrationManager) { COMPOUND_PRICE_FEED = _compoundPriceFeed; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during cEther lend/redeem receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "COMPOUND"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = tokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = cToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minCTokenAmount; } else if (_selector == REDEEM_SELECTOR) { (address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = cToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = cTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); if (spendAssets[0] == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]); ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}(); } else { __approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]); ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]); } } /// @notice Redeems an amount of cTokens from Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]); if (incomingAssets[0] == WETH_TOKEN) { IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address cToken_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `COMPOUND_PRICE_FEED` variable /// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) { return COMPOUND_PRICE_FEED; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; /// @title ICEther Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound Ether interface ICEther { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title IChai Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Chai contract interface IChai is IERC20 { function exit(address, uint256) external; function join(address, uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IChai.sol"; import "../utils/AdapterBase.sol"; /// @title ChaiAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Chai <https://github.com/dapphub/chai> contract ChaiAdapter is AdapterBase { address private immutable CHAI; address private immutable DAI; constructor( address _integrationManager, address _chai, address _dai ) public AdapterBase(_integrationManager) { CHAI = _chai; DAI = _dai; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "CHAI"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = DAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = daiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = CHAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minChaiAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = CHAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = chaiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = DAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minDaiAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lend Dai for Chai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(DAI, CHAI, daiAmount); // Execute Lend on Chai // Chai.join allows specifying the vaultProxy as the destination of Chai tokens IChai(CHAI).join(_vaultProxy, daiAmount); } /// @notice Redeem Chai for Dai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs); // Execute redeem on Chai // Chai.exit sends Dai back to the adapter IChai(CHAI).exit(address(this), chaiAmount); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/SwapperBase.sol"; contract MockGenericIntegratee is SwapperBase { function swap( address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( msg.sender, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } function swapOnBehalf( address payable _trader, address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( _trader, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; import "../utils/SwapperBase.sol"; contract MockChaiIntegratee is MockToken, SwapperBase { address private immutable CENTRALIZED_RATE_PROVIDER; address public immutable DAI; constructor( address _dai, address _centralizedRateProvider, uint8 _decimals ) public MockToken("Chai", "CHAI", _decimals) { _setupDecimals(_decimals); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; DAI = _dai; } function join(address, uint256 _daiAmount) external { uint256 tokenDecimals = ERC20(DAI).decimals(); uint256 chaiDecimals = decimals(); // Calculate the amount of tokens per one unit of DAI uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI); // Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div( daiPerChaiUnit ); // Mint and send those CHAI to sender uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals); _mint(address(this), destAmount); __swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount); } function exit(address payable _trader, uint256 _chaiAmount) external { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _chaiAmount, DAI ); // Burn CHAI of the trader. _burn(_trader, _chaiAmount); // Release DAI to the trader. ERC20(DAI).transfer(msg.sender, destAmount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title AlphaHomoraV1Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/> contract AlphaHomoraV1Adapter is AdapterBase { address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _ibethToken, address _wethToken ) public AdapterBase(_integrationManager) { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during redemption receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "ALPHA_HOMORA_V1"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = wethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = IBETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIbethAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = IBETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = ibethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minWethAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends WETH for ibETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs); IWETH(payable(WETH_TOKEN)).withdraw(wethAmount); IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}(); } /// @notice Redeems ibETH for WETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs); IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAlphaHomoraV1Bank interface /// @author Enzyme Council <[email protected]> interface IAlphaHomoraV1Bank { function deposit() external payable; function totalETH() external view returns (uint256); function totalSupply() external view returns (uint256); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../IDerivativePriceFeed.sol"; /// @title AlphaHomoraV1PriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Alpha Homora v1 ibETH contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed { using SafeMath for uint256; address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor(address _ibethToken, address _wethToken) public { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH_TOKEN; underlyingAmounts_ = new uint256[](1); IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN); underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div( alphaHomoraBankContract.totalSupply() ); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == IBETH_TOKEN; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IMakerDaoPot.sol"; import "../IDerivativePriceFeed.sol"; /// @title ChaiPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Chai contract ChaiPriceFeed is IDerivativePriceFeed { using SafeMath for uint256; uint256 private constant CHI_DIVISOR = 10**27; address private immutable CHAI; address private immutable DAI; address private immutable DSR_POT; constructor( address _chai, address _dai, address _dsrPot ) public { CHAI = _chai; DAI = _dai; DSR_POT = _dsrPot; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount /// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported"); underlyings_ = new address[](1); underlyings_[0] = DAI; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div( CHI_DIVISOR ); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == CHAI; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } /// @notice Gets the `DSR_POT` variable value /// @return dsrPot_ The `DSR_POT` variable value function getDsrPot() external view returns (address dsrPot_) { return DSR_POT; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @notice Limited interface for Maker DSR's Pot contract /// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md interface IMakerDaoPot { function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeBase.sol"; /// @title EntranceRateFeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund abstract contract EntranceRateFeeBase is FeeBase { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate); event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity); uint256 private constant RATE_DIVISOR = 10**18; IFeeManager.SettlementType private immutable SETTLEMENT_TYPE; mapping(address => uint256) private comptrollerProxyToRate; constructor(address _feeManager, IFeeManager.SettlementType _settlementType) public FeeBase(_feeManager) { require( _settlementType == IFeeManager.SettlementType.Burn || _settlementType == IFeeManager.SettlementType.Direct, "constructor: Invalid _settlementType" ); SETTLEMENT_TYPE = _settlementType; } // EXTERNAL FUNCTIONS /// @notice Add the fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 rate = abi.decode(_settingsData, (uint256)); require(rate > 0, "addFundSettings: Fee rate must be >0"); comptrollerProxyToRate[_comptrollerProxy] = rate; emit FundSettingsAdded(_comptrollerProxy, rate); } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](1); implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settles the fee /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settlementData Encoded args to use in calculating the settlement /// @return settlementType_ The type of settlement /// @return payer_ The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address, IFeeManager.FeeHook, bytes calldata _settlementData, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ) { uint256 sharesBought; (payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData); uint256 rate = comptrollerProxyToRate[_comptrollerProxy]; sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate)); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } emit Settled(_comptrollerProxy, payer_, sharesDue_); return (SETTLEMENT_TYPE, payer_, sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `rate` variable for a fund /// @param _comptrollerProxy The ComptrollerProxy contract for the fund /// @return rate_ The `rate` variable value function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) { return comptrollerProxyToRate[_comptrollerProxy]; } /// @notice Gets the `SETTLEMENT_TYPE` variable /// @return settlementType_ The `SETTLEMENT_TYPE` variable value function getSettlementType() external view returns (IFeeManager.SettlementType settlementType_) { return SETTLEMENT_TYPE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateDirectFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that transfers the fee shares to the fund manager contract EntranceRateDirectFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_DIRECT"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateBurnFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that burns the fee shares contract EntranceRateBurnFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_BURN"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract MockChaiPriceSource { using SafeMath for uint256; uint256 private chiStored = 10**27; uint256 private rhoStored = now; function drip() external returns (uint256) { require(now >= rhoStored, "drip: invalid now"); rhoStored = now; chiStored = chiStored.mul(99).div(100); return chi(); } //////////////////// // STATE GETTERS // /////////////////// function chi() public view returns (uint256) { return chiStored; } function rho() public view returns (uint256) { return rhoStored; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/DispatcherOwnerMixin.sol"; import "./IAggregatedDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); event DerivativeUpdated( address indexed derivative, address prevPriceFeed, address nextPriceFeed ); mapping(address => address) private derivativeToPriceFeed; constructor( address _dispatcher, address[] memory _derivatives, address[] memory _priceFeeds ) public DispatcherOwnerMixin(_dispatcher) { if (_derivatives.length > 0) { __addDerivatives(_derivatives, _priceFeeds); } } /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = derivativeToPriceFeed[_derivative]; require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative /// @dev This should be as low-cost and simple as possible function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return derivativeToPriceFeed[_asset] != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty"); __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty"); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty"); require( _derivatives.length == _priceFeeds.length, "updateDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]]; require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added"); require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set"); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]); } } /// @dev Helper to add derivative-feed pairs function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) private { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative"); require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed"); require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) external view override returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } }
Helper to parse settlement arguments from encoded data for PostBuyShares fee hook
function __decodePostBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesBought_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); }
1,697,161
pragma solidity ^0.5.16; import "./KineControllerInterface.sol"; import "./KMCDInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./KTokenInterfaces.sol"; /** Copyright 2020 Compound Labs, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol * Modified to work in the Kine system. * Main modifications: * 1. removed Comp token related logics. * 2. removed interest rate model related logics. * 3. removed mint, redeem logics. users can only supply kTokens (see KToken) and borrow Kine MCD. * 4. removed transfer logics. MCD can't be transferred. * 5. removed error code propagation mechanism, using revert to fail fast and loudly. */ /** * @title Kine's KMCD Contract * @notice Kine Market Connected Debt (MCD) contract. Users are allowed to call KUSDMinter to borrow Kine MCD and mint KUSD * after they supply collaterals in KTokens. One should notice that Kine MCD is not ERC20 token since it can't be transferred by user. * @author Kine */ contract KMCD is KMCDInterface, Exponential, KTokenErrorReporter { modifier onlyAdmin(){ require(msg.sender == admin, "only admin can call this function"); _; } /// @notice Prevent anyone other than minter from borrow/repay Kine MCD modifier onlyMinter { require( msg.sender == minter, "Only minter can call this function." ); _; } /** * @notice Initialize the money market * @param controller_ The address of the Controller * @param name_ Name of this MCD token * @param symbol_ Symbol of this MCD token * @param decimals_ Decimal precision of this token */ function initialize(KineControllerInterface controller_, string memory name_, string memory symbol_, uint8 decimals_, address minter_) public { require(msg.sender == admin, "only admin may initialize the market"); require(initialized == false, "market may only be initialized once"); // Set the controller _setController(controller_); minter = minter_; name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; initialized = true; } /*** User Interface ***/ /** * @notice Only minter can borrow Kine MCD on behalf of user from the protocol * @param borrowAmount Amount of Kine MCD to borrow on behalf of user */ function borrowBehalf(address payable borrower, uint borrowAmount) onlyMinter external { borrowInternal(borrower, borrowAmount); } /** * @notice Only minter can repay Kine MCD on behalf of borrower to the protocol * @param borrower Account with the MCD being payed off * @param repayAmount The amount to repay */ function repayBorrowBehalf(address borrower, uint repayAmount) onlyMinter external { repayBorrowBehalfInternal(borrower, repayAmount); } /** * @notice Only minter can liquidates the borrowers collateral on behalf of user * The collateral seized is transferred to the liquidator * @param borrower The borrower of MCD to be liquidated * @param repayAmount The amount of the MCD to repay * @param kTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrowBehalf(address liquidator, address borrower, uint repayAmount, KTokenInterface kTokenCollateral, uint minSeizeKToken) onlyMinter external { liquidateBorrowInternal(liquidator, borrower, repayAmount, kTokenCollateral, minSeizeKToken); } /** * @notice Get a snapshot of the account's balances * @dev This is used by controller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (token balance, borrow balance) */ function getAccountSnapshot(address account) external view returns (uint, uint) { return (0, accountBorrows[account]); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice get account's borrow balance * @param account The address whose balance should be get * @return The balance */ function borrowBalance(address account) public view returns (uint) { return accountBorrows[account]; } /** * @notice Sender borrows MCD from the protocol to their own address * @param borrowAmount The amount of MCD to borrow */ function borrowInternal(address payable borrower, uint borrowAmount) internal nonReentrant { borrowFresh(borrower, borrowAmount); } struct BorrowLocalVars { uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Sender borrow MCD from the protocol to their own address * @param borrowAmount The amount of the MCD to borrow */ function borrowFresh(address payable borrower, uint borrowAmount) internal { /* Fail if borrow not allowed */ (bool allowed, string memory reason) = controller.borrowAllowed(address(this), borrower, borrowAmount); require(allowed, reason); BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = accountBorrows[borrower]; vars.accountBorrowsNew = vars.accountBorrows.add(borrowAmount, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED); vars.totalBorrowsNew = totalBorrows.add(borrowAmount, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); /* We write the previously calculated values into storage */ accountBorrows[borrower] = vars.accountBorrowsNew; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ controller.borrowVerify(address(this), borrower, borrowAmount); } /** * @notice Sender repays MCD belonging to borrower * @param borrower the account with the MCD being payed off * @param repayAmount The amount to repay * @return the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint) { return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Borrows are repaid by another user, should be the minter. * @param payer the account paying off the MCD * @param borrower the account with the MCD being payed off * @param repayAmount the amount of MCD being returned * @return the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) { /* Fail if repayBorrow not allowed */ (bool allowed, string memory reason) = controller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); require(allowed, reason); RepayBorrowLocalVars memory vars; /* We fetch the amount the borrower owes */ vars.accountBorrows = accountBorrows[borrower]; /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = vars.accountBorrows.sub(repayAmount, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED); vars.totalBorrowsNew = totalBorrows.sub(repayAmount, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); /* We write the previously calculated values into storage */ accountBorrows[borrower] = vars.accountBorrowsNew; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, repayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ controller.repayBorrowVerify(address(this), payer, borrower, repayAmount); return repayAmount; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this MCD to be liquidated * @param kTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the MCD asset to repay * @return the actual repayment amount. */ function liquidateBorrowInternal(address liquidator, address borrower, uint repayAmount, KTokenInterface kTokenCollateral, uint minSeizeKToken) internal nonReentrant returns (uint) { return liquidateBorrowFresh(liquidator, borrower, repayAmount, kTokenCollateral, minSeizeKToken); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this MCD to be liquidated * @param liquidator The address repaying the MCD and seizing collateral * @param kTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the borrowed MCD to repay * @return the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, KTokenInterface kTokenCollateral, uint minSeizeKToken) internal returns (uint) { /* Revert if trying to seize MCD */ require(address(kTokenCollateral) != address(this), "Kine MCD can't be seized"); /* Fail if liquidate not allowed */ (bool allowed, string memory reason) = controller.liquidateBorrowAllowed(address(this), address(kTokenCollateral), liquidator, borrower, repayAmount); require(allowed, reason); /* Fail if borrower = liquidator */ require(borrower != liquidator, INVALID_ACCOUNT_PAIR); /* Fail if repayAmount = 0 */ require(repayAmount != 0, INVALID_CLOSE_AMOUNT_REQUESTED); /* Fail if repayAmount = -1 */ require(repayAmount != uint(- 1), INVALID_CLOSE_AMOUNT_REQUESTED); ///////////////////////// // EFFECTS & INTERACTIONS /* We calculate the number of collateral tokens that will be seized */ uint seizeTokens = controller.liquidateCalculateSeizeTokens(borrower, address(this), address(kTokenCollateral), repayAmount); require(seizeTokens >= minSeizeKToken, "Reach minSeizeKToken limit"); /* Revert if borrower collateral token balance < seizeTokens */ require(kTokenCollateral.balanceOf(borrower) >= seizeTokens, LIQUIDATE_SEIZE_TOO_MUCH); /* Fail if repayBorrow fails */ repayBorrowFresh(liquidator, borrower, repayAmount); /* Seize borrower tokens to liquidator */ kTokenCollateral.seize(liquidator, borrower, seizeTokens); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, repayAmount, address(kTokenCollateral), seizeTokens); /* We call the defense hook */ controller.liquidateBorrowVerify(address(this), address(kTokenCollateral), liquidator, borrower, repayAmount, seizeTokens); return repayAmount; } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function _setPendingAdmin(address payable newPendingAdmin) external onlyAdmin() { // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() external { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized"); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } /** * @notice Sets a new controller for the market * @dev Admin function to set a new controller */ function _setController(KineControllerInterface newController) public onlyAdmin() { KineControllerInterface oldController = controller; // Ensure invoke controller.isController() returns true require(newController.isController(), "marker method returned false"); // Set market's controller to newController controller = newController; // Emit NewController(oldController, newController) emit NewController(oldController, newController); } function _setMinter(address newMinter) public onlyAdmin() { address oldMinter = minter; minter = newMinter; emit NewMinter(oldMinter, newMinter); } /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } }
Only minter can liquidates the borrowers collateral on behalf of user The collateral seized is transferred to the liquidator borrower The borrower of MCD to be liquidated repayAmount The amount of the MCD to repay kTokenCollateral The market in which to seize collateral from the borrower/
function liquidateBorrowBehalf(address liquidator, address borrower, uint repayAmount, KTokenInterface kTokenCollateral, uint minSeizeKToken) onlyMinter external { liquidateBorrowInternal(liquidator, borrower, repayAmount, kTokenCollateral, minSeizeKToken); }
1,079,278
pragma solidity ^0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { address sender = msg.sender; address _owner = owner; require(msg.sender == _owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } 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) { 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 ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant 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)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.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. * * 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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title BrickToken * @dev Brick ERC20 Token that can be minted. * It is meant to be used in Brick crowdsale contract. */ contract BrickToken is MintableToken { string public constant name = "The Brick"; string public constant symbol = "BRK"; uint8 public constant decimals = 18; function getTotalSupply() view public returns (uint256) { return totalSupply; } function transfer(address _to, uint256 _value) public returns (bool) { super.transfer(_to, _value); } } /** * @title Brick Crowdsale * @dev This is Brick's crowdsale contract. */ contract BrickCrowdsale is Ownable { using SafeMath for uint256; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // amount of raised money in wei uint256 public weiRaised; uint256 public limitDateSale; // end date in units uint256 public currentTime; bool public isSoftCapHit = false; bool public isStarted = false; bool public isFinalized = false; // Token rates as per rounds uint256 icoPvtRate = 40; uint256 icoPreRate = 50; uint256 ico1Rate = 65; uint256 ico2Rate = 75; uint256 ico3Rate = 90; // Tokens in each round uint256 public pvtTokens = (40000) * (10**18); uint256 public preSaleTokens = (6000000) * (10**18); uint256 public ico1Tokens = (8000000) * (10**18); uint256 public ico2Tokens = (8000000) * (10**18); uint256 public ico3Tokens = (8000000) * (10**18); uint256 public totalTokens = (40000000)* (10**18); // 40 million // address where funds are collected address public advisoryEthWallet = 0x0D7629d32546CD493bc33ADEF115D4489f5599Be; address public infraEthWallet = 0x536D36a05F6592aa29BB0beE30cda706B1272521; address public techDevelopmentEthWallet = 0x4d0B70d8E612b5dca3597C64643a8d1efd5965e1; address public operationsEthWallet = 0xbc67B82924eEc8643A4f2ceDa59B5acfd888A967; // address where token will go address public wallet = 0x44d44CA0f75bdd3AE8806D02515E8268459c554A; // wallet where remaining tokens will go struct ContributorData { uint256 contributionAmount; uint256 tokensIssued; } mapping(address => ContributorData) public contributorList; mapping(uint => address) contributorIndexes; uint nextContributorIndex; constructor() public {} function init( uint256 _tokensForCrowdsale, uint256 _etherInUSD, address _tokenAddress, uint256 _softCapInEthers, uint256 _hardCapInEthers, uint _saleDurationInDays, uint bonus) onlyOwner public { // setTotalTokens(_totalTokens); currentTime = now; setTokensForCrowdSale(_tokensForCrowdsale); setRate(_etherInUSD); setTokenAddress(_tokenAddress); setSoftCap(_softCapInEthers); setHardCap(_hardCapInEthers); setSaleDuration(_saleDurationInDays); setSaleBonus(bonus); start(); // starting the crowdsale } /** * @dev Must be called to start the crowdsale */ function start() onlyOwner public { require(!isStarted); require(!hasStarted()); require(tokenAddress != address(0)); require(saleDuration != 0); require(totalTokens != 0); require(tokensForCrowdSale != 0); require(softCap != 0); require(hardCap != 0); starting(); emit BrickStarted(); isStarted = true; // endPvtSale(); } function splitTokens() internal { token.mint(techDevelopmentEthWallet, totalTokens.mul(3).div(100)); //wallet for tech development tokensIssuedTillNow = tokensIssuedTillNow + totalTokens.mul(3).div(100); token.mint(operationsEthWallet, totalTokens.mul(7).div(100)); //wallet for operations wallet tokensIssuedTillNow = tokensIssuedTillNow + totalTokens.mul(7).div(100); } uint256 public tokensForCrowdSale = 0; function setTokensForCrowdSale(uint256 _tokensForCrowdsale) onlyOwner public { tokensForCrowdSale = _tokensForCrowdsale.mul(10 ** 18); } uint256 public rate=0; uint256 public etherInUSD; function setRate(uint256 _etherInUSD) internal { etherInUSD = _etherInUSD; rate = getCurrentRateInCents().mul(10**18).div(100).div(_etherInUSD); } function setRate(uint256 rateInCents, uint256 _etherInUSD) public onlyOwner { etherInUSD = _etherInUSD; rate = rateInCents.mul(10**18).div(100).div(_etherInUSD); } function updateRateInWei() internal { // this method requires that you must have called etherInUSD earliar, must not be called except when round is ending. require(etherInUSD != 0); rate = getCurrentRateInCents().mul(10**18).div(100).div(etherInUSD); } function getCurrentRateInCents() public view returns (uint256) { if(currentRound == 1) { return icoPvtRate; } else if(currentRound == 2) { return icoPreRate; } else if(currentRound == 3) { return ico1Rate; } else if(currentRound == 4) { return ico2Rate; } else if(currentRound == 5) { return ico3Rate; } else { return ico3Rate; } } // The token being sold BrickToken public token; address tokenAddress = 0x0; function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; // to check if token address is provided at start token = BrickToken(_tokenAddress); } function setPvtTokens (uint256 _pvtTokens)onlyOwner public { require(!icoPvtEnded); pvtTokens = (_pvtTokens).mul(10 ** 18); } function setPreSaleTokens (uint256 _preSaleTokens)onlyOwner public { require(!icoPreEnded); preSaleTokens = (_preSaleTokens).mul(10 ** 18); } function setIco1Tokens (uint256 _ico1Tokens)onlyOwner public { require(!ico1Ended); ico1Tokens = (_ico1Tokens).mul(10 ** 18); } function setIco2Tokens (uint256 _ico2Tokens)onlyOwner public { require(!ico2Ended); ico2Tokens = (_ico2Tokens).mul(10 ** 18); } function setIco3Tokens (uint256 _ico3Tokens)onlyOwner public { require(!ico3Ended); ico3Tokens = (_ico3Tokens).mul(10 ** 18); } uint256 public softCap = 0; function setSoftCap(uint256 _softCap) onlyOwner public { softCap = _softCap.mul(10 ** 18); } uint256 public hardCap = 0; function setHardCap(uint256 _hardCap) onlyOwner public { hardCap = _hardCap.mul(10 ** 18); } // sale period (includes holidays) uint public saleDuration = 0; // in days ex: 60. function setSaleDuration(uint _saleDurationInDays) onlyOwner public { saleDuration = _saleDurationInDays; limitDateSale = startTime.add(saleDuration * 1 days); endTime = limitDateSale; } uint public saleBonus = 0; // ex. 10 function setSaleBonus(uint bonus) public onlyOwner{ saleBonus = bonus; } // fallback function can be used to buy tokens function () public payable { buyPhaseTokens(msg.sender); } function transferTokenOwnership(address _address) onlyOwner public { token.transferOwnership(_address); } function releaseTokens(address _contributerAddress, uint256 tokensOfContributor) internal { token.mint(_contributerAddress, tokensOfContributor); } function currentTokenSupply() public view returns(uint256){ return token.getTotalSupply(); } function buyPhaseTokens(address beneficiary) public payable { assert(!ico3Ended); require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = computeTokens(weiAmount); //converts the wei to token amount require(isWithinTokenAllocLimit(tokens)); if(int(pvtTokens - tokensIssuedTillNow) > 0) { //phase1 80 require(int (tokens) < (int(pvtTokens - tokensIssuedTillNow))); buyTokens(tokens,weiAmount,beneficiary); } else if (int (preSaleTokens + pvtTokens - tokensIssuedTillNow) > 0) { //phase 2 80 require(int(tokens) < (int(preSaleTokens + pvtTokens - tokensIssuedTillNow))); buyTokens(tokens,weiAmount,beneficiary); } else if(int(ico1Tokens + preSaleTokens + pvtTokens - tokensIssuedTillNow) > 0) { //phase3 require(int(tokens) < (int(ico1Tokens + preSaleTokens + pvtTokens -tokensIssuedTillNow))); buyTokens(tokens,weiAmount,beneficiary); } else if(int(ico2Tokens + ico1Tokens + preSaleTokens + pvtTokens - (tokensIssuedTillNow)) > 0) { //phase4 require(int(tokens) < (int(ico2Tokens + ico1Tokens + preSaleTokens + pvtTokens - (tokensIssuedTillNow)))); buyTokens(tokens,weiAmount,beneficiary); } else if(!ico3Ended && (int(tokensForCrowdSale - (tokensIssuedTillNow)) > 0)) { // 500 -400 require(int(tokens) < (int(tokensForCrowdSale - (tokensIssuedTillNow)))); buyTokens(tokens,weiAmount,beneficiary); } } uint256 public tokensIssuedTillNow=0; function buyTokens(uint256 tokens, uint256 weiAmount ,address beneficiary) internal { // update state - Add to eth raised weiRaised = weiRaised.add(weiAmount); if (contributorList[beneficiary].contributionAmount == 0) { // if its a new contributor, add him and increase index contributorIndexes[nextContributorIndex] = beneficiary; nextContributorIndex += 1; } contributorList[beneficiary].contributionAmount += weiAmount; contributorList[beneficiary].tokensIssued += tokens; tokensIssuedTillNow = tokensIssuedTillNow + tokens; releaseTokens(beneficiary, tokens); // releaseTokens forwardFunds(); // forwardFunds emit BrickTokenPurchase(msg.sender, beneficiary, weiAmount, tokens); } /** * 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 BrickTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function investorCount() constant public returns(uint) { return nextContributorIndex; } function hasStarted() public constant returns (bool) { return (startTime != 0 && now > startTime); } function isWithinSaleTimeLimit() internal view returns (bool) { return now <= limitDateSale; } function isWithinSaleLimit(uint256 _tokens) internal view returns (bool) { return token.getTotalSupply().add(_tokens) <= tokensForCrowdSale; } function computeTokens(uint256 weiAmount) view internal returns (uint256) { return weiAmount.mul(10 ** 18).div(rate); } function isWithinTokenAllocLimit(uint256 _tokens) view internal returns (bool) { return (isWithinSaleTimeLimit() && isWithinSaleLimit(_tokens)); } // overriding BrckBaseCrowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal constant returns (bool) { bool withinCap = weiRaised.add(msg.value) <= hardCap; bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return (withinPeriod && nonZeroPurchase) && withinCap && isWithinSaleTimeLimit(); } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= hardCap; return (endTime != 0 && now > endTime) || capReached; } event BrickStarted(); event BrickFinalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); // require(hasEnded()); finalization(); emit BrickFinalized(); isFinalized = true; } function starting() internal { startTime = now; limitDateSale = startTime.add(saleDuration * 1 days); endTime = limitDateSale; } function finalization() internal { splitTokens(); token.mint(wallet, totalTokens.sub(tokensIssuedTillNow)); if(address(this).balance > 0){ // if any funds are left in contract. processFundsIfAny(); } } // send ether to the fund collection wallet function forwardFunds() internal { require(advisoryEthWallet != address(0)); require(infraEthWallet != address(0)); require(techDevelopmentEthWallet != address(0)); require(operationsEthWallet != address(0)); operationsEthWallet.transfer(msg.value.mul(60).div(100)); advisoryEthWallet.transfer(msg.value.mul(5).div(100)); infraEthWallet.transfer(msg.value.mul(10).div(100)); techDevelopmentEthWallet.transfer(msg.value.mul(25).div(100)); } // send ether to the fund collection wallet function processFundsIfAny() internal { require(advisoryEthWallet != address(0)); require(infraEthWallet != address(0)); require(techDevelopmentEthWallet != address(0)); require(operationsEthWallet != address(0)); operationsEthWallet.transfer(address(this).balance.mul(60).div(100)); advisoryEthWallet.transfer(address(this).balance.mul(5).div(100)); infraEthWallet.transfer(address(this).balance.mul(10).div(100)); techDevelopmentEthWallet.transfer(address(this).balance.mul(25).div(100)); } //functions to manually end round sales uint256 public currentRound = 1; bool public icoPvtEnded = false; bool public icoPreEnded = false; bool public ico1Ended = false; bool public ico2Ended = false; bool public ico3Ended = false; function endPvtSale() onlyOwner public //ending private sale { require(!icoPvtEnded); pvtTokens = tokensIssuedTillNow; currentRound = 2; updateRateInWei(); icoPvtEnded = true; } function endPreSale() onlyOwner public //ending pre-sale { require(!icoPreEnded && icoPvtEnded); preSaleTokens = tokensIssuedTillNow - pvtTokens; currentRound = 3; updateRateInWei(); icoPreEnded = true; } function endIcoSaleRound1() onlyOwner public //ending IcoSaleRound1 { require(!ico1Ended && icoPreEnded); ico1Tokens = tokensIssuedTillNow - preSaleTokens - pvtTokens; currentRound = 4; updateRateInWei(); ico1Ended = true; } function endIcoSaleRound2() onlyOwner public //ending IcoSaleRound2 { require(!ico2Ended && ico1Ended); ico2Tokens = tokensIssuedTillNow - ico1Tokens - preSaleTokens - pvtTokens; currentRound = 5; updateRateInWei(); ico2Ended=true; } function endIcoSaleRound3() onlyOwner public //ending IcoSaleRound3 { require(!ico3Ended && ico2Ended); ico3Tokens = tokensIssuedTillNow - ico2Tokens - ico1Tokens - preSaleTokens - pvtTokens; updateRateInWei(); ico3Ended = true; } modifier afterDeadline() { if (hasEnded() || isFinalized) _; } // a modifier to tell token sale ended function selfDestroy(address _address) public onlyOwner { // this method will send all money to the following address after finalize assert(isFinalized); selfdestruct(_address); } }
this method will send all money to the following address after finalize
function selfDestroy(address _address) public onlyOwner {
62,917
// Copyright (c) 2017 Aler Denisov // 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.18; import "./ICounter.sol"; import "../../base/UIntStorage.sol"; /// @title Incremental implementation of counter for explanation external storage pattern /// @author Aler Denisov contract IncrementCounter is ICounter, Ownable { /// @notice Method modifier to ensure providen storage is UIntStorage /// @param _storage Instance of uint storage of counter /// @dev Throw error if storage isn't valid modifier validStorage(address _storage) { require(validateStorage(_storage)); _; } /// @notice Increment counter on one tick each time when endpoint call incrementCounter via interface /// @param _storage Instance of uint storage of counter /// @dev Implementation of Counter interface /// @return Current value of counter (after increment) function increaseCounter(address _storage) onlyOwner validStorage(_storage) public returns (uint) { UIntStorage counter = UIntStorage(_storage); return counter.setValue(counter.getValue() + 1); } /// @notice Import stored value from external storage /// @param _storage Instance of uint storage of counter /// @return Current value of counter function getCounter(address _storage) validStorage(_storage) public view returns (uint) { UIntStorage counter = UIntStorage(_storage); return counter.getValue(); } /// @notice Method to validate received storage /// @param _storage Instance of uint storage of counter /// @return True if storage is valid, false\revert overwise function validateStorage(address _storage) public view returns (bool) { return UIntStorage(_storage).isUIntStorage(); } /// @notice Method to transfer ownership of storage to another counter /// @param _storage Instance of uint storage of counter /// @param _counter Instance of ICounter implementation to transfer ownership /// @return True if ownership is transfered, false\revert overwise function transferStorage(address _storage, address _counter) onlyOwner validStorage(_storage) public returns (bool) { UIntStorage(_storage).transferOwnership(_counter); return true; } }
Import stored value from external storage _storage Instance of uint storage of counter return Current value of counter
function getCounter(address _storage) validStorage(_storage) public view returns (uint) { UIntStorage counter = UIntStorage(_storage); return counter.getValue(); }
13,130,539
// SPDX-License-Identifier: MIT // SYS 64738 // Version 2.0 // Author: 0xTycoon // Contributor: Alphasoup <twitter: alphasoups> // Special Thanks: straybits1, cryptopunkart, cyounessi1, ethereumdegen, Punk7572, sherone.eth, // songadaymann, Redlioneye.eth, tw1tte7, PabloPunkasso, Kaprekar_Punk, aradtski, // phantom_scribbs, Cryptopapa.eth, johnhenderson, thekriskay, PerfectoidPeter, // uxt_exe, 0xUnicorn, dansickles.eth, Blon Dee#9649, VRPunk1, Don Seven Slices, hogo.eth, // GeoCities#5700, "HP OfficeJet Pro 9015e #2676", gigiuz#0061, danpolko.eth, mariano.eth, // 0xfoobar, jakerockland, Mudit__Gupta, BokkyPooBah, 0xaaby.eth, and // everyone at the discord, and all the awesome people who gave feedback for this project! // Greetings to: Punk3395, foxthepunk, bushleaf.eth, 570KylΞ.eth, bushleaf.eth, Tokyolife, Joshuad.eth (1641), // markchesler_coinwitch, decideus.eth, zachologylol, punk8886, jony_bee, nfttank, DolAtoR, punk8886 // DonJon.eth, kilifibaobab, joked507, cryptoed#3040, DroScott#7162, 0xAllen.eth, Tschuuuly#5158, // MetasNomadic#0349, punk8653, NittyB, heygareth.eth, Aaru.eth, robertclarke.eth, Acmonides#6299, // Gustavus99 (1871), Foobazzler // Repo: github.com/0xTycoon/punksceo pragma solidity ^0.8.11; //import "./safemath.sol"; // don't need since v0.8 //import "./ceo.sol"; //import "hardhat/console.sol"; /* PUNKS CEO (and "Cigarette" token) WEB: https://punksceo.eth.limo / https://punksceo.eth.link IPFS: See content hash record for punksceo.eth Token Address: cigtoken.eth , - ~ ~ ~ - , , ' ' , , 🚬 , , 🚬 , , 🚬 , , 🚬 , , ============= , , ||█ , , ============= , , , ' ' - , _ _ _ , ' ### THE RULES OF THE GAME 1. Anybody can buy the CEO title at any time using Cigarettes. (The CEO of all cryptopunks) 2. When buying the CEO title, you must nominate a punk, set the price and pre-pay the tax. 3. The CEO title can be bought from the existing CEO at any time. 4. To remain a CEO, a daily tax needs to be paid. 5. The tax is 0.1% of the price to buy the CEO title, to be charged per epoch. 6. The CEO can be removed if they fail to pay the tax. A reward of CIGs is paid to the whistleblower. 7. After Removing a CEO: A dutch auction is held, where the price will decrease 10% every half-an-epoch. 8. The price can be changed by the CEO at any time. (Once per block) 9. An epoch is 7200 blocks. 10. All the Cigarettes from the sale are burned. 11. All tax is burned 12. After buying the CEO title, the old CEO will get their unspent tax deposit refunded ### CEO perk 13. The CEO can increase or decrease the CIG farming block reward by 20% every 2nd epoch! However, note that the issuance can never be more than 1000 CIG per block, also never under 0.0001 CIG. 14. THE CEO gets to hold a NFT in their wallet. There will only be ever 1 this NFT. The purpose of this NFT is so that everyone can see that they are the CEO. IMPORTANT: This NFT will be revoked once the CEO title changes. Also, the NFT cannot be transferred by the owner, the only way to transfer is for someone else to buy the CEO title! (Think of this NFT as similar to a "title belt" in boxing.) END * states * 0 = initial * 1 = CEO reigning * 2 = Dutch auction * 3 = Migration Notes: It was decided that whoever buys the CEO title does not have to hold a punk and can nominate any punk they wish. This is because some may hold their punks in cold storage, plus checking ownership costs additional gas. Besides, CEOs are usually appointed by the board. Credits: - LP Staking based on code from SushiSwap's MasterChef.sol - ERC20 & SafeMath based on lib from OpenZeppelin */ contract Cig { //using SafeMath for uint256; // no need since Solidity 0.8 string public constant name = "Cigarette Token"; string public constant symbol = "CIG"; uint8 public constant decimals = 18; uint256 public totalSupply = 0; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // UserInfo keeps track of user LP deposits and withdrawals struct UserInfo { uint256 deposit; // How many LP tokens the user has deposited. uint256 rewardDebt; // keeps track of how much reward was paid out } mapping(address => UserInfo) public farmers; // keeps track of UserInfo for each staking address with own pool mapping(address => UserInfo) public farmersMasterchef; // keeps track of UserInfo for each staking address with masterchef pool mapping(address => uint256) public wBal; // keeps tracked of wrapped old cig address public admin; // admin is used for deployment, burned after ILiquidityPoolERC20 public lpToken; // lpToken is the address of LP token contract that's being staked. uint256 public lastRewardBlock; // Last block number that cigarettes distribution occurs. uint256 public accCigPerShare; // Accumulated cigarettes per share, times 1e12. See below. uint256 public masterchefDeposits; // How much has been deposited onto the masterchef contract uint256 public cigPerBlock; // CIGs per-block rewarded and split with LPs bytes32 public graffiti; // a 32 character graffiti set when buying a CEO ICryptoPunk public punks; // a reference to the CryptoPunks contract event Deposit(address indexed user, uint256 amount); // when depositing LP tokens to stake event Harvest(address indexed user, address to, uint256 amount);// when withdrawing LP tokens form staking event Withdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed event EmergencyWithdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed event ChefDeposit(address indexed user, uint256 amount); // when depositing LP tokens to stake event ChefWithdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed event RewardUp(uint256 reward, uint256 upAmount); // when cigPerBlock is increased event RewardDown(uint256 reward, uint256 downAmount); // when cigPerBlock is decreased event Claim(address indexed owner, uint indexed punkIndex, uint256 value); // when a punk is claimed mapping(uint => bool) public claims; // keep track of claimed punks modifier onlyAdmin { require( msg.sender == admin, "Only admin can call this" ); _; } uint256 constant MIN_PRICE = 1e12; // 0.000001 CIG uint256 constant CLAIM_AMOUNT = 100000 ether; // claim amount for each punk uint256 constant MIN_REWARD = 1e14; // minimum block reward of 0.0001 CIG (1e14 wei) uint256 constant MAX_REWARD = 1000 ether; // maximum block reward of 1000 CIG uint256 constant STARTING_REWARDS = 512 ether;// starting rewards at end of migration address public The_CEO; // address of CEO uint public CEO_punk_index; // which punk id the CEO is using uint256 public CEO_price = 50000 ether; // price to buy the CEO title uint256 public CEO_state; // state has 3 states, described above. uint256 public CEO_tax_balance; // deposit to be used to pay the CEO tax uint256 public taxBurnBlock; // The last block when the tax was burned uint256 public rewardsChangedBlock; // which block was the last reward increase / decrease uint256 private immutable CEO_epoch_blocks; // secs per day divided by 12 (86400 / 12), assuming 12 sec blocks uint256 private immutable CEO_auction_blocks; // 3600 blocks // NewCEO 0x09b306c6ea47db16bdf4cc36f3ea2479af494cd04b4361b6485d70f088658b7e event NewCEO(address indexed user, uint indexed punk_id, uint256 new_price, bytes32 graffiti); // when a CEO is bought // TaxDeposit 0x2ab3b3b53aa29a0599c58f343221e29a032103d015c988fae9a5cdfa5c005d9d event TaxDeposit(address indexed user, uint256 amount); // when tax is deposited // RevenueBurned 0x1b1be00a9ca19f9c14f1ca5d16e4aba7d4dd173c2263d4d8a03484e1c652c898 event RevenueBurned(address indexed user, uint256 amount); // when tax is burned // TaxBurned 0x9ad3c710e1cc4e96240264e5d3cd5aeaa93fd8bd6ee4b11bc9be7a5036a80585 event TaxBurned(address indexed user, uint256 amount); // when tax is burned // CEODefaulted b69f2aeff650d440d3e7385aedf764195cfca9509e33b69e69f8c77cab1e1af1 event CEODefaulted(address indexed called_by, uint256 reward); // when CEO defaulted on tax // CEOPriceChange 0x10c342a321267613a25f77d4273d7f2688bef174a7214bc3dde44b31c5064ff6 event CEOPriceChange(uint256 price); // when CEO changed price modifier onlyCEO { require( msg.sender == The_CEO, "only CEO can call this" ); _; } IRouterV2 private immutable V2ROUTER; // address of router used to get the price quote ICEOERC721 private immutable The_NFT; // reference to the CEO NFT token address private immutable MASTERCHEF_V2; // address pointing to SushiSwap's MasterChefv2 contract IOldCigtoken private immutable OC; // Old Contract /** * @dev constructor * @param _cigPerBlock Number of CIG tokens rewarded per block * @param _punks address of the cryptopunks contract * @param _CEO_epoch_blocks how many blocks between each epochs * @param _CEO_auction_blocks how many blocks between each auction discount * @param _CEO_price starting price to become CEO (in CIG) * @param _graffiti bytes32 initial graffiti message * @param _NFT address pointing to the NFT contract * @param _V2ROUTER address pointing to the SushiSwap router * @param _OC address pointing to the original Cig Token contract * @param _MASTERCHEF_V2 address for the sushi masterchef v2 contract */ constructor( uint256 _cigPerBlock, address _punks, uint _CEO_epoch_blocks, uint _CEO_auction_blocks, uint256 _CEO_price, bytes32 _graffiti, address _NFT, address _V2ROUTER, address _OC, uint256 _migration_epochs, address _MASTERCHEF_V2 ) { cigPerBlock = _cigPerBlock; admin = msg.sender; // the admin key will be burned after deployment punks = ICryptoPunk(_punks); CEO_epoch_blocks = _CEO_epoch_blocks; CEO_auction_blocks = _CEO_auction_blocks; CEO_price = _CEO_price; graffiti = _graffiti; The_NFT = ICEOERC721(_NFT); V2ROUTER = IRouterV2(_V2ROUTER); OC = IOldCigtoken(_OC); lastRewardBlock = block.number + (CEO_epoch_blocks * _migration_epochs); // set the migration window end MASTERCHEF_V2 = _MASTERCHEF_V2; CEO_state = 3; // begin in migration state } /** * @dev buyCEO allows anybody to be the CEO * @param _max_spend the total CIG that can be spent * @param _new_price the new price for the punk (in CIG) * @param _tax_amount how much to pay in advance (in CIG) * @param _punk_index the id of the punk 0-9999 * @param _graffiti a little message / ad from the buyer */ function buyCEO( uint256 _max_spend, uint256 _new_price, uint256 _tax_amount, uint256 _punk_index, bytes32 _graffiti ) external { require (CEO_state != 3); // disabled in in migration state if (CEO_state == 1 && (taxBurnBlock != block.number)) { _burnTax(); // _burnTax can change CEO_state to 2 } if (CEO_state == 2) { // Auction state. The price goes down 10% every `CEO_auction_blocks` blocks CEO_price = _calcDiscount(); } require (CEO_price + _tax_amount <= _max_spend, "overpaid"); // prevent CEO over-payment require (_new_price >= MIN_PRICE, "price 2 smol"); // price cannot be under 0.000001 CIG require (_punk_index <= 9999, "invalid punk"); // validate the punk index require (_tax_amount >= _new_price / 1000, "insufficient tax" ); // at least %0.1 fee paid for 1 epoch transfer(address(this), CEO_price); // pay for the CEO title _burn(address(this), CEO_price); // burn the revenue emit RevenueBurned(msg.sender, CEO_price); _returnDeposit(The_CEO, CEO_tax_balance); // return deposited tax back to old CEO transfer(address(this), _tax_amount); // deposit tax (reverts if not enough) CEO_tax_balance = _tax_amount; // store the tax deposit amount _transferNFT(The_CEO, msg.sender); // yank the NFT to the new CEO CEO_price = _new_price; // set the new price CEO_punk_index = _punk_index; // store the punk id The_CEO = msg.sender; // store the CEO's address taxBurnBlock = block.number; // store the block number // (tax may not have been burned if the // previous state was 0) CEO_state = 1; graffiti = _graffiti; emit TaxDeposit(msg.sender, _tax_amount); emit NewCEO(msg.sender, _punk_index, _new_price, _graffiti); } /** * @dev _returnDeposit returns the tax deposit back to the CEO * @param _to address The address which you want to transfer to * remember to update CEO_tax_balance after calling this */ function _returnDeposit( address _to, uint256 _amount ) internal { if (_amount == 0) { return; } balanceOf[address(this)] = balanceOf[address(this)] - _amount; balanceOf[_to] = balanceOf[_to] + _amount; emit Transfer(address(this), _to, _amount); //CEO_tax_balance = 0; // can be omitted since value gets overwritten by caller } /** * @dev transfer the NFT to a new wallet */ function _transferNFT(address _oldCEO, address _newCEO) internal { The_NFT.transferFrom(_oldCEO, _newCEO, 0); } /** * @dev depositTax pre-pays tax for the existing CEO. * It may also burn any tax debt the CEO may have. * @param _amount amount of tax to pre-pay */ function depositTax(uint256 _amount) external onlyCEO { require (CEO_state == 1, "no CEO"); if (_amount > 0) { transfer(address(this), _amount); // place the tax on deposit CEO_tax_balance = CEO_tax_balance + _amount; // record the balance emit TaxDeposit(msg.sender, _amount); } if (taxBurnBlock != block.number) { _burnTax(); // settle any tax debt taxBurnBlock = block.number; } } /** * @dev burnTax is called to burn tax. * It removes the CEO if tax is unpaid. * 1. deduct tax, update last update * 2. if not enough tax, remove & begin auction * 3. reward the caller by minting a reward from the amount indebted * A Dutch auction begins where the price decreases 10% every hour. */ function burnTax() external { if (taxBurnBlock == block.number) return; if (CEO_state == 1) { _burnTax(); taxBurnBlock = block.number; } } /** * @dev _burnTax burns any tax debt. Boots the CEO if defaulted, paying a reward to the caller */ function _burnTax() internal { // calculate tax per block (tpb) uint256 tpb = CEO_price / 1000 / CEO_epoch_blocks; // 0.1% per epoch uint256 debt = (block.number - taxBurnBlock) * tpb; if (CEO_tax_balance !=0 && CEO_tax_balance >= debt) { // Does CEO have enough deposit to pay debt? CEO_tax_balance = CEO_tax_balance - debt; // deduct tax _burn(address(this), debt); // burn the tax emit TaxBurned(msg.sender, debt); } else { // CEO defaulted uint256 default_amount = debt - CEO_tax_balance; // calculate how much defaulted _burn(address(this), CEO_tax_balance); // burn the tax emit TaxBurned(msg.sender, CEO_tax_balance); CEO_state = 2; // initiate a Dutch auction. CEO_tax_balance = 0; _transferNFT(The_CEO, address(this)); // This contract holds the NFT temporarily The_CEO = address(this); // This contract is the "interim CEO" _mint(msg.sender, default_amount); // reward the caller for reporting tax default emit CEODefaulted(msg.sender, default_amount); } } /** * @dev setPrice changes the price for the CEO title. * @param _price the price to be paid. The new price most be larger tan MIN_PRICE and not default on debt */ function setPrice(uint256 _price) external onlyCEO { require(CEO_state == 1, "No CEO in charge"); require (_price >= MIN_PRICE, "price 2 smol"); require (CEO_tax_balance >= _price / 1000, "price would default"); // need at least 0.1% for tax if (block.number != taxBurnBlock) { _burnTax(); taxBurnBlock = block.number; } // The state is 1 if the CEO hasn't defaulted on tax if (CEO_state == 1) { CEO_price = _price; // set the new price emit CEOPriceChange(_price); } } /** * @dev rewardUp allows the CEO to increase the block rewards by %20 * Can only be called by the CEO every 2 epochs * @return _amount increased by */ function rewardUp() external onlyCEO returns (uint256) { require(CEO_state == 1, "No CEO in charge"); require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks"); require (cigPerBlock < MAX_REWARD, "reward already max"); rewardsChangedBlock = block.number; uint256 _amount = cigPerBlock / 5; // %20 uint256 _new_reward = cigPerBlock + _amount; if (_new_reward > MAX_REWARD) { _amount = MAX_REWARD - cigPerBlock; _new_reward = MAX_REWARD; // cap } cigPerBlock = _new_reward; emit RewardUp(_new_reward, _amount); return _amount; } /** * @dev rewardDown decreases the block rewards by 20% * Can only be called by the CEO every 2 epochs */ function rewardDown() external onlyCEO returns (uint256) { require(CEO_state == 1, "No CEO in charge"); require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks"); require(cigPerBlock > MIN_REWARD, "reward already low"); rewardsChangedBlock = block.number; uint256 _amount = cigPerBlock / 5; // %20 uint256 _new_reward = cigPerBlock - _amount; if (_new_reward < MIN_REWARD) { _amount = cigPerBlock - MIN_REWARD; _new_reward = MIN_REWARD; // limit } cigPerBlock = _new_reward; emit RewardDown(_new_reward, _amount); return _amount; } /** * @dev _calcDiscount calculates the discount for the CEO title based on how many blocks passed */ function _calcDiscount() internal view returns (uint256) { unchecked { uint256 d = (CEO_price / 10) // 10% discount // multiply by the number of discounts accrued * ((block.number - taxBurnBlock) / CEO_auction_blocks); if (d > CEO_price) { // overflow assumed, reset to MIN_PRICE return MIN_PRICE; } uint256 price = CEO_price - d; if (price < MIN_PRICE) { price = MIN_PRICE; } return price; } } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Information used by the UI 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev getStats helps to fetch some stats for the GUI in a single web3 call * @param _user the address to return the report for * @return uint256[27] the stats * @return address of the current CEO * @return bytes32 Current graffiti */ function getStats(address _user) external view returns(uint256[] memory, address, bytes32, uint112[] memory) { uint[] memory ret = new uint[](27); uint112[] memory reserves = new uint112[](2); uint256 tpb = (CEO_price / 1000) / (CEO_epoch_blocks); // 0.1% per epoch uint256 debt = (block.number - taxBurnBlock) * tpb; uint256 price = CEO_price; UserInfo memory info = farmers[_user]; if (CEO_state == 2) { price = _calcDiscount(); } ret[0] = CEO_state; ret[1] = CEO_tax_balance; ret[2] = taxBurnBlock; // the block number last tax burn ret[3] = rewardsChangedBlock; // the block of the last staking rewards change ret[4] = price; // price of the CEO title ret[5] = CEO_punk_index; // punk ID of CEO ret[6] = cigPerBlock; // staking reward per block ret[7] = totalSupply; // total supply of CIG if (address(lpToken) != address(0)) { ret[8] = lpToken.balanceOf(address(this)); // Total LP staking ret[16] = lpToken.balanceOf(_user); // not staked by user ret[17] = pendingCig(_user); // pending harvest (reserves[0], reserves[1], ) = lpToken.getReserves(); // uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ret[18] = V2ROUTER.getAmountOut(1 ether, uint(reserves[0]), uint(reserves[1])); // CIG price in ETH if (isContract(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2))) { // are we on mainnet? ILiquidityPoolERC20 ethusd = ILiquidityPoolERC20(address(0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f)); // sushi DAI-WETH pool uint112 r0; uint112 r1; (r0, r1, ) = ethusd.getReserves(); // get the price of ETH in USD ret[19] = V2ROUTER.getAmountOut(1 ether, uint(r0), uint(r1)); // ETH price in USD } ret[22] = lpToken.totalSupply(); // total supply } ret[9] = block.number; // current block number ret[10] = tpb; // "tax per block" (tpb) ret[11] = debt; // tax debt accrued ret[12] = lastRewardBlock; // the block of the last staking rewards payout update ret[13] = info.deposit; // amount of LP tokens staked by user ret[14] = info.rewardDebt; // amount of rewards paid out ret[15] = balanceOf[_user]; // amount of CIG held by user ret[20] = accCigPerShare; // Accumulated cigarettes per share ret[21] = balanceOf[address(punks)]; // amount of CIG to be claimed ret[23] = wBal[_user]; // wrapped cig balance ret[24] = OC.balanceOf(_user); // balance of old cig in old isContract ret[25] = OC.allowance(_user, address(this));// is old contract approved (ret[26], ) = OC.userInfo(_user); // old contract stake bal return (ret, The_CEO, graffiti, reserves); } /** * @dev Returns true if `account` is a contract. * * credits https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol */ function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Token distribution and farming stuff 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev isClaimed checks to see if a punk was claimed * @param _punkIndex the punk number */ function isClaimed(uint256 _punkIndex) external view returns (bool) { if (claims[_punkIndex]) { return true; } if (OC.claims(_punkIndex)) { return true; } return false; } /** * Claim claims the initial CIG airdrop using a punk * @param _punkIndex the index of the punk, number between 0-9999 */ function claim(uint256 _punkIndex) external returns(bool) { require (CEO_state != 3, "invalid state"); // disabled in migration state require (_punkIndex <= 9999, "invalid punk"); require(claims[_punkIndex] == false, "punk already claimed"); require(OC.claims(_punkIndex) == false, "punk already claimed"); // claimed in old contract require(msg.sender == punks.punkIndexToAddress(_punkIndex), "punk 404"); claims[_punkIndex] = true; balanceOf[address(punks)] = balanceOf[address(punks)] - CLAIM_AMOUNT; // deduct from the punks contract balanceOf[msg.sender] = balanceOf[msg.sender] + CLAIM_AMOUNT; // deposit to the caller emit Transfer(address(punks), msg.sender, CLAIM_AMOUNT); emit Claim(msg.sender, _punkIndex, CLAIM_AMOUNT); return true; } /** * @dev Gets the LP supply, with masterchef deposits taken into account. */ function stakedlpSupply() public view returns(uint256) { return lpToken.balanceOf(address(this)) + masterchefDeposits; } /** * @dev update updates the accCigPerShare value and mints new CIG rewards to be distributed to LP stakers * Credits go to MasterChef.sol * Modified the original by removing poolInfo as there is only a single pool * Removed totalAllocPoint and pool.allocPoint * pool.lastRewardBlock moved to lastRewardBlock * There is no need for getMultiplier (rewards are adjusted by the CEO) * */ function update() public { if (block.number <= lastRewardBlock) { return; } uint256 supply = stakedlpSupply(); if (supply == 0) { lastRewardBlock = block.number; return; } // mint some new cigarette rewards to be distributed uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock; _mint(address(this), cigReward); accCigPerShare = accCigPerShare + ( cigReward * 1e12 / supply ); lastRewardBlock = block.number; } /** * @dev pendingCig displays the amount of cig to be claimed * @param _user the address to report */ function pendingCig(address _user) view public returns (uint256) { uint256 _acps = accCigPerShare; // accumulated cig per share UserInfo storage user = farmers[_user]; uint256 supply = stakedlpSupply(); if (block.number > lastRewardBlock && supply != 0) { uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock; _acps = _acps + ( cigReward * 1e12 / supply ); } return (user.deposit * _acps / 1e12) - user.rewardDebt; } /** * @dev userInfo is added for compatibility with the Snapshot.org interface. */ function userInfo(uint256, address _user) view external returns (uint256, uint256 depositAmount) { return (0,farmers[_user].deposit + farmersMasterchef[_user].deposit); } /** * @dev deposit deposits LP tokens to be staked. * @param _amount the amount of LP tokens to deposit. Assumes this contract has been approved for the _amount. */ function deposit(uint256 _amount) external { require(_amount != 0, "You cannot deposit only 0 tokens"); // Check how many bytes UserInfo storage user = farmers[msg.sender]; update(); _deposit(user, _amount); require(lpToken.transferFrom( address(msg.sender), address(this), _amount )); emit Deposit(msg.sender, _amount); } function _deposit(UserInfo storage _user, uint256 _amount) internal { _user.deposit += _amount; _user.rewardDebt += _amount * accCigPerShare / 1e12; } /** * @dev withdraw takes out the LP tokens * @param _amount the amount to withdraw */ function withdraw(uint256 _amount) external { UserInfo storage user = farmers[msg.sender]; update(); /* harvest beforehand, so _withdraw can safely decrement their reward count */ _harvest(user, msg.sender); _withdraw(user, _amount); /* Interact */ require(lpToken.transferFrom( address(this), address(msg.sender), _amount )); emit Withdraw(msg.sender, _amount); } /** * @dev Internal withdraw, updates internal accounting after withdrawing LP * @param _amount to subtract */ function _withdraw(UserInfo storage _user, uint256 _amount) internal { require(_user.deposit >= _amount, "Balance is too low"); _user.deposit -= _amount; uint256 _rewardAmount = _amount * accCigPerShare / 1e12; _user.rewardDebt -= _rewardAmount; } /** * @dev harvest redeems pending rewards & updates state */ function harvest() external { UserInfo storage user = farmers[msg.sender]; update(); _harvest(user, msg.sender); } /** * @dev Internal harvest * @param _to the amount to harvest */ function _harvest(UserInfo storage _user, address _to) internal { uint256 potentialValue = (_user.deposit * accCigPerShare / 1e12); uint256 delta = potentialValue - _user.rewardDebt; safeSendPayout(_to, delta); // Recalculate their reward debt now that we've given them their reward _user.rewardDebt = _user.deposit * accCigPerShare / 1e12; emit Harvest(msg.sender, _to, delta); } /** * @dev safeSendPayout, just in case if rounding error causes pool to not have enough CIGs. * @param _to recipient address * @param _amount the value to send */ function safeSendPayout(address _to, uint256 _amount) internal { uint256 cigBal = balanceOf[address(this)]; require(cigBal >= _amount, "insert more tobacco leaves..."); unchecked { balanceOf[address(this)] = balanceOf[address(this)] - _amount; balanceOf[_to] = balanceOf[_to] + _amount; } emit Transfer(address(this), _to, _amount); } /** * @dev emergencyWithdraw does a withdraw without caring about rewards. EMERGENCY ONLY. */ function emergencyWithdraw() external { UserInfo storage user = farmers[msg.sender]; uint256 amount = user.deposit; user.deposit = 0; user.rewardDebt = 0; // Interact require(lpToken.transfer( address(msg.sender), amount )); emit EmergencyWithdraw(msg.sender, amount); } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Migration 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev renounceOwnership burns the admin key, so this contract is unruggable */ function renounceOwnership() external onlyAdmin { admin = address(0); } /** * @dev setStartingBlock sets the starting block for LP staking rewards * Admin only, used only for initial configuration. * @param _startBlock the block to start rewards for */ function setStartingBlock(uint256 _startBlock) external onlyAdmin { lastRewardBlock = _startBlock; } /** * @dev setPool address to an LP pool. Only Admin. (used only in testing/deployment) */ function setPool(ILiquidityPoolERC20 _addr) external onlyAdmin { require(address(lpToken) == address(0), "pool already set"); lpToken = _addr; } /** * @dev setReward sets the reward. Admin only (used only in testing/deployment) */ function setReward(uint256 _value) public onlyAdmin { cigPerBlock = _value; } /** * @dev migrationComplete completes the migration */ function migrationComplete() external { require (CEO_state == 3); require (OC.CEO_state() == 1); require (block.number > lastRewardBlock, "cannot end migration yet"); CEO_state = 1; // CEO is in charge state OC.burnTax(); // before copy, burn the old CEO's tax /* copy the state over to this contract */ _mint(address(punks), OC.balanceOf(address(punks))); // CIG to be set aside for the remaining airdrop uint256 taxDeposit = OC.CEO_tax_balance(); The_CEO = OC.The_CEO(); // copy the CEO if (taxDeposit > 0) { // copy the CEO's outstanding tax _mint(address(this), taxDeposit); // mint tax that CEO had locked in previous contract (cannot be migrated) CEO_tax_balance = taxDeposit; } taxBurnBlock = OC.taxBurnBlock(); CEO_price = OC.CEO_price(); graffiti = OC.graffiti(); CEO_punk_index = OC.CEO_punk_index(); cigPerBlock = STARTING_REWARDS; // set special rewards lastRewardBlock = OC.lastRewardBlock();// start rewards rewardsChangedBlock = OC.rewardsChangedBlock(); /* Historical records */ _transferNFT( address(0), address(0x1e32a859d69dde58d03820F8f138C99B688D132F) ); emit NewCEO( address(0x1e32a859d69dde58d03820F8f138C99B688D132F), 0x00000000000000000000000000000000000000000000000000000000000015c9, 0x000000000000000000000000000000000000000000007618fa42aac317900000, 0x41732043454f2049206465636c617265204465632032322050756e6b20446179 ); _transferNFT( address(0x1e32a859d69dde58d03820F8f138C99B688D132F), address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d) ); emit NewCEO( address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d), 0x0000000000000000000000000000000000000000000000000000000000000343, 0x00000000000000000000000000000000000000000001a784379d99db42000000, 0x40617a756d615f626974636f696e000000000000000000000000000000000000 ); _transferNFT( address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d), address(0x4947DA4bEF9D79bc84bD584E6c12BfFa32D1bEc8) ); emit NewCEO( address(0x4947DA4bEF9D79bc84bD584E6c12BfFa32D1bEc8), 0x00000000000000000000000000000000000000000000000000000000000007fa, 0x00000000000000000000000000000000000000000014adf4b7320334b9000000, 0x46697273742070756e6b7320746f6b656e000000000000000000000000000000 ); } /** * @dev wrap wraps old CIG and issues new CIG 1:1 * @param _value how much old cig to wrap */ function wrap(uint256 _value) external { require (CEO_state == 3); OC.transferFrom(msg.sender, address(this), _value); // transfer old cig to here _mint(msg.sender, _value); // give user new cig wBal[msg.sender] = wBal[msg.sender] + _value; // record increase of wrapped old cig for caller } /** * @dev unwrap unwraps old CIG and burns new CIG 1:1 */ function unwrap(uint256 _value) external { require (CEO_state == 3); _burn(msg.sender, _value); // burn new cig OC.transfer(msg.sender, _value); // give back old cig wBal[msg.sender] = wBal[msg.sender] - _value; // record decrease of wrapped old cig for caller } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 ERC20 Token stuff 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev burn some tokens * @param _from The address to burn from * @param _amount The amount to burn */ function _burn(address _from, uint256 _amount) internal { balanceOf[_from] = balanceOf[_from] - _amount; totalSupply = totalSupply - _amount; emit Transfer(_from, address(0), _amount); } /** * @dev mint new tokens * @param _to The address to mint to. * @param _amount The amount to be minted. */ function _mint(address _to, uint256 _amount) internal { require(_to != address(0), "ERC20: mint to the zero address"); unchecked { totalSupply = totalSupply + _amount; balanceOf[_to] = balanceOf[_to] + _amount; } emit Transfer(address(0), _to, _amount); } /** * @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 <= balanceOf[msg.sender], "value exceeds balance"); // SafeMath already checks this balanceOf[msg.sender] = balanceOf[msg.sender] - _value; balanceOf[_to] = balanceOf[_to] + _value; emit Transfer(msg.sender, _to, _value); return true; } /** * @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) { uint256 a = allowance[_from][msg.sender]; // read allowance //require(_value <= balanceOf[_from], "value exceeds balance"); // SafeMath already checks this if (a != type(uint256).max) { // not infinite approval require(_value <= a, "not approved"); unchecked { allowance[_from][msg.sender] = a - _value; } } balanceOf[_from] = balanceOf[_from] - _value; balanceOf[_to] = balanceOf[_to] + _value; emit Transfer(_from, _to, _value); return true; } /** * @dev Approve tokens of mount _value to be spent by _spender * @param _spender address The spender * @param _value the stipend to spend */ function approve(address _spender, uint256 _value) external returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Masterchef v2 integration 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev onSushiReward implements the SushiSwap masterchefV2 callback, guarded by the onlyMCV2 modifier * @param _user address called on behalf of * @param _to address who send rewards to * @param _sushiAmount uint256, if not 0 then the rewards will be harvested * @param _newLpAmount uint256, amount of LP tokens staked at Sushi */ function onSushiReward ( uint256 /* pid */, address _user, address _to, uint256 _sushiAmount, uint256 _newLpAmount) external onlyMCV2 { UserInfo storage user = farmersMasterchef[_user]; update(); // Harvest sushi when there is sushiAmount passed through as this only comes in the event of the masterchef contract harvesting if(_sushiAmount != 0) _harvest(user, _to); // send outstanding CIG to _to uint256 delta; // Withdraw stake if(user.deposit >= _newLpAmount) { // Delta is withdraw delta = user.deposit - _newLpAmount; masterchefDeposits -= delta; // subtract from staked total _withdraw(user, delta); emit ChefWithdraw(_user, delta); } // Deposit stake else if(user.deposit != _newLpAmount) { // Delta is deposit delta = _newLpAmount - user.deposit; masterchefDeposits += delta; // add to staked total _deposit(user, delta); emit ChefDeposit(_user, delta); } } // onlyMCV2 ensures only the MasterChefV2 contract can call this modifier onlyMCV2 { require( msg.sender == MASTERCHEF_V2, "Only MCV2" ); _; } } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 interfaces 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev IRouterV2 is the sushi router 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F */ interface IRouterV2 { function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external pure returns(uint256 amountOut); } /** * @dev ICryptoPunk used to query the cryptopunks contract to verify the owner */ interface ICryptoPunk { //function balanceOf(address account) external view returns (uint256); function punkIndexToAddress(uint256 punkIndex) external returns (address); //function punksOfferedForSale(uint256 punkIndex) external returns (bool, uint256, address, uint256, address); //function buyPunk(uint punkIndex) external payable; //function transferPunk(address to, uint punkIndex) external; } interface ICEOERC721 { function transferFrom(address _from, address _to, uint256 _tokenId) external payable; } /* * @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 * 0xTycoon was here * 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 from UniswapV2Pair.sol */ interface ILiquidityPoolERC20 is IERC20 { function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast); function totalSupply() external view returns(uint); } interface IOldCigtoken is IERC20 { function claims(uint256) external view returns (bool); function graffiti() external view returns (bytes32); function cigPerBlock() external view returns (uint256); function The_CEO() external view returns (address); function CEO_punk_index() external view returns (uint); function CEO_price() external view returns (uint256); function CEO_state() external view returns (uint256); function CEO_tax_balance() external view returns (uint256); function taxBurnBlock() external view returns (uint256); function lastRewardBlock() external view returns (uint256); function rewardsChangedBlock() external view returns (uint256); function userInfo(address) external view returns (uint256, uint256); function burnTax() external; } // 🚬
deposit deposits LP tokens to be staked. _amount the amount of LP tokens to deposit. Assumes this contract has been approved for the _amount./
function deposit(uint256 _amount) external { UserInfo storage user = farmers[msg.sender]; update(); _deposit(user, _amount); require(lpToken.transferFrom( address(msg.sender), address(this), _amount )); emit Deposit(msg.sender, _amount); }
1,073,018
./full_match/80001/0x4bdbD516956B5C7950F1eF49d7a43D487341D82d/sources/contracts/messaging/libraries/MerkleLib.sol
Calculates and returns tree's current root. return _current bytes32 root./
function root(Tree storage tree) internal view returns (bytes32 _current) { uint256 _index = tree.count; if (_index == 0) { return Z_32; } uint256 i; assembly { let TREE_SLOT := tree.slot for { for { if and(_index, 1) { mstore(0, sload(TREE_SLOT)) mstore(0x20, Z_0) _current := keccak256(0, 0x40) break } if and(_index, shl(1, 1)) { mstore(0, sload(add(TREE_SLOT, 1))) mstore(0x20, Z_1) _current := keccak256(0, 0x40) i := 1 break } if and(_index, shl(2, 1)) { mstore(0, sload(add(TREE_SLOT, 2))) mstore(0x20, Z_2) _current := keccak256(0, 0x40) i := 2 break } if and(_index, shl(3, 1)) { mstore(0, sload(add(TREE_SLOT, 3))) mstore(0x20, Z_3) _current := keccak256(0, 0x40) i := 3 break } if and(_index, shl(4, 1)) { mstore(0, sload(add(TREE_SLOT, 4))) mstore(0x20, Z_4) _current := keccak256(0, 0x40) i := 4 break } if and(_index, shl(5, 1)) { mstore(0, sload(add(TREE_SLOT, 5))) mstore(0x20, Z_5) _current := keccak256(0, 0x40) i := 5 break } if and(_index, shl(6, 1)) { mstore(0, sload(add(TREE_SLOT, 6))) mstore(0x20, Z_6) _current := keccak256(0, 0x40) i := 6 break } if and(_index, shl(7, 1)) { mstore(0, sload(add(TREE_SLOT, 7))) mstore(0x20, Z_7) _current := keccak256(0, 0x40) i := 7 break } if and(_index, shl(8, 1)) { mstore(0, sload(add(TREE_SLOT, 8))) mstore(0x20, Z_8) _current := keccak256(0, 0x40) i := 8 break } if and(_index, shl(9, 1)) { mstore(0, sload(add(TREE_SLOT, 9))) mstore(0x20, Z_9) _current := keccak256(0, 0x40) i := 9 break } if and(_index, shl(10, 1)) { mstore(0, sload(add(TREE_SLOT, 10))) mstore(0x20, Z_10) _current := keccak256(0, 0x40) i := 10 break } if and(_index, shl(11, 1)) { mstore(0, sload(add(TREE_SLOT, 11))) mstore(0x20, Z_11) _current := keccak256(0, 0x40) i := 11 break } if and(_index, shl(12, 1)) { mstore(0, sload(add(TREE_SLOT, 12))) mstore(0x20, Z_12) _current := keccak256(0, 0x40) i := 12 break } if and(_index, shl(13, 1)) { mstore(0, sload(add(TREE_SLOT, 13))) mstore(0x20, Z_13) _current := keccak256(0, 0x40) i := 13 break } if and(_index, shl(14, 1)) { mstore(0, sload(add(TREE_SLOT, 14))) mstore(0x20, Z_14) _current := keccak256(0, 0x40) i := 14 break } if and(_index, shl(15, 1)) { mstore(0, sload(add(TREE_SLOT, 15))) mstore(0x20, Z_15) _current := keccak256(0, 0x40) i := 15 break } if and(_index, shl(16, 1)) { mstore(0, sload(add(TREE_SLOT, 16))) mstore(0x20, Z_16) _current := keccak256(0, 0x40) i := 16 break } if and(_index, shl(17, 1)) { mstore(0, sload(add(TREE_SLOT, 17))) mstore(0x20, Z_17) _current := keccak256(0, 0x40) i := 17 break } if and(_index, shl(18, 1)) { mstore(0, sload(add(TREE_SLOT, 18))) mstore(0x20, Z_18) _current := keccak256(0, 0x40) i := 18 break } if and(_index, shl(19, 1)) { mstore(0, sload(add(TREE_SLOT, 19))) mstore(0x20, Z_19) _current := keccak256(0, 0x40) i := 19 break } if and(_index, shl(20, 1)) { mstore(0, sload(add(TREE_SLOT, 20))) mstore(0x20, Z_20) _current := keccak256(0, 0x40) i := 20 break } if and(_index, shl(21, 1)) { mstore(0, sload(add(TREE_SLOT, 21))) mstore(0x20, Z_21) _current := keccak256(0, 0x40) i := 21 break } if and(_index, shl(22, 1)) { mstore(0, sload(add(TREE_SLOT, 22))) mstore(0x20, Z_22) _current := keccak256(0, 0x40) i := 22 break } if and(_index, shl(23, 1)) { mstore(0, sload(add(TREE_SLOT, 23))) mstore(0x20, Z_23) _current := keccak256(0, 0x40) i := 23 break } if and(_index, shl(24, 1)) { mstore(0, sload(add(TREE_SLOT, 24))) mstore(0x20, Z_24) _current := keccak256(0, 0x40) i := 24 break } if and(_index, shl(25, 1)) { mstore(0, sload(add(TREE_SLOT, 25))) mstore(0x20, Z_25) _current := keccak256(0, 0x40) i := 25 break } if and(_index, shl(26, 1)) { mstore(0, sload(add(TREE_SLOT, 26))) mstore(0x20, Z_26) _current := keccak256(0, 0x40) i := 26 break } if and(_index, shl(27, 1)) { mstore(0, sload(add(TREE_SLOT, 27))) mstore(0x20, Z_27) _current := keccak256(0, 0x40) i := 27 break } if and(_index, shl(28, 1)) { mstore(0, sload(add(TREE_SLOT, 28))) mstore(0x20, Z_28) _current := keccak256(0, 0x40) i := 28 break } if and(_index, shl(29, 1)) { mstore(0, sload(add(TREE_SLOT, 29))) mstore(0x20, Z_29) _current := keccak256(0, 0x40) i := 29 break } if and(_index, shl(30, 1)) { mstore(0, sload(add(TREE_SLOT, 30))) mstore(0x20, Z_30) _current := keccak256(0, 0x40) i := 30 break } if and(_index, shl(31, 1)) { mstore(0, sload(add(TREE_SLOT, 31))) mstore(0x20, Z_31) _current := keccak256(0, 0x40) i := 31 break } _current := Z_32 i := 32 break } if gt(i, 30) { break } { if lt(i, 1) { switch and(_index, shl(1, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_1) } default { mstore(0, sload(add(TREE_SLOT, 1))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 2) { switch and(_index, shl(2, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_2) } default { mstore(0, sload(add(TREE_SLOT, 2))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 3) { switch and(_index, shl(3, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_3) } default { mstore(0, sload(add(TREE_SLOT, 3))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 4) { switch and(_index, shl(4, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_4) } default { mstore(0, sload(add(TREE_SLOT, 4))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 5) { switch and(_index, shl(5, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_5) } default { mstore(0, sload(add(TREE_SLOT, 5))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 6) { switch and(_index, shl(6, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_6) } default { mstore(0, sload(add(TREE_SLOT, 6))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 7) { switch and(_index, shl(7, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_7) } default { mstore(0, sload(add(TREE_SLOT, 7))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 8) { switch and(_index, shl(8, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_8) } default { mstore(0, sload(add(TREE_SLOT, 8))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 9) { switch and(_index, shl(9, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_9) } default { mstore(0, sload(add(TREE_SLOT, 9))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 10) { switch and(_index, shl(10, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_10) } default { mstore(0, sload(add(TREE_SLOT, 10))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 11) { switch and(_index, shl(11, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_11) } default { mstore(0, sload(add(TREE_SLOT, 11))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 12) { switch and(_index, shl(12, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_12) } default { mstore(0, sload(add(TREE_SLOT, 12))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 13) { switch and(_index, shl(13, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_13) } default { mstore(0, sload(add(TREE_SLOT, 13))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 14) { switch and(_index, shl(14, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_14) } default { mstore(0, sload(add(TREE_SLOT, 14))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 15) { switch and(_index, shl(15, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_15) } default { mstore(0, sload(add(TREE_SLOT, 15))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 16) { switch and(_index, shl(16, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_16) } default { mstore(0, sload(add(TREE_SLOT, 16))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 17) { switch and(_index, shl(17, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_17) } default { mstore(0, sload(add(TREE_SLOT, 17))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 18) { switch and(_index, shl(18, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_18) } default { mstore(0, sload(add(TREE_SLOT, 18))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 19) { switch and(_index, shl(19, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_19) } default { mstore(0, sload(add(TREE_SLOT, 19))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 20) { switch and(_index, shl(20, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_20) } default { mstore(0, sload(add(TREE_SLOT, 20))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 21) { switch and(_index, shl(21, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_21) } default { mstore(0, sload(add(TREE_SLOT, 21))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 22) { switch and(_index, shl(22, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_22) } default { mstore(0, sload(add(TREE_SLOT, 22))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 23) { switch and(_index, shl(23, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_23) } default { mstore(0, sload(add(TREE_SLOT, 23))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 24) { switch and(_index, shl(24, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_24) } default { mstore(0, sload(add(TREE_SLOT, 24))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 25) { switch and(_index, shl(25, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_25) } default { mstore(0, sload(add(TREE_SLOT, 25))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 26) { switch and(_index, shl(26, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_26) } default { mstore(0, sload(add(TREE_SLOT, 26))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 27) { switch and(_index, shl(27, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_27) } default { mstore(0, sload(add(TREE_SLOT, 27))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 28) { switch and(_index, shl(28, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_28) } default { mstore(0, sload(add(TREE_SLOT, 28))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 29) { switch and(_index, shl(29, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_29) } default { mstore(0, sload(add(TREE_SLOT, 29))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 30) { switch and(_index, shl(30, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_30) } default { mstore(0, sload(add(TREE_SLOT, 30))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } if lt(i, 31) { switch and(_index, shl(31, 1)) case 0 { mstore(0, _current) mstore(0x20, Z_31) } default { mstore(0, sload(add(TREE_SLOT, 31))) mstore(0x20, _current) } _current := keccak256(0, 0x40) } } break } } }
9,459,364
/** *Submitted for verification at Etherscan.io on 2021-12-07 */ // File: @openzeppelin/contracts/utils/Counters.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /// /// @dev Interface for the NFT Royalty Standard /// interface IERC2981 is IERC165 { /// ERC165 bytes to add to interface array - set in parent contract /// implementing this standard /// /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a /// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /// _registerInterface(_INTERFACE_ID_ERC2981); /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) external view returns ( address receiver, uint256 royaltyAmount ); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: CosmicCoffeeCollective.sol pragma solidity ^0.8.10; contract CosmicCoffeeCollective is ERC721, ERC721Enumerable, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; using Address for address; // Sale info uint256 constant MAX_COSMIC_COFFEES = 12000; uint256 public constant MAX_PER_MINT = 5; uint256 public communitySaleprice = 25000000000000000; // 0.025 ETH uint256 public price = 50000000000000000; // 0.05 ETH uint256 public CosmicCoffees = 10000; uint256 public constant MAX_FREECOFFEE_MINT = 50; // Token Availability uint256 public reservedClaimed; uint256 public numFreeCoffeeMinted; uint256 public reserved = 2000; // Reserved for the team, giveaways, collabs and so on // The base link that leads to the image / metadata of the token string public baseTokenURI; //Starting and stopping the sale bool public communitySaleStarted = false; bool public publicSaleStarted = false; // Team addresses for withdrawals address public a1 = 0xcc8d8F2451Dc756FB612DDD104ee148EdFCDD146; //Artist Wallet address public a2 = 0x8AA41A73deAD00D9DE913E4B10273D050703Fe3d; //Dev Wallet address public a3 = 0xdF968Caf4C2fB59bDb2Bfd9f43d06fa4491b38fb; //Founder Wallet address public a4 = 0xb5C224e0c8E5D7587b49434F858332AB95A79434; //Community Wallet address public a5 = 0x8dA2666D10f887a6D71EbD8577e6df80F6E2aB4e; //Charity Wallet //mapping mapping(address => bool) private _communityEligible; mapping(address => uint256) private _totalClaimed; // events event BaseURIChanged(string baseURI); event CommunityMint(address minter, uint256 amountOfFreeCoffee); event PublicSaleMint(address minter, uint256 amountOfFreeCoffee); //modifiers modifier whenCommunitySaleStarted() { require(communitySaleStarted, "Community sale is not active fren"); _; } modifier whenPublicSaleStarted() { require(publicSaleStarted, "Public sale is not active ser"); _; } constructor (string memory newBaseURI) ERC721 ("Cosmic Coffee Collective", "FREECOFFEE") { setBaseURI(newBaseURI); numFreeCoffeeMinted += 1; _safeMint(msg.sender, numFreeCoffeeMinted); } // add addresses to Community Sale function addToCommunitySale(address[] calldata addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Cannot add null address"); _communityEligible[addresses[i]] = true; _totalClaimed[addresses[i]] > 0 ? _totalClaimed[addresses[i]] : 0; } } // enter address to determine if eligible for Cosmic Coffee Community sale function checkCommunityEligiblity(address addr) external view returns (bool) { return _communityEligible[addr]; } ///// Minting Funtions ///// // Admin minting to use for giveaways, collabs, and so on... function claimReserved(address recipient, uint256 amount) external onlyOwner { require(reservedClaimed != reserved, "Already have claimed all reserved Cosmic Coffees"); require(reservedClaimed + amount <= reserved, "Minting would exceed max reserved Cosmic Coffees"); require(recipient != address(0), "Cannot add null address"); require(totalSupply() < MAX_COSMIC_COFFEES, "All tokens have been minted"); require(totalSupply() + amount <= MAX_COSMIC_COFFEES, "Minting would exceed max supply"); uint256 _nextTokenId = numFreeCoffeeMinted + 1; for (uint256 i = 0; i < amount; i++) { _safeMint(recipient, _nextTokenId + i); } numFreeCoffeeMinted += amount; reservedClaimed += amount; } // Cosmic Coffee Community Sale price minting function mintCommunity(uint256 amountOfFreeCoffee) external payable whenCommunitySaleStarted { require(_communityEligible[msg.sender], "You are not eligible for the Cosmic Coffee community minting fren"); require(totalSupply() < MAX_COSMIC_COFFEES, "All tokens have been minted fren"); require(amountOfFreeCoffee <= MAX_PER_MINT, "Cannot purchase this many tokens during community minting fren"); require(totalSupply() + amountOfFreeCoffee <= MAX_COSMIC_COFFEES, "Minting would exceed max supply fren"); require(_totalClaimed[msg.sender] + amountOfFreeCoffee <= MAX_PER_MINT, "Purchase exceeds max allowed fren"); require(amountOfFreeCoffee > 0, "Must mint at least one cosmic coffee"); require(communitySaleprice * amountOfFreeCoffee == msg.value, "ETH amount is incorrect"); for (uint256 i = 0; i < amountOfFreeCoffee; i++) { uint256 tokenId = numFreeCoffeeMinted + 1; numFreeCoffeeMinted += 1; _totalClaimed[msg.sender] += 1; _safeMint(msg.sender, tokenId); } emit CommunityMint(msg.sender, amountOfFreeCoffee); } // Public Minting of Cosmic Coffees function mint(uint256 amountOfFreeCoffee) external payable whenPublicSaleStarted { require(totalSupply() < MAX_COSMIC_COFFEES, "All tokens have been minted fren"); require(amountOfFreeCoffee <= MAX_PER_MINT, "Cannot purchase this many tokens during community minting fren"); require(totalSupply() + amountOfFreeCoffee <= MAX_COSMIC_COFFEES, "Minting would exceed max supply fren"); require(_totalClaimed[msg.sender] + amountOfFreeCoffee <= MAX_PER_MINT, "Purchase exceeds max allowed fren"); require(amountOfFreeCoffee > 0, "Must mint at least one cosmic coffee"); require(price * amountOfFreeCoffee == msg.value, "ETH amount is incorrect"); for (uint256 i = 0; i < amountOfFreeCoffee; i++) { uint256 tokenId = numFreeCoffeeMinted + 1; numFreeCoffeeMinted += 1; _totalClaimed[msg.sender] += 1; _safeMint(msg.sender, tokenId); } emit PublicSaleMint(msg.sender, amountOfFreeCoffee); } // See which address owns which tokens function tokensOfOwner(address addr) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(addr); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(addr, i); } return tokensId; } ///// Owner Administrative ///// // Toggle to start/stop Cosmic Coffee Community Sale function toggleCommunitySaleStarted() external onlyOwner { communitySaleStarted = !communitySaleStarted; } // Toggle to start/stop Public Sale function togglePublicSaleStarted() external onlyOwner { publicSaleStarted = !publicSaleStarted; } // Override so the openzeppelin tokenURI() method will use this method to create the full tokenURI instead function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } // Update Base URI post deployment of smart contract function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; emit BaseURIChanged(baseURI); } // Set a different price in case ETH changes drastically function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } // Set team addresses function setAddresses(address[] memory _a) public onlyOwner { a1 = _a[0]; a2 = _a[1]; a3 = _a[2]; a4 = _a[3]; a5 = _a[4]; } // Withdraw funds from contract for the team function withdrawTeam(uint256 amount) public payable onlyOwner { uint256 percent = amount / 100; // 25% to each team wallet require(payable(a1).send(percent * 25)); require(payable(a2).send(percent * 25)); require(payable(a3).send(percent * 25)); // 15% will got to the community wallet to support community (and neighboring community) projects require(payable(a4).send(percent * 15)); // 10% will got to the charity wallet to support coffee farms and other organizations identified by the community require(payable(a5).send(percent * 10)); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721,ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
Public Minting of Cosmic Coffees
function mint(uint256 amountOfFreeCoffee) external payable whenPublicSaleStarted { require(totalSupply() < MAX_COSMIC_COFFEES, "All tokens have been minted fren"); require(amountOfFreeCoffee <= MAX_PER_MINT, "Cannot purchase this many tokens during community minting fren"); require(totalSupply() + amountOfFreeCoffee <= MAX_COSMIC_COFFEES, "Minting would exceed max supply fren"); require(_totalClaimed[msg.sender] + amountOfFreeCoffee <= MAX_PER_MINT, "Purchase exceeds max allowed fren"); require(amountOfFreeCoffee > 0, "Must mint at least one cosmic coffee"); require(price * amountOfFreeCoffee == msg.value, "ETH amount is incorrect"); for (uint256 i = 0; i < amountOfFreeCoffee; i++) { uint256 tokenId = numFreeCoffeeMinted + 1; numFreeCoffeeMinted += 1; _totalClaimed[msg.sender] += 1; _safeMint(msg.sender, tokenId); } emit PublicSaleMint(msg.sender, amountOfFreeCoffee); }
8,077,461
./full_match/80001/0x856c7b441b104C45f18D3D4f874b3dBaFb7AF33e/sources/StakingContract.sol
_setTokenURI(newTokenId, getTokenURI(newTokenId));_sendReward(msg.value); Set the NFT referral ID Emit the NFTMinted event Update the referral count for the referrer if a referral ID was provided
function mintStarter(uint256 _referralId) public payable returns (uint256) { require(msg.value >= STARTER_PRICE, "Insufficient MATIC Sent"); require( _referralId >= STARTER_MIN_ID && _referralId <= DIAMOND_MAX_ID, "ENTER LOW LEVEL REFERRAL ID" ); address _to = msg.sender; uint256 newTokenId = _typeTokenIds[STARTER].current() + STARTER_MIN_ID; uint256 _id = newTokenId; require( newTokenId <= STARTER_MAX_ID, "All starter tokens have been minted" ); _safeMint(msg.sender, newTokenId); _setTokenURI(newTokenId, string(abi.encodePacked(STARTER_URI))); _typeTokenIds[STARTER].increment(); giankyToken.safeTransfer(msg.sender, STARTER_r); nftReferrals[_id] = _referralId; emit NFTMinted(_id, _to, _referralId); distributeRewards(_id); if (_referralId != 0) { _updateReferralCount(_referralId); } if (_referralId != 0) { _updateReferralCountstarter(_referralId); incrementReferralCountStarter(newTokenId); } return newTokenId; }
5,647,733
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.7.2; import { IMACI } from "./IMACI.sol"; import { Params } from "./Params.sol"; import { Hasher } from "./crypto/Hasher.sol"; import { Verifier } from "./crypto/Verifier.sol"; import { SnarkCommon } from "./crypto/SnarkCommon.sol"; import { SnarkConstants } from "./crypto/SnarkConstants.sol"; import { DomainObjs, IPubKey, IMessage } from "./DomainObjs.sol"; import { AccQueue, AccQueueQuinaryMaci } from "./trees/AccQueue.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { VkRegistry } from "./VkRegistry.sol"; import { EmptyBallotRoots } from "./trees/EmptyBallotRoots.sol"; contract MessageAqFactory is Ownable { function deploy(uint256 _subDepth) public onlyOwner returns (AccQueue) { AccQueue aq = new AccQueueQuinaryMaci(_subDepth); aq.transferOwnership(owner()); return aq; } } contract PollDeploymentParams { struct ExtContracts { VkRegistry vkRegistry; IMACI maci; AccQueue messageAq; } } /* * A factory contract which deploys Poll contracts. It allows the MACI contract * size to stay within the limit set by EIP-170. */ contract PollFactory is Params, IPubKey, IMessage, Ownable, Hasher, PollDeploymentParams { MessageAqFactory public messageAqFactory; function setMessageAqFactory(MessageAqFactory _messageAqFactory) public onlyOwner { messageAqFactory = _messageAqFactory; } /* * Deploy a new Poll contract and AccQueue contract for messages. */ function deploy( uint256 _duration, MaxValues memory _maxValues, TreeDepths memory _treeDepths, BatchSizes memory _batchSizes, PubKey memory _coordinatorPubKey, VkRegistry _vkRegistry, IMACI _maci, address _pollOwner ) public onlyOwner returns (Poll) { uint256 treeArity = 5; // Validate _maxValues // NOTE: these checks may not be necessary. Removing them will save // 0.28 Kb of bytecode. // maxVoteOptions must be less than 2 ** 50 due to circuit limitations; // it will be packed as a 50-bit value along with other values as one // of the inputs (aka packedVal) require( _maxValues.maxMessages <= treeArity ** uint256(_treeDepths.messageTreeDepth) && _maxValues.maxMessages >= _batchSizes.messageBatchSize && _maxValues.maxMessages % _batchSizes.messageBatchSize == 0 && _maxValues.maxVoteOptions <= treeArity ** uint256(_treeDepths.voteOptionTreeDepth) && _maxValues.maxVoteOptions < (2 ** 50), "PollFactory: invalid _maxValues" ); AccQueue messageAq = messageAqFactory.deploy(_treeDepths.messageTreeSubDepth); ExtContracts memory extContracts; // TODO: remove _vkRegistry; only PollProcessorAndTallyer needs it extContracts.vkRegistry = _vkRegistry; extContracts.maci = _maci; extContracts.messageAq = messageAq; Poll poll = new Poll( _duration, _maxValues, _treeDepths, _batchSizes, _coordinatorPubKey, extContracts ); // Make the Poll contract own the messageAq contract, so only it can // run enqueue/merge messageAq.transferOwnership(address(poll)); // TODO: should this be _maci.owner() instead? poll.transferOwnership(_pollOwner); return poll; } } /* * Do not deploy this directly. Use PollFactory.deploy() which performs some * checks on the Poll constructor arguments. */ contract Poll is Params, Hasher, IMessage, IPubKey, SnarkCommon, Ownable, PollDeploymentParams, EmptyBallotRoots { // The coordinator's public key PubKey public coordinatorPubKey; uint256 public mergedStateRoot; uint256 public coordinatorPubKeyHash; // TODO: to reduce the Poll bytecode size, consider storing deployTime and // duration in a mapping in the MACI contract // The timestamp of the block at which the Poll was deployed uint256 internal deployTime; // The duration of the polling period, in seconds uint256 internal duration; function getDeployTimeAndDuration() public view returns (uint256, uint256) { return (deployTime, duration); } // Whether the MACI contract's stateAq has been merged by this contract bool public stateAqMerged; // The commitment to the state leaves and the ballots. This is // hash3(stateRoot, ballotRoot, salt). // Its initial value should be // hash(maciStateRootSnapshot, emptyBallotRoot, 0) // Each successful invocation of processMessages() should use a different // salt to update this value, so that an external observer cannot tell in // the case that none of the messages are valid. uint256 public currentSbCommitment; uint256 internal numMessages; function numSignUpsAndMessages() public view returns (uint256, uint256) { uint numSignUps = extContracts.maci.numSignUps(); return (numSignUps, numMessages); } MaxValues public maxValues; TreeDepths public treeDepths; BatchSizes public batchSizes; // Error codes. We store them as constants and keep them short to reduce // this contract's bytecode size. string constant ERROR_VK_NOT_SET = "PollE01"; string constant ERROR_SB_COMMITMENT_NOT_SET = "PollE02"; string constant ERROR_VOTING_PERIOD_PASSED = "PollE03"; string constant ERROR_VOTING_PERIOD_NOT_PASSED = "PollE04"; string constant ERROR_INVALID_PUBKEY = "PollE05"; string constant ERROR_MAX_MESSAGES_REACHED = "PollE06"; string constant ERROR_STATE_AQ_ALREADY_MERGED = "PollE07"; string constant ERROR_STATE_AQ_SUBTREES_NEED_MERGE = "PollE08"; uint8 private constant LEAVES_PER_NODE = 5; event PublishMessage(Message _message, PubKey _encPubKey); event MergeMaciStateAqSubRoots(uint256 _numSrQueueOps); event MergeMaciStateAq(uint256 _stateRoot); event MergeMessageAqSubRoots(uint256 _numSrQueueOps); event MergeMessageAq(uint256 _messageRoot); ExtContracts public extContracts; /* * Each MACI instance can have multiple Polls. * When a Poll is deployed, its voting period starts immediately. */ constructor( uint256 _duration, MaxValues memory _maxValues, TreeDepths memory _treeDepths, BatchSizes memory _batchSizes, PubKey memory _coordinatorPubKey, ExtContracts memory _extContracts ) { extContracts = _extContracts; coordinatorPubKey = _coordinatorPubKey; coordinatorPubKeyHash = hashLeftRight(_coordinatorPubKey.x, _coordinatorPubKey.y); duration = _duration; maxValues = _maxValues; batchSizes = _batchSizes; treeDepths = _treeDepths; // Record the current timestamp deployTime = block.timestamp; } /* * A modifier that causes the function to revert if the voting period is * not over. */ modifier isAfterVotingDeadline() { uint256 secondsPassed = block.timestamp - deployTime; require( secondsPassed > duration, ERROR_VOTING_PERIOD_NOT_PASSED ); _; } function isAfterDeadline() public view returns (bool) { uint256 secondsPassed = block.timestamp - deployTime; return secondsPassed > duration; } /* * Allows anyone to publish a message (an encrypted command and signature). * This function also enqueues the message. * @param _message The message to publish * @param _encPubKey An epheremal public key which can be combined with the * coordinator's private key to generate an ECDH shared key with which * to encrypt the message. */ function publishMessage( Message memory _message, PubKey memory _encPubKey ) public { uint256 secondsPassed = block.timestamp - deployTime; require( secondsPassed <= duration, ERROR_VOTING_PERIOD_PASSED ); require( numMessages <= maxValues.maxMessages, ERROR_MAX_MESSAGES_REACHED ); require( _encPubKey.x < SNARK_SCALAR_FIELD && _encPubKey.y < SNARK_SCALAR_FIELD, ERROR_INVALID_PUBKEY ); uint256 messageLeaf = hashMessageAndEncPubKey(_message, _encPubKey); extContracts.messageAq.enqueue(messageLeaf); numMessages ++; emit PublishMessage(_message, _encPubKey); } function hashMessageAndEncPubKey( Message memory _message, PubKey memory _encPubKey ) public pure returns (uint256) { uint256[5] memory n; n[0] = _message.data[0]; n[1] = _message.data[1]; n[2] = _message.data[2]; n[3] = _message.data[3]; n[4] = _message.data[4]; uint256[5] memory m; m[0] = _message.data[5]; m[1] = _message.data[6]; m[2] = _message.data[7]; m[3] = _message.data[8]; m[4] = _message.data[9]; return hash4([ hash5(n), hash5(m), _encPubKey.x, _encPubKey.y ]); } /* * The first step of merging the MACI state AccQueue. This allows the * ProcessMessages circuit to access the latest state tree and ballots via * currentSbCommitment. */ function mergeMaciStateAqSubRoots( uint256 _numSrQueueOps, uint256 _pollId ) public onlyOwner isAfterVotingDeadline { // This function can only be called once per Poll require(!stateAqMerged, ERROR_STATE_AQ_ALREADY_MERGED); if (!extContracts.maci.stateAq().subTreesMerged()) { extContracts.maci.mergeStateAqSubRoots(_numSrQueueOps, _pollId); } emit MergeMaciStateAqSubRoots(_numSrQueueOps); } /* * The second step of merging the MACI state AccQueue. This allows the * ProcessMessages circuit to access the latest state tree and ballots via * currentSbCommitment. */ function mergeMaciStateAq( uint256 _pollId ) public onlyOwner isAfterVotingDeadline { // This function can only be called once per Poll after the voting // deadline require(!stateAqMerged, ERROR_STATE_AQ_ALREADY_MERGED); require(extContracts.maci.stateAq().subTreesMerged(), ERROR_STATE_AQ_SUBTREES_NEED_MERGE); extContracts.maci.mergeStateAq(_pollId); stateAqMerged = true; mergedStateRoot = extContracts.maci.getStateAqRoot(); // Set currentSbCommitment uint256[3] memory sb; sb[0] = mergedStateRoot; sb[1] = emptyBallotRoots[treeDepths.voteOptionTreeDepth - 1]; sb[2] = uint256(0); currentSbCommitment = hash3(sb); emit MergeMaciStateAq(mergedStateRoot); } /* * The first step in merging the message AccQueue so that the * ProcessMessages circuit can access the message root. */ function mergeMessageAqSubRoots(uint256 _numSrQueueOps) public onlyOwner isAfterVotingDeadline { extContracts.messageAq.mergeSubRoots(_numSrQueueOps); emit MergeMessageAqSubRoots(_numSrQueueOps); } /* * The second step in merging the message AccQueue so that the * ProcessMessages circuit can access the message root. */ function mergeMessageAq() public onlyOwner isAfterVotingDeadline { uint256 root = extContracts.messageAq.merge(treeDepths.messageTreeDepth); emit MergeMessageAq(root); } /* * Enqueue a batch of messages. */ function batchEnqueueMessage(uint256 _messageSubRoot) public onlyOwner isAfterVotingDeadline { extContracts.messageAq.insertSubTree(_messageSubRoot); // TODO: emit event } /* * @notice Verify the number of spent voice credits from the tally.json * @param _totalSpent spent field retrieved in the totalSpentVoiceCredits object * @param _totalSpentSalt the corresponding salt in the totalSpentVoiceCredit object * @return valid a boolean representing successful verification */ function verifySpentVoiceCredits( uint256 _totalSpent, uint256 _totalSpentSalt ) public view returns (bool) { uint256 ballotRoot = hashLeftRight(_totalSpent, _totalSpentSalt); return ballotRoot == emptyBallotRoots[treeDepths.voteOptionTreeDepth - 1]; } /* * @notice Verify the number of spent voice credits per vote option from the tally.json * @param _voteOptionIndex the index of the vote option where credits were spent * @param _spent the spent voice credits for a given vote option index * @param _spentProof proof generated for the perVOSpentVoiceCredits * @param _salt the corresponding salt given in the tally perVOSpentVoiceCredits object * @return valid a boolean representing successful verification */ function verifyPerVOSpentVoiceCredits( uint256 _voteOptionIndex, uint256 _spent, uint256[][] memory _spentProof, uint256 _spentSalt ) public view returns (bool) { uint256 computedRoot = computeMerkleRootFromPath( treeDepths.voteOptionTreeDepth, _voteOptionIndex, _spent, _spentProof ); uint256 ballotRoot = hashLeftRight(computedRoot, _spentSalt); uint256[3] memory sb; sb[0] = mergedStateRoot; sb[1] = ballotRoot; sb[2] = uint256(0); return currentSbCommitment == hash3(sb); } /* * @notice Verify the result generated of the tally.json * @param _voteOptionIndex the index of the vote option to verify the correctness of the tally * @param _tallyResult Flattened array of the tally * @param _tallyResultProof Corresponding proof of the tally result * @param _tallyResultSalt the respective salt in the results object in the tally.json * @param _spentVoiceCreditsHash hashLeftRight(number of spent voice credits, spent salt) * @param _perVOSpentVoiceCreditsHash hashLeftRight(merkle root of the no spent voice credits per vote option, perVOSpentVoiceCredits salt) * @param _tallyCommitment newTallyCommitment field in the tally.json * @return valid a boolean representing successful verification */ function verifyTallyResult( uint256 _voteOptionIndex, uint256 _tallyResult, uint256[][] memory _tallyResultProof, uint256 _spentVoiceCreditsHash, uint256 _perVOSpentVoiceCreditsHash, uint256 _tallyCommitment ) public view returns (bool){ uint256 computedRoot = computeMerkleRootFromPath( treeDepths.voteOptionTreeDepth, _voteOptionIndex, _tallyResult, _tallyResultProof ); uint256[3] memory tally; tally[0] = computedRoot; tally[1] = _spentVoiceCreditsHash; tally[2] = _perVOSpentVoiceCreditsHash; return hash3(tally) == _tallyCommitment; } function computeMerkleRootFromPath( uint8 _depth, uint256 _index, uint256 _leaf, uint256[][] memory _pathElements ) internal pure returns (uint256) { uint256 pos = _index % LEAVES_PER_NODE; uint256 current = _leaf; uint8 k; uint256[LEAVES_PER_NODE] memory level; for (uint8 i = 0; i < _depth; i ++) { for (uint8 j = 0; j < LEAVES_PER_NODE; j ++) { if (j == pos) { level[j] = current; } else { if (j > pos) { k = j - 1; } else { k = j; } level[j] = _pathElements[i][k]; } } _index /= LEAVES_PER_NODE; pos = _index % LEAVES_PER_NODE; current = hash5(level); } return current; } } contract PollProcessorAndTallyer is Ownable, SnarkCommon, SnarkConstants, IPubKey, PollDeploymentParams{ // Error codes string constant ERROR_VOTING_PERIOD_NOT_PASSED = "PptE01"; string constant ERROR_NO_MORE_MESSAGES = "PptE02"; string constant ERROR_MESSAGE_AQ_NOT_MERGED = "PptE03"; string constant ERROR_INVALID_STATE_ROOT_SNAPSHOT_TIMESTAMP = "PptE04"; string constant ERROR_INVALID_PROCESS_MESSAGE_PROOF = "PptE05"; string constant ERROR_INVALID_TALLY_VOTES_PROOF = "PptE06"; string constant ERROR_PROCESSING_NOT_COMPLETE = "PptE07"; string constant ERROR_ALL_BALLOTS_TALLIED = "PptE08"; string constant ERROR_STATE_AQ_NOT_MERGED = "PptE09"; string constant ERROR_ALL_SUBSIDY_CALCULATED = "PptE10"; string constant ERROR_INVALID_SUBSIDY_PROOF = "PptE11"; // The commitment to the state and ballot roots uint256 public sbCommitment; // The current message batch index. When the coordinator runs // processMessages(), this action relates to messages // currentMessageBatchIndex to currentMessageBatchIndex + messageBatchSize. uint256 public currentMessageBatchIndex; // Whether there are unprocessed messages left bool public processingComplete; // The number of batches processed uint256 public numBatchesProcessed; // The commitment to the tally results. Its initial value is 0, but after // the tally of each batch is proven on-chain via a zk-SNARK, it should be // updated to: // // hash3( // hashLeftRight(merkle root of current results, salt0) // hashLeftRight(number of spent voice credits, salt1), // hashLeftRight(merkle root of the no. of spent voice credits per vote option, salt2) // ) // // Where each salt is unique and the merkle roots are of arrays of leaves // TREE_ARITY ** voteOptionTreeDepth long. uint256 public tallyCommitment; uint256 public tallyBatchNum; uint256 public subsidyCommitment; uint256 public rbi; // row batch index uint256 public cbi; // column batch index Verifier public verifier; constructor( Verifier _verifier ) { verifier = _verifier; } modifier votingPeriodOver(Poll _poll) { (uint256 deployTime, uint256 duration) = _poll.getDeployTimeAndDuration(); // Require that the voting period is over uint256 secondsPassed = block.timestamp - deployTime; require( secondsPassed > duration, ERROR_VOTING_PERIOD_NOT_PASSED ); _; } /* * Hashes an array of values using SHA256 and returns its modulo with the * snark scalar field. This function is used to hash inputs to circuits, * where said inputs would otherwise be public inputs. As such, the only * public input to the circuit is the SHA256 hash, and all others are * private inputs. The circuit will verify that the hash is valid. Doing so * saves a lot of gas during verification, though it makes the circuit take * up more constraints. */ function sha256Hash(uint256[] memory array) public pure returns (uint256) { return uint256(sha256(abi.encodePacked(array))) % SNARK_SCALAR_FIELD; } /* * Update the Poll's currentSbCommitment if the proof is valid. * @param _poll The poll to update * @param _newSbCommitment The new state root and ballot root commitment * after all messages are processed * @param _proof The zk-SNARK proof */ function processMessages( Poll _poll, uint256 _newSbCommitment, uint256[8] memory _proof ) public onlyOwner votingPeriodOver(_poll) { // There must be unprocessed messages require(!processingComplete, ERROR_NO_MORE_MESSAGES); // The state AccQueue must be merged require(_poll.stateAqMerged(), ERROR_STATE_AQ_NOT_MERGED); // Retrieve stored vals ( , , uint8 messageTreeDepth,) = _poll.treeDepths(); (uint256 messageBatchSize,, ) = _poll.batchSizes(); AccQueue messageAq; (, , messageAq) = _poll.extContracts(); // Require that the message queue has been merged uint256 messageRoot = messageAq.getMainRoot(messageTreeDepth); require(messageRoot != 0, ERROR_MESSAGE_AQ_NOT_MERGED); // Copy the state and ballot commitment and set the batch index if this // is the first batch to process if (numBatchesProcessed == 0) { uint256 currentSbCommitment = _poll.currentSbCommitment(); sbCommitment = currentSbCommitment; (, uint256 numMessages) = _poll.numSignUpsAndMessages(); uint256 r = numMessages % messageBatchSize; if (r == 0) { currentMessageBatchIndex = (numMessages / messageBatchSize) * messageBatchSize; } else { currentMessageBatchIndex = numMessages; } if (currentMessageBatchIndex > 0) { if (r == 0) { currentMessageBatchIndex -= messageBatchSize; } else { currentMessageBatchIndex -= r; } } } bool isValid = verifyProcessProof( _poll, currentMessageBatchIndex, messageRoot, sbCommitment, _newSbCommitment, _proof ); require(isValid, ERROR_INVALID_PROCESS_MESSAGE_PROOF); { (, uint256 numMessages) = _poll.numSignUpsAndMessages(); // Decrease the message batch start index to ensure that each // message batch is processed in order if (currentMessageBatchIndex > 0) { currentMessageBatchIndex -= messageBatchSize; } updateMessageProcessingData( _newSbCommitment, currentMessageBatchIndex, numMessages <= messageBatchSize * (numBatchesProcessed + 1) ); } } function verifyProcessProof( Poll _poll, uint256 _currentMessageBatchIndex, uint256 _messageRoot, uint256 _currentSbCommitment, uint256 _newSbCommitment, uint256[8] memory _proof ) internal view returns (bool) { ( , , uint8 messageTreeDepth, uint8 voteOptionTreeDepth) = _poll.treeDepths(); (uint256 messageBatchSize,,) = _poll.batchSizes(); (uint256 numSignUps, ) = _poll.numSignUpsAndMessages(); (VkRegistry vkRegistry, IMACI maci, ) = _poll.extContracts(); // Calculate the public input hash (a SHA256 hash of several values) uint256 publicInputHash = genProcessMessagesPublicInputHash( _poll, _currentMessageBatchIndex, _messageRoot, numSignUps, _currentSbCommitment, _newSbCommitment ); // Get the verifying key from the VkRegistry VerifyingKey memory vk = vkRegistry.getProcessVk( maci.stateTreeDepth(), messageTreeDepth, voteOptionTreeDepth, messageBatchSize ); return verifier.verify(_proof, vk, publicInputHash); } /* * Returns the SHA256 hash of the packed values (see * genProcessMessagesPackedVals), the hash of the coordinator's public key, * the message root, and the commitment to the current state root and * ballot root. By passing the SHA256 hash of these values to the circuit * as a single public input and the preimage as private inputs, we reduce * its verification gas cost though the number of constraints will be * higher and proving time will be higher. */ function genProcessMessagesPublicInputHash( Poll _poll, uint256 _currentMessageBatchIndex, uint256 _messageRoot, uint256 _numSignUps, uint256 _currentSbCommitment, uint256 _newSbCommitment ) public view returns (uint256) { uint256 coordinatorPubKeyHash = _poll.coordinatorPubKeyHash(); uint256 packedVals = genProcessMessagesPackedVals( _poll, _currentMessageBatchIndex, _numSignUps ); (uint256 deployTime, uint256 duration) = _poll.getDeployTimeAndDuration(); uint256[] memory input = new uint256[](6); input[0] = packedVals; input[1] = coordinatorPubKeyHash; input[2] = _messageRoot; input[3] = _currentSbCommitment; input[4] = _newSbCommitment; input[5] = deployTime + duration; uint256 inputHash = sha256Hash(input); return inputHash; } /* * One of the inputs to the ProcessMessages circuit is a 250-bit * representation of four 50-bit values. This function generates this * 250-bit value, which consists of the maximum number of vote options, the * number of signups, the current message batch index, and the end index of * the current batch. */ function genProcessMessagesPackedVals( Poll _poll, uint256 _currentMessageBatchIndex, uint256 _numSignUps ) public view returns (uint256) { (, uint256 maxVoteOptions) = _poll.maxValues(); (, uint256 numMessages) = _poll.numSignUpsAndMessages(); (uint8 mbs,,) = _poll.batchSizes(); uint256 messageBatchSize = uint256(mbs); uint256 batchEndIndex = _currentMessageBatchIndex + messageBatchSize; if (batchEndIndex > numMessages) { batchEndIndex = numMessages; } uint256 result = maxVoteOptions + (_numSignUps << uint256(50)) + (_currentMessageBatchIndex << uint256(100)) + (batchEndIndex << uint256(150)); return result; } function updateMessageProcessingData( uint256 _newSbCommitment, uint256 _currentMessageBatchIndex, bool _processingComplete ) internal { sbCommitment = _newSbCommitment; processingComplete = _processingComplete; currentMessageBatchIndex = _currentMessageBatchIndex; numBatchesProcessed ++; } function genSubsidyPackedVals(uint256 _numSignUps) public view returns (uint256) { // TODO: ensure that each value is less than or equal to 2 ** 50 uint256 result = (_numSignUps << uint256(100)) + (rbi << uint256(50))+ cbi; return result; } function genSubsidyPublicInputHash( uint256 _numSignUps, uint256 _newSubsidyCommitment ) public view returns (uint256) { uint256 packedVals = genSubsidyPackedVals(_numSignUps); uint256[] memory input = new uint256[](4); input[0] = packedVals; input[1] = sbCommitment; input[2] = subsidyCommitment; input[3] = _newSubsidyCommitment; uint256 inputHash = sha256Hash(input); return inputHash; } function updateSubsidy( Poll _poll, uint256 _newSubsidyCommitment, uint256[8] memory _proof ) public onlyOwner votingPeriodOver(_poll) { // Require that all messages have been processed require( processingComplete, ERROR_PROCESSING_NOT_COMPLETE ); (uint8 intStateTreeDepth,,,uint8 voteOptionTreeDepth) = _poll.treeDepths(); uint256 subsidyBatchSize = 5 ** intStateTreeDepth; // treeArity is fixed to 5 (uint256 numSignUps,) = _poll.numSignUpsAndMessages(); uint256 numLeaves = numSignUps + 1; // Require that there are untalied ballots left require( rbi * subsidyBatchSize <= numLeaves, ERROR_ALL_SUBSIDY_CALCULATED ); require( cbi * subsidyBatchSize <= numLeaves, ERROR_ALL_SUBSIDY_CALCULATED ); bool isValid = verifySubsidyProof(_poll,_proof,numSignUps, _newSubsidyCommitment); require(isValid, ERROR_INVALID_SUBSIDY_PROOF); subsidyCommitment = _newSubsidyCommitment; increaseSubsidyIndex(subsidyBatchSize, numLeaves); } function increaseSubsidyIndex(uint256 batchSize, uint256 numLeaves) internal { if (cbi * batchSize + batchSize < numLeaves) { cbi++; } else { rbi++; cbi = 0; } } function verifySubsidyProof( Poll _poll, uint256[8] memory _proof, uint256 _numSignUps, uint256 _newSubsidyCommitment ) public view returns (bool) { (uint8 intStateTreeDepth,,,uint8 voteOptionTreeDepth) = _poll.treeDepths(); (VkRegistry vkRegistry, IMACI maci, ) = _poll.extContracts(); // Get the verifying key VerifyingKey memory vk = vkRegistry.getSubsidyVk( maci.stateTreeDepth(), intStateTreeDepth, voteOptionTreeDepth ); // Get the public inputs uint256 publicInputHash = genSubsidyPublicInputHash(_numSignUps, _newSubsidyCommitment); // Verify the proof return verifier.verify(_proof, vk, publicInputHash); } /* * Pack the batch start index and number of signups into a 100-bit value. */ function genTallyVotesPackedVals( uint256 _numSignUps, uint256 _batchStartIndex, uint256 _tallyBatchSize ) public pure returns (uint256) { // TODO: ensure that each value is less than or equal to 2 ** 50 uint256 result = (_batchStartIndex / _tallyBatchSize) + (_numSignUps << uint256(50)); return result; } function genTallyVotesPublicInputHash( uint256 _numSignUps, uint256 _batchStartIndex, uint256 _tallyBatchSize, uint256 _newTallyCommitment ) public view returns (uint256) { uint256 packedVals = genTallyVotesPackedVals( _numSignUps, _batchStartIndex, _tallyBatchSize ); uint256[] memory input = new uint256[](4); input[0] = packedVals; input[1] = sbCommitment; input[2] = tallyCommitment; input[3] = _newTallyCommitment; uint256 inputHash = sha256Hash(input); return inputHash; } function tallyVotes( Poll _poll, uint256 _newTallyCommitment, uint256[8] memory _proof ) public onlyOwner votingPeriodOver(_poll) { // Require that all messages have been processed require( processingComplete, ERROR_PROCESSING_NOT_COMPLETE ); ( , uint256 tallyBatchSize,) = _poll.batchSizes(); uint256 batchStartIndex = tallyBatchNum * tallyBatchSize; (uint256 numSignUps,) = _poll.numSignUpsAndMessages(); // Require that there are untalied ballots left require( batchStartIndex <= numSignUps, ERROR_ALL_BALLOTS_TALLIED ); bool isValid = verifyTallyProof( _poll, _proof, numSignUps, batchStartIndex, tallyBatchSize, _newTallyCommitment ); require(isValid, ERROR_INVALID_TALLY_VOTES_PROOF); // Update the tally commitment and the tally batch num tallyCommitment = _newTallyCommitment; tallyBatchNum ++; } /* * @notice Verify the tally proof using the verifiying key * @param _poll contract address of the poll proof to be verified * @param _proof the proof generated after processing all messages * @param _numSignUps number of signups for a given poll * @param _batchStartIndex the number of batches multiplied by the size of the batch * @param _tallyBatchSize batch size for the tally * @param _newTallyCommitment the tally commitment to be verified at a given batch index * @return valid a boolean representing successful verification */ function verifyTallyProof( Poll _poll, uint256[8] memory _proof, uint256 _numSignUps, uint256 _batchStartIndex, uint256 _tallyBatchSize, uint256 _newTallyCommitment ) public view returns (bool) { (uint8 intStateTreeDepth,,,uint8 voteOptionTreeDepth) = _poll.treeDepths(); (VkRegistry vkRegistry, IMACI maci, ) = _poll.extContracts(); // Get the verifying key VerifyingKey memory vk = vkRegistry.getTallyVk( maci.stateTreeDepth(), intStateTreeDepth, voteOptionTreeDepth ); // Get the public inputs uint256 publicInputHash = genTallyVotesPublicInputHash( _numSignUps, _batchStartIndex, _tallyBatchSize, _newTallyCommitment ); // Verify the proof return verifier.verify(_proof, vk, publicInputHash); } }
Verify the number of spent voice credits from the tally.json _totalSpent spent field retrieved in the totalSpentVoiceCredits object _totalSpentSalt the corresponding salt in the totalSpentVoiceCredit object return valid a boolean representing successful verification/
function verifySpentVoiceCredits( uint256 _totalSpent, uint256 _totalSpentSalt ) public view returns (bool) { uint256 ballotRoot = hashLeftRight(_totalSpent, _totalSpentSalt); return ballotRoot == emptyBallotRoots[treeDepths.voteOptionTreeDepth - 1]; }
1,814,246
pragma solidity ^0.5.9; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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; } } pragma experimental ABIEncoderV2; /** * @title Etherclear * @dev The Etherclear contract is meant to serve as a transition step for funds between a sender * and a recipient, where the sender can take the funds back if they cancel the payment, * and the recipient can only retrieve the funds in a specified amount of time, using * a passphrase communicated privately by the sender. * * The usage of the contract is as follows: * * 1) The sender generates a passphrase, and passes keccak256(passphrase,recipient_address) to the * contract, along with a hold time. This registers a payment ID (which must be unique), and * marks the start of the holding time window. * 2) The sender communicates this passphrase to the recipient over a secure channel. * 3) Before the holding time has passed, the recipient can send the passphrase to the contract to withdraw the funds. * 4) After the holding time has passed, the recipient is no longer able to withdraw the funds, regardless * of whether they have the passphrase or not. * * At any time, the sender can cancel the payment if they provide the payment ID, which * will initiate a transfer of funds back to the sender. * The sender is expected to cancel the payment if they have made a mistake in specifying * the recipient's address, the recipient does not claim the funds, or if the holding period has expired and the * funds need to be retrieved. * * TODO: Currently, the payment ID is a truncated version of the passphrase hash that is used to ensure knowledge of the * passphrase. They will be left as separate entities for now in case they need to be constructed differently. * * NOTE: the hold time functionality is not very secure for small time periods since it uses now (block.timestamp). It is meant to be an additional security measure, and should not be relied upon in the case of an attack. The current known tolerance is 900 seconds: * https://github.com/ethereum/wiki/blob/c02254611f218f43cbb07517ca8e5d00fd6d6d75/Block-Protocol-2.0.md * * Some parts are modified from https://github.com/forkdelta/smart_contract/blob/master/contracts/ForkDelta.sol */ /* * This is used as an interface to provide functionality when setting up the contract with ENS. */ contract ReverseRegistrar { function setName(string memory name) public returns (bytes32); } contract Etherclear { // TODO: think about adding a ERC223 fallback method. // NOTE: PaymentClosed has the same signature // because we want to look for payments // from the latest block backwards, and // we want to terminate the search for // past events as soon as possible when doing so. event PaymentOpened( uint txnId, uint holdTime, uint openTime, uint closeTime, address token, uint sendAmount, address indexed sender, address indexed recipient, bytes codeHash ); event PaymentClosed( uint txnId, uint holdTime, uint openTime, uint closeTime, address token, uint sendAmount, address indexed sender, address indexed recipient, bytes codeHash, uint state ); // A Payment starts in the OPEN state. // Once it is COMPLETED or CANCELLED, it cannot be changed further. enum PaymentState {OPEN, COMPLETED, CANCELLED} // Used when receiving signed messages to cancel or complete // a payment. enum CompletePaymentRequestType {CANCEL, RETRIEVE} // A Payment is created each time a sender wants to // send an amount to a recipient. struct Payment { // timestamps are in epoch seconds uint holdTime; uint paymentOpenTime; uint paymentCloseTime; // Token contract address, 0 is Ether. address token; uint sendAmount; address payable sender; address payable recipient; bytes codeHash; PaymentState state; } ReverseRegistrar reverseRegistrar; // EIP-712 code uses the examples provided at // https://medium.com/metamask/eip712-is-coming-what-to-expect-and-how-to-use-it-bb92fd1a7a26 // TODO: the salt and verifyingContract still need to be changed. // This struct and the associated typed signature are used for both // cancelling and retrieving payments. struct CompletePaymentRequest { uint txnId; address sender; address recipient; // Passphrase doesn't matter if the request ype is CANCEL. string passphrase; // CompletePaymentRequestType uint requestType; } // Payments are looked up with a uint UUID generated within the contract. mapping(uint => Payment) openPayments; // This contract's owner (gives ability to set fees). address payable public owner; // The fees are represented with a percentage times 1 ether. // The baseFee is to cover feeless retrieval // The paymentFee is to cover development costs uint public baseFee; uint public paymentFee; // mapping of token addresses to mapping of account balances (token=0 means Ether) mapping(address => mapping(address => uint)) public tokens; // NOTE: We do not lock the cancel payment functionality, so that users // will still be able to withdraw funds from payments they created. // Failsafe to lock the create payments functionality for both ether and tokens. bool public createPaymentEnabled; // Failsafe to lock the retrieval (withdraw) functionality. bool public retrieveFundsEnabled; address constant verifyingContract = 0x1C56346CD2A2Bf3202F771f50d3D14a367B48070; bytes32 constant salt = 0xf2d857f4a3edcb9b78b4d503bfe733db1e3f6cdc2b7971ee739626c97e86a558; string private constant COMPLETE_PAYMENT_REQUEST_TYPE = "CompletePaymentRequest(uint256 txnId,address sender,address recipient,string passphrase,uint256 requestType)"; string private constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"; bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256( abi.encodePacked(EIP712_DOMAIN_TYPE) ); bytes32 private constant COMPLETE_PAYMENT_REQUEST_TYPEHASH = keccak256( abi.encodePacked(COMPLETE_PAYMENT_REQUEST_TYPE) ); bytes32 private DOMAIN_SEPARATOR; // The chainId is public because it differs between // contract instances uint256 public chainId; function hashCompletePaymentRequest(CompletePaymentRequest memory request) private view returns (bytes32 hash) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( COMPLETE_PAYMENT_REQUEST_TYPEHASH, request.txnId, request.sender, request.recipient, keccak256(bytes(request.passphrase)), request.requestType ) ) ) ); } // Used to test the sign and recover functionality. function getSignerForPaymentCompleteRequest( uint256 txnId, address sender, address recipient, string memory passphrase, uint requestType, bytes32 sigR, bytes32 sigS, uint8 sigV ) public view returns (address result) { CompletePaymentRequest memory request = CompletePaymentRequest( txnId, sender, recipient, passphrase, requestType ); address signer = ecrecover( hashCompletePaymentRequest(request), sigV, sigR, sigS ); return signer; } constructor(uint256 _chainId) public { owner = msg.sender; baseFee = 0.001 ether; paymentFee = 0.005 ether; createPaymentEnabled = true; retrieveFundsEnabled = true; chainId = _chainId; DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256("Etherclear"), keccak256("1"), chainId, verifyingContract, salt ) ); } modifier onlyOwner { require( msg.sender == owner, "Only the contract owner is allowed to use this function." ); _; } /* * SetENS sets the name of the reverse record so that it points to this contract address. */ function setENS(address reverseRegistrarAddr, string memory name) public onlyOwner { reverseRegistrar = ReverseRegistrar(reverseRegistrarAddr); reverseRegistrar.setName(name); } function withdrawFees(address token) external onlyOwner { // The "owner" account is considered the fee account. uint total = tokens[token][owner]; tokens[token][owner] = 0; if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS owner.transfer(total); } else { require( IERC20(token).transfer(owner, total), "Could not successfully withdraw token" ); } } function viewBalance(address token, address user) external view returns (uint balance) { return tokens[token][user]; } // TODO: change this so that the fee can only be decreased // (once a suitable starting fee is reached). function changeBaseFee(uint newFee) external onlyOwner { baseFee = newFee; } function changePaymentFee(uint newFee) external onlyOwner { paymentFee = newFee; } function disableRetrieveFunds(bool disabled) public onlyOwner { retrieveFundsEnabled = !disabled; } function disableCreatePayment(bool disabled) public onlyOwner { createPaymentEnabled = !disabled; } function getPaymentInfo(uint paymentID) external view returns ( uint holdTime, uint paymentOpenTime, uint paymentCloseTime, address token, uint sendAmount, address sender, address recipient, bytes memory codeHash, uint state ) { Payment memory txn = openPayments[paymentID]; return ( txn.holdTime, txn.paymentOpenTime, txn.paymentCloseTime, txn.token, txn.sendAmount, txn.sender, txn.recipient, txn.codeHash, uint(txn.state) ); } function cancelPaymentAsSender(uint txnId) external { // Check txn sender and state. Payment memory txn = openPayments[txnId]; require( txn.sender == msg.sender, "Payment sender does not match message sender." ); require( txn.state == PaymentState.OPEN, "Payment must be open to cancel." ); cancelPayment(txnId); } // Cancels the payment and returns the funds to the payment's sender. // Assumes that checks have already been done on any external calls. function cancelPayment(uint txnId) private { // Check txn sender and state. Payment memory txn = openPayments[txnId]; // Update txn state. txn.paymentCloseTime = now; txn.state = PaymentState.CANCELLED; delete openPayments[txnId]; // Return funds to sender. if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS tokens[address(0)][txn.sender] = SafeMath.sub( tokens[address(0)][txn.sender], txn.sendAmount ); txn.sender.transfer(txn.sendAmount); } else { withdrawToken(txn.token, txn.sender, txn.sender, txn.sendAmount); } emit PaymentClosed( txnId, txn.holdTime, txn.paymentOpenTime, txn.paymentCloseTime, txn.token, txn.sendAmount, txn.sender, txn.recipient, txn.codeHash, uint(txn.state) ); } /** * This function handles deposits of ERC-20 tokens to the contract. * Does not allow Ether. * If token transfer fails, payment is reverted and remaining gas is refunded. * Additionally, includes a fee which must be accounted for when approving the amount. * Note: Remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf. * @param token Ethereum contract address of the token or 0 for Ether * @param originalAmount uint of the amount of the token the user wishes to deposit * @param feeAmount uint total amount of the fee charged by the contract */ // TODO: this doesn't follow checks-effects-interactions // https://solidity.readthedocs.io/en/develop/security-considerations.html?highlight=check%20effects#use-the-checks-effects-interactions-pattern function transferToken( address token, address user, uint originalAmount, uint feeAmount ) internal { require(token != address(0)); // TODO: use depositingTokenFlag in the ERC223 fallback function //depositingTokenFlag = true; require( IERC20(token).transferFrom( user, address(this), SafeMath.add(originalAmount, feeAmount) ) ); //depositingTokenFlag = false; tokens[token][user] = SafeMath.add( tokens[token][msg.sender], originalAmount ); tokens[token][owner] = SafeMath.add(tokens[token][owner], feeAmount); } // TODO: Make sure to check if amounts are available // We don't increment any balances because the funds are sent // outside of the contract. function withdrawToken( address token, address userFrom, address userTo, uint amount ) internal { require(token != address(0)); require(IERC20(token).transfer(userTo, amount)); tokens[token][userFrom] = SafeMath.sub(tokens[token][userFrom], amount); } /* This takes ether for the fee amount*/ // TODO check order of execution. function createPayment( uint amount, address payable recipient, uint holdTime, bytes calldata codeHash ) external payable { return createTokenPayment( address(0), amount, recipient, holdTime, codeHash ); } // Meant to be used for the approve() call, since the // amount in the ERC20 contract implementation will be // overwritten with the amount requested in the next approve(). // This returns the amount of the token that the // contract still holds. // TODO: ensure this value will be correct. function getBalance(address token) external view returns (uint amt) { return tokens[token][msg.sender]; } function getPaymentId(address recipient, bytes memory codeHash) public pure returns (uint result) { bytes memory txnIdBytes = abi.encodePacked( keccak256(abi.encodePacked(codeHash, recipient)) ); uint txnId = sliceUint(txnIdBytes); return txnId; } // Creates a new payment with the msg.sender as sender. // Expected to take a base fee in ETH. // Also takes a payment fee in either ETH or the token used, // this payment fee is calculated from the original amount. // We assume here that an approve() call has already been made for // the original amount + payment fee. function createTokenPayment( address token, uint amount, address payable recipient, uint holdTime, bytes memory codeHash ) public payable { // Check amount and fee, make sure to truncate fee. require( createPaymentEnabled, "The create payments functionality is currently disabled" ); uint paymentFeeTotal = uint( SafeMath.mul(paymentFee, amount) / (1 ether) ); if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS require( msg.value >= ( SafeMath.add(SafeMath.add(amount, baseFee), paymentFeeTotal) ), "Message value is not enough to cover amount and fees" ); } else { require( msg.value >= baseFee, "Message value is not enough to cover base fee" ); // We don't check for a minimum when taking the paymentFee here. Since we don't // care what the original sent amount was supposed to be, we just take a percentage and // subtract that from the sent amount. } // Check payment ID. // TODO: should other components be included in the hash? This isn't secure // if someone uses a bad codeHash. But they could mess up other components anyway, // unless a UUID was generated in the contract, which is expensive. uint txnId = getPaymentId(recipient, codeHash); // If txnId already exists, don't overwrite. require( openPayments[txnId].sender == address(0), "Payment ID must be unique. Use a different passphrase hash." ); // Create payments. Payment memory txn = Payment( holdTime, now, 0, token, amount, msg.sender, recipient, codeHash, PaymentState.OPEN ); openPayments[txnId] = txn; // Take fees; mark ether or token balances. if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS // Mark sender's ether balance with the sent amount tokens[address(0)][msg.sender] = SafeMath.add( tokens[address(0)][msg.sender], amount ); // Take baseFee and paymentFee (and any ether sent in the message) tokens[address(0)][owner] = SafeMath.add( tokens[address(0)][owner], SafeMath.sub(msg.value, amount) ); } else { // Take baseFee (and any ether sent in the message) tokens[address(0)][owner] = SafeMath.add( tokens[address(0)][owner], msg.value ); // Transfer tokens; mark sender's balance; take paymentFee transferToken(token, msg.sender, amount, paymentFeeTotal); } // TODO: is this the best step to emit events? emit PaymentOpened( txnId, txn.holdTime, txn.paymentOpenTime, txn.paymentCloseTime, txn.token, txn.sendAmount, txn.sender, txn.recipient, txn.codeHash ); } // Meant to be called by anyone, on behalf of the recipient // or sender of a payment, in order to retrieve funds or // cancel the payment, respectively. // Will only work if the correct signature is passed in. function completePaymentAsProxy( uint256 txnId, address sender, address recipient, string memory passphrase, uint requestType, bytes32 sigR, bytes32 sigS, uint8 sigV ) public { CompletePaymentRequest memory request = CompletePaymentRequest( txnId, sender, recipient, passphrase, requestType ); address signer = ecrecover( hashCompletePaymentRequest(request), sigV, sigR, sigS ); require( requestType == uint( CompletePaymentRequestType.CANCEL ) || requestType == uint(CompletePaymentRequestType.RETRIEVE), "requestType must be 0 (CANCEL) or 1 (RETRIEVE)" ); if (block.timestamp == uint(CompletePaymentRequestType.RETRIEVE)) { //injected CONTRACT AFFECTED BY MINERS require( recipient == signer, "The message recipient must be the same as the signer of the message" ); Payment memory txn = openPayments[txnId]; require( txn.recipient == recipient, "The payment's recipient must be the same as signer of the message" ); retrieveFunds(txn, txnId, passphrase); } else { require( sender == signer, "The message sender must be the same as the signer of the message" ); Payment memory txn = openPayments[txnId]; require( txn.sender == sender, "The payment's sender must be the same as signer of the message" ); cancelPayment(txnId); } } // Meant to be called by the recipient. function retrieveFundsAsRecipient(uint txnId, string memory code) public { Payment memory txn = openPayments[txnId]; // Check recipient require( txn.recipient == msg.sender, "Message sender must match payment recipient" ); retrieveFunds(txn, txnId, code); } // Sends funds to a payment recipient. // Internal ONLY, because it does not do any checks with msg.sender, // and leaves that for calling functions. // TODO: find a more secure way to implement the recipient check. function retrieveFunds(Payment memory txn, uint txnId, string memory code) private { require( retrieveFundsEnabled, "The retrieve funds functionality is currently disabled." ); require( txn.state == PaymentState.OPEN, "Payment must be open to retrieve funds" ); // TODO: make sure this is secure. bytes memory actualHash = abi.encodePacked( keccak256(abi.encodePacked(code, txn.recipient)) ); // Check codeHash require( sliceUint(actualHash) == sliceUint(txn.codeHash), "Passphrase is not correct" ); // Check holdTime require( (txn.paymentOpenTime + txn.holdTime) > now, "Hold time has already expired" ); // Update state. txn.paymentCloseTime = now; txn.state = PaymentState.COMPLETED; delete openPayments[txnId]; // Transfer either ether or tokens. if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS // Pay out retrieved funds based on payment amount // TODO: recipient must be valid! txn.recipient.transfer(txn.sendAmount); tokens[address(0)][txn.sender] = SafeMath.sub( tokens[address(0)][txn.sender], txn.sendAmount ); } else { withdrawToken(txn.token, txn.sender, txn.recipient, txn.sendAmount); } emit PaymentClosed( txnId, txn.holdTime, txn.paymentOpenTime, txn.paymentCloseTime, txn.token, txn.sendAmount, txn.sender, txn.recipient, txn.codeHash, uint(txn.state) ); } // Utility function to go from bytes -> uint // This is apparently not reversible. function sliceUint(bytes memory bs) public pure returns (uint) { uint start = 0; if (bs.length < start + 32) { return 0; } uint x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } }
The "owner" account is considered the fee account.
function withdrawFees(address token) external onlyOwner { uint total = tokens[token][owner]; tokens[token][owner] = 0; owner.transfer(total); require( IERC20(token).transfer(owner, total), "Could not successfully withdraw token" ); }
5,362,403
./full_match/5/0xc138a35532D9FC0558c01F0654719d7FD995736a/sources/src/ERC721MusicGame.sol
,-. `-' /|\ | ,----------. / \ |ERC721Drop| Caller `----+-----' | purchasePresale() | | ----------------------------------> | | | | _________________________________________________________________ ! ALT / drop has no tokens left for caller to mint? ! !_____/ | | ! ! | revert Mint_SoldOut() | ! ! | <---------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | | _________________________________________________________________ ! ALT / presale sale isn't active? | ! !_____/ | | ! ! | revert Presale_Inactive() | ! ! | <---------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | | _________________________________________________________________ ! ALT / merkle proof unapproved for caller? | ! !_____/ | | ! ! | revert Presale_MerkleNotApproved()| ! ! | <---------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | | _________________________________________________________________ ! ALT / inadequate funds sent? | ! !_____/ | | ! ! | revert Purchase_WrongPrice() | ! ! | <---------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | |----. | | | mint tokens | |<---' | | | |----. | | | emit IERC721Drop.Sale() | |<---' | | | return first minted token ID | | <---------------------------------- Caller ,----+-----. ,-. |ERC721Drop| `-' `----------' /|\ | / \ Merkle-tree based presale purchase function quantity quantity to purchase maxQuantity max quantity that can be purchased via merkle proof pricePerToken price that each token is purchased at merkleProof proof for presale mint address, uint256, uint256
function purchasePresale( uint256 quantity, uint256 maxQuantity, uint256 pricePerToken, bytes32[] calldata merkleProof ) external payable nonReentrant canMintTokens(quantity) onlyPresaleActive returns (uint256) { if ( !MerkleProof.verify( merkleProof, salesConfig.presaleMerkleRoot, keccak256( abi.encode(_msgSender(), maxQuantity, pricePerToken) ) ) ) { revert Presale_MerkleNotApproved(); } if (msg.value != pricePerToken * quantity) { revert Purchase_WrongPrice(pricePerToken * quantity); } presaleMintsByAddress[_msgSender()] += quantity; if (presaleMintsByAddress[_msgSender()] > maxQuantity) { revert Presale_TooManyForAddress(); } _mintNFTs(_msgSender(), quantity); uint256 firstMintedTokenId = _lastMintedTokenId() - quantity; emit IERC721Drop.Sale({ to: _msgSender(), quantity: quantity, pricePerToken: pricePerToken, firstPurchasedTokenId: firstMintedTokenId }); return firstMintedTokenId; }
1,929,378
./full_match/5/0x5C729aCd895EAa2b6A415219Af6FB49B2FF7f5C3/sources/contracts/XSender.sol
Sends the fund across chain. destinationDomain The destination domain ID. target Address of the Reciever contract on the destination domain. relayerFee The fee offered to relayers./ Include the relayerFee so Reciever will use the same fee Include the address of this contract so Reciever will know where to send the "callback"
function Fund( address target, uint32 destinationDomain, uint256 relayerFee ) external payable { require( msg.value == relayerFee, "Must send gas equal to the specified relayer fee" ); bytes memory callData = abi.encode(msgrecievedback, address(this), relayerFee); ); }
11,596,084
./full_match/7701/0x4e0b416439DEe7Dc3488Eb08b408390529763AD2/sources/MagnetErc721aBase.sol
to be called to ditribute contract revenues to all payees - only callable by owner
function releaseAll() public virtual onlyOwner { for(uint256 i = 0 ; i < _teamLength ; i++) { address account_ = payee(i); uint256 payment_ = releasable(account_); if(payment_ > 0) { super.release(payable(account_)); } } }
13,215,327
/** *Submitted for verification at Etherscan.io on 2021-12-13 */ pragma solidity >=0.7.0 <0.9.0; library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } contract ZOS { using SafeMath for uint; string public constant name = 'Zeus Operating System Initial Dex Offering'; string public constant symbol = 'ZOSIDO'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; address public owner; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { owner = msg.sender; uint _totalSupply = 30000000 * 1000000000000000000; _mint(msg.sender, _totalSupply); } function burn(uint256 _value) external returns (bool success) { _burn(msg.sender, _value); return true; } function mint(uint256 _value) external returns (bool success) { require(owner == msg.sender,"owner error"); _mint(msg.sender, _value); return true; } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { //require(balanceOf[from] >= value,"_transfer error"); balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { //require(allowance[from][msg.sender] >= value,"transferFrom error"); allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); _transfer(from, to, value); return true; } }
require(allowance[from][msg.sender] >= value,"transferFrom error");
function transferFrom(address from, address to, uint value) external returns (bool) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); _transfer(from, to, value); return true; }
8,000,812
/** *Submitted for verification at Etherscan.io on 2021-03-21 */ pragma solidity ^0.6.0; // SPDX-License-Identifier: UNLICENSED /** * @title SafeMath * @dev Math operations with safety checks that throw on error * */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() public virtual view returns (uint); function balanceOf(address tokenOwner) public virtual view returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining); function transfer(address to, uint256 tokens) public virtual returns (bool success); function approve(address spender, uint256 tokens) public virtual returns (bool success); function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } contract HedgeHog is ERC20Interface, Owned { using SafeMath for uint256; string public symbol = "HHOG"; string public name = "HedgeHog"; uint256 public decimals = 18; uint256 _totalSupply = 1e9 * 10 ** (decimals); // 1,000,000,000 mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor (address owner) public { owner = 0x5E220057920Dcc7826AB5e5EB5Cf4Bb41C6CD902; balances[address(owner)] = 1000000000 * 10 ** (18); // 1,000,000,000 emit Transfer(address(0), address(owner), 1000000000 * 10 ** (18)); } /** ERC20Interface function's implementation **/ function totalSupply() public override view returns (uint256){ return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public override returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender,spender,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 (uint256 remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[msg.sender] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[msg.sender] = balances[msg.sender].sub(tokens); uint256 deduction = deductionsToApply(tokens); applyDeductions(deduction); balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(msg.sender, to, tokens.sub(deduction)); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); uint256 deduction = deductionsToApply(tokens); applyDeductions(deduction); balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(from, to, tokens.sub(tokens)); return true; } function _transfer(address to, uint256 tokens, bool rewards) internal returns(bool){ // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[address(this)] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[address(this)] = balances[address(this)].sub(tokens); uint256 deduction = 0; if(!rewards){ deduction = deductionsToApply(tokens); applyDeductions(deduction); } balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(address(this),to,tokens.sub(deduction)); return true; } function deductionsToApply(uint256 tokens) private view returns(uint256){ uint256 deduction = 0; uint256 minSupply = 100000 * 10 ** (18); if(_totalSupply > minSupply){ deduction = onePercent(tokens).mul(5); // 5% transaction cost if(_totalSupply.sub(deduction) < minSupply) deduction = _totalSupply.sub(minSupply); } return deduction; } function applyDeductions(uint256 deduction) private{ if(stakedCoins == 0){ burnTokens(deduction); } else{ burnTokens(deduction.div(2)); disburse(deduction.div(2)); } } // ------------------------------------------------------------------------ // Burn the ``value` amount of tokens from the `account` // ------------------------------------------------------------------------ function burnTokens(uint256 value) internal{ require(_totalSupply >= value); // burn only unsold tokens _totalSupply = _totalSupply.sub(value); emit Transfer(msg.sender, address(0), value); } // ------------------------------------------------------------------------ // Calculates onePercent of the uint256 amount sent // ------------------------------------------------------------------------ function onePercent(uint256 _tokens) internal pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; } /********************************STAKING CONTRACT**********************************/ uint256 deployTime; uint256 private totalDividentPoints; uint256 private unclaimedDividendPoints; uint256 pointMultiplier = 1000000000000000000; uint256 public stakedCoins; uint256 public totalStakes; uint256 public totalRewardsClaimed; bool public stakingOpen; struct Account { uint256 balance; uint256 lastDividentPoints; uint256 timeInvest; uint256 lastClaimed; uint256 rewardsClaimed; uint256 pending; } mapping(address => Account) accounts; function openStaking() external onlyOwner{ require(!stakingOpen, "staking already open"); stakingOpen = true; } function STAKE(uint256 _tokens) external returns(bool){ require(stakingOpen, "staking is close"); require(transfer(address(this), _tokens), "In sufficient tokens in user wallet"); uint256 owing = dividendsOwing(msg.sender); if(owing > 0) // early stakes accounts[msg.sender].pending = owing; uint256 deduction = deductionsToApply(_tokens); stakedCoins = stakedCoins.add(_tokens.sub(deduction)); accounts[msg.sender].balance = accounts[msg.sender].balance.add(_tokens.sub(deduction)); accounts[msg.sender].lastDividentPoints = totalDividentPoints; accounts[msg.sender].timeInvest = now; accounts[msg.sender].lastClaimed = now; totalStakes = totalStakes.add(_tokens.sub(deduction)); return true; } function pendingReward(address _user) external view returns(uint256){ uint256 owing = dividendsOwing(_user); return owing; } function dividendsOwing(address investor) internal view returns (uint256){ uint256 newDividendPoints = totalDividentPoints.sub(accounts[investor].lastDividentPoints); return (((accounts[investor].balance).mul(newDividendPoints)).div(pointMultiplier)).add(accounts[investor].pending); } function updateDividend(address investor) internal returns(uint256){ uint256 owing = dividendsOwing(investor); if (owing > 0){ unclaimedDividendPoints = unclaimedDividendPoints.sub(owing); accounts[investor].lastDividentPoints = totalDividentPoints; } return owing; } function activeStake(address _user) external view returns (uint256){ return accounts[_user].balance; } function UNSTAKE() external returns (bool){ require(accounts[msg.sender].balance > 0); uint256 owing = updateDividend(msg.sender); if(owing > 0) // unclaimed reward accounts[msg.sender].pending = owing; stakedCoins = stakedCoins.sub(accounts[msg.sender].balance); require(_transfer(msg.sender, accounts[msg.sender].balance, false)); accounts[msg.sender].balance = 0; return true; } function disburse(uint256 amount) internal{ balances[address(this)] = balances[address(this)].add(amount); uint256 unnormalized = amount.mul(pointMultiplier); totalDividentPoints = totalDividentPoints.add(unnormalized.div(stakedCoins)); unclaimedDividendPoints = unclaimedDividendPoints.add(amount); } function claimReward() external returns(bool){ uint256 owing = updateDividend(msg.sender); require(owing > 0); require(_transfer(msg.sender, owing, true)); accounts[msg.sender].rewardsClaimed = accounts[msg.sender].rewardsClaimed.add(owing); totalRewardsClaimed = totalRewardsClaimed.add(owing); return true; } function rewardsClaimed(address _user) external view returns(uint256 rewardClaimed){ return accounts[_user].rewardsClaimed; } }
------------------------------------------------------------------------ Get the token balance for account `tokenOwner` ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public override view returns (uint256 balance) { return balances[tokenOwner]; }
2,002,024
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/Address.sol"; import "../TokenPaymaster.sol"; import "./ProxyFactory.sol"; contract ProxyDeployingPaymaster is TokenPaymaster { using Address for address; string public override versionPaymaster = "2.2.3+opengsn.proxydeploying.ipaymaster"; ProxyFactory public proxyFactory; constructor(IUniswap[] memory _uniswaps, ProxyFactory _proxyFactory) TokenPaymaster(_uniswaps) { proxyFactory = _proxyFactory; } function getPayer(GsnTypes.RelayRequest calldata relayRequest) public override virtual view returns (address) { // TODO: if (rr.paymasterData != '') return address(rr.paymasterData) // this is to support pre-existing proxies/proxies with changed owner return proxyFactory.calculateAddress(relayRequest.request.from); } /** * @notice unlike the default implementation we need to allow destination address to have no code deployed yet */ function _verifyForwarder(GsnTypes.RelayRequest calldata relayRequest) internal virtual override view { require(getTrustedForwarder() == relayRequest.relayData.forwarder, "Forwarder is not trusted"); if (relayRequest.request.to.isContract()){ GsnEip712Library.verifyForwarderTrusted(relayRequest); } } function _verifyPaymasterData(GsnTypes.RelayRequest calldata relayRequest) internal virtual override view { // solhint-disable-next-line reason-string require(relayRequest.relayData.paymasterData.length == 32, "paymasterData: invalid length for Uniswap v1 exchange address"); } // solhint-disable-next-line no-empty-blocks function _verifyValue(GsnTypes.RelayRequest calldata relayRequest) internal virtual override view {} function _preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) internal override virtual returns (bytes memory, bool revertOnRecipientRevert) { (signature, approvalData); (IERC20 token, IUniswap uniswap) = _getToken(relayRequest.relayData.paymasterData); (address payer, uint256 tokenPrecharge) = _calculatePreCharge(token, uniswap, relayRequest, maxPossibleGas); if (!payer.isContract()) { deployProxy(relayRequest.request.from); } token.transferFrom(payer, address(this), tokenPrecharge); //solhint-disable-next-line uniswap.tokenToEthSwapOutput(relayRequest.request.value, type(uint256).max, block.timestamp + 60 * 15); payable(relayRequest.relayData.forwarder).transfer(relayRequest.request.value); return (abi.encode(payer, relayRequest.request.from, tokenPrecharge, relayRequest.request.value, relayRequest.relayData.forwarder, token, uniswap), false); } function deployProxy(address owner) public returns (ProxyIdentity) { ProxyIdentity proxy = proxyFactory.deployProxy(owner); proxy.initialize(address(getTrustedForwarder()), tokens); return proxy; } function _postRelayedCall( bytes calldata context, bool, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) internal override virtual { (address payer,, uint256 tokenPrecharge, uint256 valueRequested,,IERC20 token, IUniswap uniswap) = abi.decode(context, (address, address, uint256, uint256, address, IERC20, IUniswap)); _postRelayedCallInternal(payer, tokenPrecharge, valueRequested, gasUseWithoutPost, relayData, token, uniswap); } // TODO: calculate precise values for these params uint256 constant private PRE_RELAYED_CALL_GAS_LIMIT_OVERRIDE = 2000000; uint256 constant public PAYMASTER_ACCEPTANCE_BUDGET_OVERRIDE = PRE_RELAYED_CALL_GAS_LIMIT_OVERRIDE + FORWARDER_HUB_OVERHEAD; function getGasAndDataLimits() public override pure returns ( GasAndDataLimits memory limits ) { return GasAndDataLimits( PAYMASTER_ACCEPTANCE_BUDGET_OVERRIDE, PRE_RELAYED_CALL_GAS_LIMIT_OVERRIDE, POST_RELAYED_CALL_GAS_LIMIT, CALLDATA_SIZE_LIMIT ); } }
solhint-disable-next-line no-empty-blocks
function _verifyValue(GsnTypes.RelayRequest calldata relayRequest) internal virtual override view {}
6,364,522
pragma solidity ^0.5.0; import "./Submarine.sol"; /** * The TestCase contract to test Submarine queries. * * MIT License * * Copyright (c) 2019 Alessandro Ricottone * * 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. */ contract TestCase { Submarine public submarine; uint[] public result; address public owner; // Permits modifications only by the owner of the contract. modifier only_owner() { require(msg.sender == owner, "Only contract owner can call this function."); _; } // Permits modifications only by the submarine contract. modifier from_submarine() { require(msg.sender == address(submarine), "Only submarine contract can call this function."); _; } /** * @dev Constructs a new theGraphsubmarine contract. */ constructor(address _submarineAddress) public { submarine = Submarine(_submarineAddress); owner = msg.sender; } /** * @dev Updates the theGraphsubmarine contract. * @param _newsubmarine The new submarine address. */ function updatesubmarine(address _newsubmarine) only_owner public { submarine = Submarine(_newsubmarine); } /** * @dev Creates a query. */ function queryAgentAt(address _agentAddress, string memory _command, bytes memory _oceanDid) public { bytes4 _callback = bytes4(keccak256("resultCallback(uint256[])")); submarine.createQuery (_agentAddress, _command, _oceanDid, _callback); } /** * @dev Callback function passed to the submarine. * @param _result The result of the query. */ function resultCallback(uint256[] calldata _result) from_submarine external { require(_result.length == 5, "This function requires a length 5 array."); result = _result; } }
Updates the theGraphsubmarine contract. _newsubmarine The new submarine address./
function updatesubmarine(address _newsubmarine) only_owner public { submarine = Submarine(_newsubmarine); }
12,776,047
// SPDX-License-Identifier: MIT /** °° °° °° °°° ######### ### ####### ######. °°°° °° °° °° °° ## ## ## ## ## ## °° °° °° °° °° °° ## ## ## ####### #### °°°°°°°° °° °° °° °° ## ## #### ## ## ## ## °° °° °° °° °° °° ## ## ## ## ## . # °° °° °°° °°° ## ## ## ## ## ###### */ pragma solidity ^0.8.7; import 'erc721a/contracts/ERC721A.sol'; import '@openzeppelin/contracts/utils/introspection/IERC165.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; contract AVOTARS is ERC721A, Ownable, ReentrancyGuard { using Strings for uint256; bytes32 public merkleRoot; mapping(address => bool) public whitelisted; string public baseURI = "ipfs://QmQzHtuMZxLJiFdALzxXrEtypwG5q7sj4ADb8UGY4xx3zm/"; uint256 public price; uint256 public maxAmountForAddress; uint256 public maxSupply = 10; bool public paused = false; bool public revealed = false; bool public whitelistMintEnabled = false; constructor() ERC721A("AVOTAR", "AVT") {} // imposta prezzo function setPrice (uint256 _price) public onlyOwner { price = _price; } function setMaxAmounthForAddress (uint256 _maxAmountForAddress) public onlyOwner { maxAmountForAddress = _maxAmountForAddress; } // un tipo di funzione che controlla prima se la quantità data in input rispetta i limiti imposti // questa funzione verà richiamata nelle funzioni di mint modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxAmountForAddress, "Invalid mint amount!"); require(totalSupply() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } // un tipo di funzione che verifica se i fonfi presenti nel wallet sono suficienti per acquistare la quantità scelta di nft // questa funzione verà richiamata nelle funzioni di mint modifier mintPriceAVOTAR(uint256 _mintAmount) { require(msg.value >= price * _mintAmount, "Insufficient funds!"); _; } // la funzione permette di mintare solo a chi è nella WL function whitelistMint(uint256 _mintAmount, bytes32[] calldata _merkleProof) public payable mintCompliance(_mintAmount) mintPriceAVOTAR(_mintAmount) { require(!paused, "The contract is paused!"); require(whitelistMintEnabled, "The whitelist sale is not enabled!"); require(!whitelisted[_msgSender()], "Address already claimed!"); bytes32 leaf = keccak256(abi.encodePacked(_msgSender())); require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid proof!"); whitelisted[_msgSender()] = true; // il mitente è nella WL _safeMint(_msgSender(), _mintAmount); // viene salvata la quantità del mint } // la funzione è riservata al mint publico function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) mintPriceAVOTAR(_mintAmount) { require(!paused, "The contract is paused!"); _safeMint(_msgSender(), _mintAmount); } //ONLY OWNER // la funzione è riservata per il mint del proprietario function Owner_mint(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _safeMint(_receiver, _mintAmount); } // imposta l'uri dei metadata nascosti function _baseURI() internal view override returns (string memory) { return baseURI; } // una volta clicato reveal gli nft vengono rivelati e non è possibile nasconderli più function reveal(bool _revealed) public onlyOwner { revealed = _revealed; } function changeBaseURI(string memory changeURI) public onlyOwner { baseURI = changeURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory changeURI = _baseURI(); if (revealed) { return bytes(changeURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; } else { return string(abi.encodePacked(changeURI, ".json")); } } // imposta lo stato del contratto se è in pausa allora paused = true e viceversa function setPaused(bool _state) public onlyOwner { paused = _state; } // imposta la radice dell'albero di Markle contenente gli hash degli address di collloro che sono nella WL function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } // imposta lo stato del mint per chi è nella WL abile = true e viceversa function setWhitelistMintEnabled(bool _state) public onlyOwner { whitelistMintEnabled = _state; } // tipica funzione di ERC721A che verifica il balance del address dato in output // alla variabile ownerTokenCount viene attribuito il valore del balans del address dato in input // viene memorizzata la quantità dei token con il loro id presenti nel balanc del address dato in input function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = _startTokenId(); uint256 ownedTokenIndex = 0; address latestOwnerAddress; // mentre vengono rispettate le condizioni vengono memorizzati i correnti token id while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { TokenOwnership memory ownership = _ownerships[currentTokenId]; // se la proprieta viene bruciata e l'address del proprietario è diverso da 0 // allora il valore dell'address del proprietario che ha brucciato viene passato alla variabile dell'address più recente del proprietario if (!ownership.burned && ownership.addr != address(0)) { latestOwnerAddress = ownership.addr; } // se l'address più recente del proprietari è = all'address del proprietario // allora l'id e il suo index viene passato alla variabile currentTokenId if (latestOwnerAddress == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } // il token id parte da 1 e non da 0 function _startTokenId() internal view virtual override returns (uint256) { return 1; } }
tipica funzione di ERC721A che verifica il balance del address dato in output alla variabile ownerTokenCount viene attribuito il valore del balans del address dato in input viene memorizzata la quantità dei token con il loro id presenti nel balanc del address dato in input mentre vengono rispettate le condizioni vengono memorizzati i correnti token id se la proprieta viene bruciata e l'address del proprietario è diverso da 0 allora il valore dell'address del proprietario che ha brucciato viene passato alla variabile dell'address più recente del proprietario se l'address più recente del proprietari è = all'address del proprietario allora l'id e il suo index viene passato alla variabile currentTokenId
function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = _startTokenId(); uint256 ownedTokenIndex = 0; address latestOwnerAddress; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { TokenOwnership memory ownership = _ownerships[currentTokenId]; if (!ownership.burned && ownership.addr != address(0)) { latestOwnerAddress = ownership.addr; } if (latestOwnerAddress == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; }
986,687
./full_match/1/0x46b13E7E8f1aEF156973AE3eD975E738cAFB08C8/sources/contracts/Pool.sol
Remove a debt token from the per-account list This function is called from `DebtToken` when user's balance changes to `0` The caller should ensure to not pass `address(0)` as `_account` account_ The account address/
function removeFromDebtTokensOfAccount(address account_) external onlyIfMsgSenderIsDebtToken { require(debtTokensOfAccount.remove(account_, msg.sender), "debt-token-doesnt-exist"); }
3,134,059
./partial_match/1/0x1da8E62726A18d3a563AF8c10fC44416A89E9BAc/sources/PaymentProcessor.sol
secureTokenPay can be used by client if he wants to securely set client address for token refund together with token payment. This call requires that token's approve method has been called prior to this. _orderId Identifier of the order/
function secureTokenPay(uint _orderId) external whenNotPaused atState(_orderId, State.Created) transition(_orderId, State.Paid) { Order storage order = orders[_orderId]; require(msg.sender == order.paymentAcceptor); require(order.tokenAddress != address(0)); GenericERC20(order.tokenAddress).transferFrom(msg.sender, address(this), order.price); }
3,724,662
./partial_match/8453/0x4E31fEF74b3823Ad89923fD315F4bc122D0f03cc/sources/Pool.sol
/ calculates the gross interest handling impermanent loss case this condition is added because emit is to only be emitted when adminFeeSet flag is false but this mehtod is called for every player withdrawal in variable deposit pool.
function _calculateAndUpdateGameAccounting( uint256 _totalBalance, uint256[] memory _grossRewardTokenAmount ) internal returns (uint256) { uint256 _grossInterest = 0; if (_totalBalance >= netTotalGamePrincipal) { _grossInterest = _totalBalance - netTotalGamePrincipal; impermanentLossShare = (_totalBalance * 100) / netTotalGamePrincipal; netTotalGamePrincipal = _totalBalance; } if (_incentiveToken != address(0)) { try IERC20(_incentiveToken).balanceOf(address(this)) returns (uint256 _totalIncentiveAmount) { totalIncentiveAmount = _totalIncentiveAmount; emit ExternalTokenGetBalanceError(_incentiveToken, reason); } } if (!adminFeeSet) { winnersLeftToWithdraw = winnerCount; emit EndGameStats( msg.sender, _totalBalance, totalGamePrincipal, netTotalGamePrincipal, _grossInterest, _grossRewardTokenAmount, totalIncentiveAmount, impermanentLossShare ); } return _grossInterest; } Calculates and set's admin accounting called by methods _setGlobalPoolParams. Updates the admin fee storage var used for admin fee. @param _grossInterest Gross interest amount. @param _grossRewardTokenAmount Gross reward amount array.
16,777,511
pragma solidity 0.5.4; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = 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; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Contract for Rewards Token * Copyright 2018, Rewards Blockchain Systems (Rewards.com) */ contract RewardsToken is Ownable { using SafeMath for uint; string public constant symbol = 'RWRD'; string public constant name = 'Rewards Cash'; uint8 public constant decimals = 18; uint256 public constant hardCap = 5 * (10 ** (18 + 8)); //500MM tokens. Max amount of tokens which can be minte10 uint256 public totalSupply; bool public mintingFinished = false; bool public frozen = true; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) internal allowed; event NewToken(address indexed _token); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burned(address indexed _burner, uint _burnedAmount); event Revoke(address indexed _from, uint256 _value); event MintFinished(); event MintStarted(); event Freeze(); event Unfreeze(); modifier canMint() { require(!mintingFinished, "Minting was already finished"); _; } modifier canTransfer() { require(msg.sender == owner || !frozen, "Tokens could not be transferred"); _; } constructor () public { emit NewToken(address(this)); } /** * @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 onlyOwner canMint returns (bool) { require(_to != address(0), "Address should not be zero"); require(totalSupply.add(_amount) <= hardCap); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_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 returns (bool) { require(!mintingFinished); mintingFinished = true; emit MintFinished(); return true; } /** * @dev Function to start minging new tokens. * @return True if the operation was successful */ function startMinting() public onlyOwner returns (bool) { require(mintingFinished); mintingFinished = false; emit MintStarted(); return true; } /** * @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 canTransfer returns (bool) { require(_to != address(0), "Address should not be zero"); require(_value <= balances[msg.sender], "Insufficient balance"); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender] - _value; balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @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 canTransfer returns (bool) { require(_to != address(0), "Address should not be zero"); require(_value <= balances[_from], "Insufficient Balance"); require(_value <= allowed[_from][msg.sender], "Insufficient Allowance"); balances[_from] = balances[_from] - _value; balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender] - _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 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); 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) * @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 success) { 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; } /** * @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]; } /** * @dev Burn tokens from an address * @param _burnAmount The amount of tokens to burn */ function burn(uint _burnAmount) public { require(_burnAmount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_burnAmount); totalSupply = totalSupply.sub(_burnAmount); emit Burned(msg.sender, _burnAmount); } /** * @dev Revokes minted tokens * @param _from The address whose tokens are revoked * @param _value The amount of token to revoke */ function revoke(address _from, uint256 _value) public onlyOwner returns (bool) { require(_value <= balances[_from]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_from] = balances[_from].sub(_value); totalSupply = totalSupply.sub(_value); emit Revoke(_from, _value); emit Transfer(_from, address(0), _value); return true; } /** * @dev Freeze tokens */ function freeze() public onlyOwner { require(!frozen); frozen = true; emit Freeze(); } /** * @dev Unfreeze tokens */ function unfreeze() public onlyOwner { require(frozen); frozen = false; emit Unfreeze(); } } /** * @title Contract that will hold vested tokens; * @notice Tokens for vested contributors will be hold in this contract and token holders * will claim their tokens according to their own vesting timelines. * Copyright 2018, Rewards Blockchain Systems (Rewards.com) */ contract VestingVault is Ownable { using SafeMath for uint256; struct Grant { uint value; uint vestingStart; uint vestingCliff; uint vestingDuration; uint[] scheduleTimes; uint[] scheduleValues; uint level; // 1: frequency, 2: schedules uint transferred; } RewardsToken public token; mapping(address => Grant) public grants; uint public totalVestedTokens; // array of vested users addresses address[] public vestedAddresses; bool public locked; event NewGrant (address _to, uint _amount, uint _start, uint _duration, uint _cliff, uint[] _scheduleTimes, uint[] _scheduleAmounts, uint _level); event NewRelease(address _holder, uint _amount); event WithdrawAll(uint _amount); event BurnTokens(uint _amount); event LockedVault(); modifier isOpen() { require(locked == false, "Vault is already locked"); _; } constructor (RewardsToken _token) public { require(address(_token) != address(0), "Token address should not be zero"); token = _token; locked = false; } /** * @return address[] that represents vested addresses; */ function returnVestedAddresses() public view returns (address[] memory) { return vestedAddresses; } /** * @return grant that represents vested info for specific user; */ function returnGrantInfo(address _user) public view returns (uint, uint, uint, uint, uint[] memory, uint[] memory, uint, uint) { require(_user != address(0), "Address should not be zero"); Grant storage grant = grants[_user]; return (grant.value, grant.vestingStart, grant.vestingCliff, grant.vestingDuration, grant.scheduleTimes, grant.scheduleValues, grant.level, grant.transferred); } /** * @dev Add vested contributor information * @param _to Withdraw address that tokens will be sent * @param _value Amount to hold during vesting period * @param _start Unix epoch time that vesting starts from * @param _duration Seconds amount of vesting duration * @param _cliff Seconds amount of vesting cliffHi * @param _scheduleTimes Array of Unix epoch times for vesting schedules * @param _scheduleValues Array of Amount for vesting schedules * @param _level Indicator that will represent types of vesting * @return Int value that represents granted token amount */ function grant( address _to, uint _value, uint _start, uint _duration, uint _cliff, uint[] memory _scheduleTimes, uint[] memory _scheduleValues, uint _level) public onlyOwner isOpen returns (uint256) { require(_to != address(0), "Address should not be zero"); require(_level == 1 || _level == 2, "Invalid vesting level"); // make sure a single address can be granted tokens only once. require(grants[_to].value == 0, "Already added to vesting vault"); if (_level == 2) { require(_scheduleTimes.length == _scheduleValues.length, "Schedule Times and Values should be matched"); _value = 0; for (uint i = 0; i < _scheduleTimes.length; i++) { require(_scheduleTimes[i] > 0, "Seconds Amount of ScheduleTime should be greater than zero"); require(_scheduleValues[i] > 0, "Amount of ScheduleValue should be greater than zero"); if (i > 0) { require(_scheduleTimes[i] > _scheduleTimes[i - 1], "ScheduleTimes should be sorted by ASC"); } _value = _value.add(_scheduleValues[i]); } } require(_value > 0, "Vested amount should be greater than zero"); grants[_to] = Grant({ value : _value, vestingStart : _start, vestingDuration : _duration, vestingCliff : _cliff, scheduleTimes : _scheduleTimes, scheduleValues : _scheduleValues, level : _level, transferred : 0 }); vestedAddresses.push(_to); totalVestedTokens = totalVestedTokens.add(_value); emit NewGrant(_to, _value, _start, _duration, _cliff, _scheduleTimes, _scheduleValues, _level); return _value; } /** * @dev Get token amount for a token holder available to transfer at specific time * @param _holder Address that represents holder's withdraw address * @param _time Unix epoch time at the moment * @return Int value that represents token amount that is available to release at the moment */ function transferableTokens(address _holder, uint256 _time) public view returns (uint256) { Grant storage grantInfo = grants[_holder]; if (grantInfo.value == 0) { return 0; } return calculateTransferableTokens(grantInfo, _time); } /** * @dev Internal function to calculate available amount at specific time * @param _grant Grant that represents holder's vesting info * @param _time Unix epoch time at the moment * @return Int value that represents available vested token amount */ function calculateTransferableTokens(Grant memory _grant, uint256 _time) private pure returns (uint256) { uint totalVestedAmount = _grant.value; uint totalAvailableVestedAmount = 0; if (_grant.level == 1) { if (_time < _grant.vestingCliff.add(_grant.vestingStart)) { return 0; } else if (_time >= _grant.vestingStart.add(_grant.vestingDuration)) { return _grant.value; } else { totalAvailableVestedAmount = totalVestedAmount.mul(_time.sub(_grant.vestingStart)).div(_grant.vestingDuration); } } else { if (_time < _grant.scheduleTimes[0]) { return 0; } else if (_time >= _grant.scheduleTimes[_grant.scheduleTimes.length - 1]) { return _grant.value; } else { for (uint i = 0; i < _grant.scheduleTimes.length; i++) { if (_grant.scheduleTimes[i] <= _time) { totalAvailableVestedAmount = totalAvailableVestedAmount.add(_grant.scheduleValues[i]); } else { break; } } } } return totalAvailableVestedAmount; } /** * @dev Claim vested token * @notice this will be eligible after vesting start + cliff or schedule times */ function claim() public { address beneficiary = msg.sender; Grant storage grantInfo = grants[beneficiary]; require(grantInfo.value > 0, "Grant does not exist"); uint256 vested = calculateTransferableTokens(grantInfo, now); require(vested > 0, "There is no vested tokens"); uint256 transferable = vested.sub(grantInfo.transferred); require(transferable > 0, "There is no remaining balance for this address"); require(token.balanceOf(address(this)) >= transferable, "Contract Balance is insufficient"); grantInfo.transferred = grantInfo.transferred.add(transferable); totalVestedTokens = totalVestedTokens.sub(transferable); token.transfer(beneficiary, transferable); emit NewRelease(beneficiary, transferable); } /** * @dev Function to revoke tokens from an address */ function revokeTokens(address _from, uint _amount) public onlyOwner { // finally transfer all remaining tokens to owner Grant storage grantInfo = grants[_from]; require(grantInfo.value > 0, "Grant does not exist"); uint256 revocable = grantInfo.value.sub(grantInfo.transferred); require(revocable > 0, "There is no remaining balance for this address"); require(revocable >= _amount, "Revocable balance is insufficient"); require(token.balanceOf(address(this)) >= _amount, "Contract Balance is insufficient"); grantInfo.value = grantInfo.value.sub(_amount); totalVestedTokens = totalVestedTokens.sub(_amount); token.burn(_amount); emit BurnTokens(_amount); } /** * @dev Function to burn remaining tokens */ function burnRemainingTokens() public onlyOwner { // finally burn all remaining tokens to owner uint amount = token.balanceOf(address(this)); token.burn(amount); emit BurnTokens(amount); } /** * @dev Function to withdraw remaining tokens; */ function withdraw() public onlyOwner { // finally withdraw all remaining tokens to owner uint amount = token.balanceOf(address(this)); token.transfer(owner, amount); emit WithdrawAll(amount); } /** * @dev Function to lock vault not to be able to alloc more */ function lockVault() public onlyOwner { // finally lock vault require(!locked); locked = true; emit LockedVault(); } } /** * @title Contract for distribution of tokens * Copyright 2018, Rewards Blockchain Systems (Rewards.com) */ contract RewardsTokenDistribution is Ownable { using SafeMath for uint256; RewardsToken public token; VestingVault public vestingVault; bool public finished; event TokenMinted(address indexed _to, uint _value, string _id); event RevokeTokens(address indexed _from, uint _value); event MintingFinished(); modifier isAllowed() { require(finished == false, "Minting was already finished"); _; } /** * @dev Constructor * @param _token Contract address of RewardsToken * @param _vestingVault Contract address of VestingVault */ constructor ( RewardsToken _token, VestingVault _vestingVault ) public { require(address(_token) != address(0), "Address should not be zero"); require(address(_vestingVault) != address(0), "Address should not be zero"); token = _token; vestingVault = _vestingVault; finished = false; } /** * @dev Function to allocate tokens for normal contributor * @param _to Address of a contributor * @param _value Value that represents tokens amount allocated for a contributor */ function allocNormalUser(address _to, uint _value) public onlyOwner isAllowed { token.mint(_to, _value); emit TokenMinted(_to, _value, "Allocated Tokens To User"); } /** * @dev Function to allocate tokens for vested contributor * @param _to Withdraw address that tokens will be sent * @param _value Amount to hold during vesting period * @param _start Unix epoch time that vesting starts from * @param _duration Seconds amount of vesting duration * @param _cliff Seconds amount of vesting cliff * @param _scheduleTimes Array of Unix epoch times for vesting schedules * @param _scheduleValues Array of Amount for vesting schedules * @param _level Indicator that will represent types of vesting */ function allocVestedUser( address _to, uint _value, uint _start, uint _duration, uint _cliff, uint[] memory _scheduleTimes, uint[] memory _scheduleValues, uint _level) public onlyOwner isAllowed { _value = vestingVault.grant(_to, _value, _start, _duration, _cliff, _scheduleTimes, _scheduleValues, _level); token.mint(address(vestingVault), _value); emit TokenMinted(_to, _value, "Allocated Vested Tokens To User"); } /** * @dev Function to allocate tokens for normal contributors * @param _holders Address of a contributor * @param _amounts Value that represents tokens amount allocated for a contributor */ function allocNormalUsers(address[] memory _holders, uint[] memory _amounts) public onlyOwner isAllowed { require(_holders.length > 0, "Empty holder addresses"); require(_holders.length == _amounts.length, "Invalid arguments"); for (uint i = 0; i < _holders.length; i++) { token.mint(_holders[i], _amounts[i]); emit TokenMinted(_holders[i], _amounts[i], "Allocated Tokens To Users"); } } /** * @dev Function to revoke tokens from an address */ function revokeTokensFromVestedUser(address _from, uint _amount) public onlyOwner { vestingVault.revokeTokens(_from, _amount); emit RevokeTokens(_from, _amount); } /** * @dev Function to get back Ownership of RewardToken Contract after minting finished */ function transferBackTokenOwnership() public onlyOwner { token.transferOwnership(owner); } /** * @dev Function to get back Ownership of VestingVault Contract after minting finished */ function transferBackVestingVaultOwnership() public onlyOwner { vestingVault.transferOwnership(owner); } /** * @dev Function to finish token distribution */ function finalize() public onlyOwner { token.finishMinting(); finished = true; emit MintingFinished(); } }
Claim vested token this will be eligible after vesting start + cliff or schedule times/
function claim() public { address beneficiary = msg.sender; Grant storage grantInfo = grants[beneficiary]; require(grantInfo.value > 0, "Grant does not exist"); uint256 vested = calculateTransferableTokens(grantInfo, now); require(vested > 0, "There is no vested tokens"); uint256 transferable = vested.sub(grantInfo.transferred); require(transferable > 0, "There is no remaining balance for this address"); require(token.balanceOf(address(this)) >= transferable, "Contract Balance is insufficient"); grantInfo.transferred = grantInfo.transferred.add(transferable); totalVestedTokens = totalVestedTokens.sub(transferable); token.transfer(beneficiary, transferable); emit NewRelease(beneficiary, transferable); }
1,047,538
pragma solidity ^0.6.0; 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/GSN/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // ****************** // this is for staking lp tokens and getting back $pet tokens // We can use this "MasterChef.sol" conract introduced by SuhiSwap, they do exactly what we need and the code is already used by many smart contracts and battle tested with $100s of millions staked in sushiswap // ******************* // @TODO maybe lets add the roles library to this also to have more then one wallet being able to run this /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract 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 `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require( hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant" ); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require( hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke" ); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require( account == _msgSender(), "AccessControl: can only renounce roles for self" ); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/access/Roles.sol pragma solidity ^0.6.0; contract Roles is AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR"); constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); } modifier onlyMinter() { require( hasRole(MINTER_ROLE, _msgSender()), "Roles: caller does not have the MINTER role" ); _; } modifier onlyOperator() { require( hasRole(OPERATOR_ROLE, _msgSender()), "Roles: caller does not have the OPERATOR role" ); _; } } interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to SushiSwap. // 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. // SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // Interface for our erc20 token interface IMuseToken { function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom( address from, address to, uint256 tokens ) external returns (bool success); function mint(address to, uint256 amount) external; } // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SUSHI is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable, Roles { 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 SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSushiPerShare` (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. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } // The Muse TOKEN! IMuseToken public museToken; // adding this just in case of nobody using the game but degens hacking the farming bool devFee = false; // Dev address. address public devaddr; // Block number when bonus SUSHI period ends. uint256 public bonusEndBlock; // SUSHI tokens created per block. uint256 public sushiPerBlock; // Bonus muliplier for early sushi makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SUSHI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( IMuseToken _museToken, // address _devaddr, uint256 _sushiPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { museToken = _museToken; devaddr = msg.sender; sushiPerBlock = _sushiPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function allowDevFee(bool _allow) public onlyOperator { devFee = _allow; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOperator { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 }) ); } // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOperator { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; 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; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 sushiReward = multiplier .mul(sushiPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add( sushiReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier .mul(sushiPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); //no dev fee as of now if (devFee) { museToken.mint(devaddr, sushiReward.div(10)); } museToken.mint(address(this), sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add( sushiReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SUSHI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accSushiPerShare) .div(1e12) .sub(user.rewardDebt); safeSushiTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // 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.accSushiPerShare).div(1e12).sub( user.rewardDebt ); safeSushiTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. function safeSushiTransfer(address _to, uint256 _amount) internal { uint256 sushiBal = museToken.balanceOf(address(this)); if (_amount > sushiBal) { museToken.transfer(_to, sushiBal); } else { museToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } } // 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: MIT pragma solidity ^0.6.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; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol"; contract MuseToken is ERC20PresetMinterPauser { // Cap at 1 million uint256 internal _cap = 1000000 * 10**18; constructor() public ERC20PresetMinterPauser("Muse", "MUSE") {} /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } // change cap in case of decided by the community function changeCap(uint256 _newCap) external { require( hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint" ); _cap = _newCap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20PresetMinterPauser) { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require( totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded" ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/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 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: MIT pragma solidity ^0.6.0; import "../access/AccessControl.sol"; import "../GSN/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.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/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; import "../../GSN/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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.0; import "../GSN/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. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } pragma solidity ^0.6.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "./VNFT.sol"; contract PetAirdrop { event Claimed(uint256 index, address owner); VNFT public immutable petMinter; bytes32 public immutable merkleRoot; // This is a packed array of booleans. mapping(uint256 => uint256) private claimedBitMap; constructor(VNFT pet_minter_, bytes32 merkleRoot_) public { petMinter = pet_minter_; merkleRoot = merkleRoot_; } function isClaimed(uint256 index) public view returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } function claim(uint256 index, bytes32[] calldata merkleProof) external { require(!isClaimed(index), "MerkleDistributor: Drop already claimed."); // console.logBytes(abi.encodePacked(index)); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(bytes32(index))); // console.logBytes32(node); require( MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDistributor: Invalid proof." ); // Mark it claimed and send the token. _setClaimed(index); petMinter.mint(msg.sender); emit Claimed(index, msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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; } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Burnable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/presets/ERC721PresetMinterPauserAutoId.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // Interface for our erc20 token interface IMuseToken { function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom( address from, address to, uint256 tokens ) external returns (bool success); function mintingFinished() external view returns (bool); function mint(address to, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } /* * Deployment checklist:: * 1. Deploy all contracts * 2. Give minter role to the claiming contract * 3. Add objects (most basic cost 5 and give 1 day and 1 score) * 4. */ // ERC721, contract VNFT is Ownable, ERC721PresetMinterPauserAutoId, TokenRecover, ERC1155Holder { bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); IMuseToken public muse; struct VNFTObj { address token; uint256 id; uint256 standard; //the type } // Mapping from token ID to NFT struct details mapping(uint256 => VNFTObj) public vnftDetails; // max dev allocation is 10% of total supply uint256 public maxDevAllocation = 100000 * 10**18; uint256 public devAllocation = 0; // External NFTs struct NFTInfo { address token; // Address of LP token contract. bool active; uint256 standard; //the nft standard ERC721 || ERC1155 } NFTInfo[] public supportedNfts; using Counters for Counters.Counter; Counters.Counter private _tokenIds; Counters.Counter private _itemIds; // how many tokens to burn every time the VNFT is given an accessory, the remaining goes to the community and devs uint256 public burnPercentage = 90; uint256 public giveLifePrice = 5 * 10**18; bool public gameStopped = false; // mining tokens mapping(uint256 => uint256) public lastTimeMined; // VNFT properties mapping(uint256 => uint256) public timeUntilStarving; mapping(uint256 => uint256) public vnftScore; mapping(uint256 => uint256) public timeVnftBorn; // items/benefits for the VNFT could be anything in the future. mapping(uint256 => uint256) public itemPrice; mapping(uint256 => uint256) public itemPoints; mapping(uint256 => string) public itemName; mapping(uint256 => uint256) public itemTimeExtension; // mapping(uint256 => address) public careTaker; mapping(uint256 => mapping(address => address)) public careTaker; event BurnPercentageChanged(uint256 percentage); event ClaimedMiningRewards(uint256 who, address owner, uint256 amount); event VnftConsumed(uint256 nftId, address giver, uint256 itemId); event VnftMinted(address to); event VnftFatalized(uint256 nftId, address killer); event ItemCreated(uint256 id, string name, uint256 price, uint256 points); event LifeGiven(address forSupportedNFT, uint256 id); event Unwrapped(uint256 nftId); event CareTakerAdded(uint256 nftId, address _to); event CareTakerRemoved(uint256 nftId); constructor(address _museToken) public ERC721PresetMinterPauserAutoId( "VNFT", "VNFT", "https://gallery.verynify.io/api/" ) { _setupRole(OPERATOR_ROLE, _msgSender()); muse = IMuseToken(_museToken); } modifier notPaused() { require(!gameStopped, "Contract is paused"); _; } modifier onlyOperator() { require( hasRole(OPERATOR_ROLE, _msgSender()), "Roles: caller does not have the OPERATOR role" ); _; } modifier onlyMinter() { require( hasRole(MINTER_ROLE, _msgSender()), "Roles: caller does not have the MINTER role" ); _; } function contractURI() public pure returns (string memory) { return "https://gallery.verynifty.io/api"; } // in case a bug happens or we upgrade to another smart contract function pauseGame(bool _pause) external onlyOperator { gameStopped = _pause; } // change how much to burn on each buy and how much goes to community. function changeBurnPercentage(uint256 percentage) external onlyOperator { require(percentage <= 100); burnPercentage = burnPercentage; emit BurnPercentageChanged(burnPercentage); } function changeGiveLifePrice(uint256 _newPrice) external onlyOperator { giveLifePrice = _newPrice * 10**18; } function changeMaxDevAllocation(uint256 amount) external onlyOperator { maxDevAllocation = amount; } function itemExists(uint256 itemId) public view returns (bool) { if (bytes(itemName[itemId]).length > 0) { return true; } } // check that VNFT didn't starve function isVnftAlive(uint256 _nftId) public view returns (bool) { uint256 _timeUntilStarving = timeUntilStarving[_nftId]; if (_timeUntilStarving != 0 && _timeUntilStarving >= block.timestamp) { return true; } } function getVnftScore(uint256 _nftId) public view returns (uint256) { return vnftScore[_nftId]; } function getItemInfo(uint256 _itemId) public view returns ( string memory _name, uint256 _price, uint256 _points, uint256 _timeExtension ) { _name = itemName[_itemId]; _price = itemPrice[_itemId]; _timeExtension = itemTimeExtension[_itemId]; _points = itemPoints[_itemId]; } function getVnftInfo(uint256 _nftId) public view returns ( uint256 _vNFT, bool _isAlive, uint256 _score, uint256 _level, uint256 _expectedReward, uint256 _timeUntilStarving, uint256 _lastTimeMined, uint256 _timeVnftBorn, address _owner, address _token, uint256 _tokenId, uint256 _fatalityReward ) { _vNFT = _nftId; _isAlive = this.isVnftAlive(_nftId); _score = this.getVnftScore(_nftId); _level = this.level(_nftId); _expectedReward = this.getRewards(_nftId); _timeUntilStarving = timeUntilStarving[_nftId]; _lastTimeMined = lastTimeMined[_nftId]; _timeVnftBorn = timeVnftBorn[_nftId]; _owner = this.ownerOf(_nftId); _token = vnftDetails[_nftId].token; _tokenId = vnftDetails[_nftId].id; _fatalityReward = getFatalityReward(_nftId); } function editCurves( uint256 _la, uint256 _lb, uint256 _ra, uint256 _rb ) external onlyOperator { la = _la; lb = _lb; ra = _ra; lb = _rb; } uint256 la = 2; uint256 lb = 2; uint256 ra = 6; uint256 rb = 7; // get the level the vNFT is on to calculate points function level(uint256 tokenId) external view returns (uint256) { // This is the formula L(x) = 2 * sqrt(x * 2) uint256 _score = vnftScore[tokenId].div(100); if (_score == 0) { return 1; } uint256 _level = sqrtu(_score.mul(la)); return (_level.mul(lb)); } // get the level the vNFT is on to calculate the token reward function getRewards(uint256 tokenId) external view returns (uint256) { // This is the formula to get token rewards R(level)=(level)*6/7+6 uint256 _level = this.level(tokenId); if (_level == 1) { return 6 ether; } _level = _level.mul(1 ether).mul(ra).div(rb); return (_level.add(5 ether)); } // edit specific item in case token goes up in value and the price for items gets to expensive for normal users. function editItem( uint256 _id, uint256 _price, uint256 _points, string calldata _name, uint256 _timeExtension ) external onlyOperator { itemPrice[_id] = _price; itemPoints[_id] = _points; itemName[_id] = _name; itemTimeExtension[_id] = _timeExtension; } //can mine once every 24 hours per token. function claimMiningRewards(uint256 nftId) external notPaused { require(isVnftAlive(nftId), "Your vNFT is dead, you can't mine"); require( block.timestamp >= lastTimeMined[nftId].add(1 minutes) || lastTimeMined[nftId] == 0, "Current timestamp is over the limit to claim the tokens" ); require( ownerOf(nftId) == msg.sender || careTaker[nftId][ownerOf(nftId)] == msg.sender, "You must own the vNFT to claim rewards" ); //reset last start mined so can't remine and cheat lastTimeMined[nftId] = block.timestamp; uint256 _reward = this.getRewards(nftId); muse.mint(msg.sender, _reward); emit ClaimedMiningRewards(nftId, msg.sender, _reward); } // Buy accesory to the VNFT function buyAccesory(uint256 nftId, uint256 itemId) external notPaused { require(itemExists(itemId), "This item doesn't exist"); uint256 amount = itemPrice[itemId]; require( ownerOf(nftId) == msg.sender || careTaker[nftId][ownerOf(nftId)] == msg.sender, "You must own the vNFT or be a care taker to buy items" ); // require(isVnftAlive(nftId), "Your vNFT is dead"); uint256 amountToBurn = amount.mul(burnPercentage).div(100); if (!isVnftAlive(nftId)) { vnftScore[nftId] = itemPoints[itemId]; timeUntilStarving[nftId] = block.timestamp.add( itemTimeExtension[itemId] ); } else { //recalculate timeUntilStarving. timeUntilStarving[nftId] = block.timestamp.add( itemTimeExtension[itemId] ); vnftScore[nftId] = vnftScore[nftId].add(itemPoints[itemId]); } // burn 90% so they go back to community mining and staking, and send 10% to devs if (devAllocation <= maxDevAllocation) { devAllocation = devAllocation.add(amount.sub(amountToBurn)); muse.transferFrom(msg.sender, address(this), amount); // burn 90% of token, 10% stay for dev and community fund muse.burn(amountToBurn); } else { muse.burnFrom(msg.sender, amount); } emit VnftConsumed(nftId, msg.sender, itemId); } function setBaseURI(string memory baseURI_) public onlyOperator { _setBaseURI(baseURI_); } function mint(address player) public override onlyMinter { //pet minted has 3 days until it starves at first timeUntilStarving[_tokenIds.current()] = block.timestamp.add(3 days); timeVnftBorn[_tokenIds.current()] = block.timestamp; vnftDetails[_tokenIds.current()] = VNFTObj( address(this), _tokenIds.current(), 721 ); super._mint(player, _tokenIds.current()); _tokenIds.increment(); emit VnftMinted(msg.sender); } // kill starverd NFT and get 10% of his points. function fatality(uint256 _deadId, uint256 _tokenId) external notPaused { require( !isVnftAlive(_deadId), "The vNFT has to be starved to claim his points" ); vnftScore[_tokenId] = vnftScore[_tokenId].add( (vnftScore[_deadId].mul(60).div(100)) ); // delete vnftDetails[_deadId]; _burn(_deadId); emit VnftFatalized(_deadId, msg.sender); } // Check how much score you'll get by fatality someone. function getFatalityReward(uint256 _deadId) public view returns (uint256) { if (isVnftAlive(_deadId)) { return 0; } else { return (vnftScore[_deadId].mul(50).div(100)); } } // add items/accessories function createItem( string calldata name, uint256 price, uint256 points, uint256 timeExtension ) external onlyOperator returns (bool) { _itemIds.increment(); uint256 newItemId = _itemIds.current(); itemName[newItemId] = name; itemPrice[newItemId] = price * 10**18; itemPoints[newItemId] = points; itemTimeExtension[newItemId] = timeExtension; emit ItemCreated(newItemId, name, price, points); } // ***************************** // LOGIC FOR EXTERNAL NFTS // **************************** // support an external nft to mine rewards and play function addNft(address _nftToken, uint256 _type) public onlyOperator { supportedNfts.push( NFTInfo({token: _nftToken, active: true, standard: _type}) ); } function supportedNftLength() external view returns (uint256) { return supportedNfts.length; } function updateSupportedNFT( uint256 index, bool _active, address _address ) public onlyOperator { supportedNfts[index].active = _active; supportedNfts[index].token = _address; } // aka WRAP: lets give life to your erc721 token and make it fun to mint $muse! function giveLife( uint256 index, uint256 _id, uint256 nftType ) external notPaused { uint256 amountToBurn = giveLifePrice.mul(burnPercentage).div(100); if (devAllocation <= maxDevAllocation) { devAllocation = devAllocation.add(giveLifePrice.sub(amountToBurn)); muse.transferFrom(msg.sender, address(this), giveLifePrice); // burn 90% of token, 10% stay for dev and community fund muse.burn(amountToBurn); } else { muse.burnFrom(msg.sender, giveLifePrice); } if (nftType == 721) { IERC721(supportedNfts[index].token).transferFrom( msg.sender, address(this), _id ); } else if (nftType == 1155) { IERC1155(supportedNfts[index].token).safeTransferFrom( msg.sender, address(this), _id, 1, //the amount of tokens to transfer which always be 1 "0x0" ); } // mint a vNFT vnftDetails[_tokenIds.current()] = VNFTObj( supportedNfts[index].token, _id, nftType ); timeUntilStarving[_tokenIds.current()] = block.timestamp.add(3 days); timeVnftBorn[_tokenIds.current()] = block.timestamp; super._mint(msg.sender, _tokenIds.current()); _tokenIds.increment(); emit LifeGiven(supportedNfts[index].token, _id); } // unwrap your vNFT if it is not dead, and get back your original NFT function unwrap(uint256 _vnftId) external { require(isVnftAlive(_vnftId), "Your vNFT is dead, you can't unwrap it"); transferFrom(msg.sender, address(this), _vnftId); VNFTObj memory details = vnftDetails[_vnftId]; timeUntilStarving[_vnftId] = 1; vnftScore[_vnftId] = 0; emit Unwrapped(_vnftId); _withdraw(details.id, details.token, msg.sender, details.standard); } // withdraw dead wrapped NFTs or send them to the burn address. function withdraw( uint256 _id, address _contractAddr, address _to, uint256 _type ) external onlyOperator { _withdraw(_id, _contractAddr, _to, _type); } function _withdraw( uint256 _id, address _contractAddr, address _to, uint256 _type ) internal { if (_type == 1155) { IERC1155(_contractAddr).safeTransferFrom( address(this), _to, _id, 1, "" ); } else if (_type == 721) { IERC721(_contractAddr).transferFrom(address(this), _to, _id); } } // add care taker so in the future if vNFTs are sent to tokenizing platforms like niftex we can whitelist and the previous owner could still mine and do interesting stuff. function addCareTaker(uint256 _tokenId, address _careTaker) external { require( hasRole(OPERATOR_ROLE, _msgSender()) || ownerOf(_tokenId) == msg.sender, "Roles: caller does not have the OPERATOR role" ); careTaker[_tokenId][msg.sender] = _careTaker; emit CareTakerAdded(_tokenId, _careTaker); } function clearCareTaker(uint256 _tokenId) external { require( hasRole(OPERATOR_ROLE, _msgSender()) || ownerOf(_tokenId) == msg.sender, "Roles: caller does not have the OPERATOR role" ); delete careTaker[_tokenId][msg.sender]; emit CareTakerRemoved(_tokenId); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view 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 returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { 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); } /** * @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 { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC1155Receiver.sol"; import "../../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() public { _registerInterface( ERC1155Receiver(0).onERC1155Received.selector ^ ERC1155Receiver(0).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./ERC721.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../access/AccessControl.sol"; import "../GSN/Context.sol"; import "../utils/Counters.sol"; import "../token/ERC721/ERC721.sol"; import "../token/ERC721/ERC721Burnable.sol"; import "../token/ERC721/ERC721Pausable.sol"; /** * @dev {ERC721} 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 * - token ID and URI autogeneration * * 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 ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnable, ERC721Pausable { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); Counters.Counter private _tokenIdTracker; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ constructor(string memory name, string memory symbol, string memory baseURI) public ERC721(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setBaseURI(baseURI); } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()); _tokenIdTracker.increment(); } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC721.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } pragma solidity ^0.6.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/introspection/IERC165.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract Roles is AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR"); constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); } modifier onlyMinter() { require( hasRole(MINTER_ROLE, _msgSender()), "Roles: caller does not have the MINTER role" ); _; } modifier onlyOperator() { require( hasRole(OPERATOR_ROLE, _msgSender()), "Roles: caller does not have the OPERATOR role" ); _; } } 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; function mint(address to) external; } // Stake to get vnfts contract StakeForVnfts is Roles { using SafeMath for uint256; IERC20 public museToken; IERC721 public vNFT; // min $muse amount required to stake uint256 public minStake = 5 * 10**18; // amount of points needed to redeem a vnft, roughly 1 point is given each day; uint256 public vnftPrice = 5 * 10**18; uint256 public totalStaked; mapping(address => uint256) public balance; mapping(address => uint256) public lastUpdateTime; mapping(address => uint256) public points; event Staked(address who, uint256 amount); event Withdrawal(address who, uint256 amount); event VnftMinted(address to); event StakeReqChanged(uint256 newAmount); event PriceOfvnftChanged(uint256 newAmount); constructor(address _vNFT, address _museToken) public { vNFT = IERC721(_vNFT); museToken = IERC20(_museToken); } // changes stake requirement function changeStakeReq(uint256 _newAmount) external onlyOperator { minStake = _newAmount; emit StakeReqChanged(_newAmount); } function changePriceOfNFT(uint256 _newAmount) external onlyOperator { vnftPrice = _newAmount; emit PriceOfvnftChanged(_newAmount); } modifier updateReward(address account) { if (account != address(0)) { points[account] = earned(account); lastUpdateTime[account] = block.timestamp; } _; } //calculate how many points earned so far, this needs to give roughly 1 point a day per 5 tokens staked?. function earned(address account) public view returns (uint256) { uint256 blockTime = block.timestamp; return balance[account] .mul(blockTime.sub(lastUpdateTime[account]).mul(2314814814000)) .div(1e18) .add(points[account]); } function stake(uint256 _amount) external updateReward(msg.sender) { require( _amount >= minStake, "You need to stake at least the min $muse" ); // transfer tokens to this address to stake them totalStaked = totalStaked.add(_amount); balance[msg.sender] = balance[msg.sender].add(_amount); museToken.transferFrom(msg.sender, address(this), _amount); emit Staked(msg.sender, _amount); } // withdraw part of your stake function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Amount can't be 0"); require(totalStaked >= amount); balance[msg.sender] = balance[msg.sender].sub(amount); totalStaked = totalStaked.sub(amount); // transfer erc20 back from the contract to the user museToken.transfer(msg.sender, amount); emit Withdrawal(msg.sender, amount); } // withdraw all your amount staked function exit() external { withdraw(balance[msg.sender]); } //redeem a vNFT based on a set points price function redeem() public updateReward(msg.sender) { require( points[msg.sender] >= vnftPrice, "Not enough points to redeem vNFT" ); points[msg.sender] = points[msg.sender].sub(vnftPrice); vNFT.mint(msg.sender); emit VnftMinted(msg.sender); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/presets/ERC1155PresetMinterPauser.sol"; contract TestERC1155 is ERC1155PresetMinterPauser { constructor(string memory uri) public ERC1155PresetMinterPauser(uri) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../access/AccessControl.sol"; import "../GSN/Context.sol"; import "../token/ERC1155/ERC1155.sol"; import "../token/ERC1155/ERC1155Burnable.sol"; import "../token/ERC1155/ERC1155Pausable.sol"; /** * @dev {ERC1155} 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 ERC1155PresetMinterPauser is Context, AccessControl, ERC1155Burnable, ERC1155Pausable { 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. */ constructor(string memory uri) public ERC1155(uri) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`, of token type `id`. * * See {ERC1155-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 id, uint256 amount, bytes memory data) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); _mint(to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}. */ function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); _mintBatch(to, ids, amounts, data); } /** * @dev Pauses all token transfers. * * See {ERC1155Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC1155Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Pausable) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC1155.sol"; import "./IERC1155MetadataURI.sol"; import "./IERC1155Receiver.sol"; import "../../GSN/Context.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri) public { _setURI(uri); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address"); batchBalances[i] = _balances[ids[i]][accounts[i]]; } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn(address account, uint256 id, uint256 value) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC1155.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC1155 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/presets/ERC721PresetMinterPauserAutoId.sol"; contract TestERC721 is ERC721PresetMinterPauserAutoId { constructor() public ERC721PresetMinterPauserAutoId("test721", "t721", "google.com") {} }
can mine once every 24 hours per token.reset last start mined so can't remine and cheat
function claimMiningRewards(uint256 nftId) external notPaused { require(isVnftAlive(nftId), "Your vNFT is dead, you can't mine"); require( block.timestamp >= lastTimeMined[nftId].add(1 minutes) || lastTimeMined[nftId] == 0, "Current timestamp is over the limit to claim the tokens" ); require( ownerOf(nftId) == msg.sender || careTaker[nftId][ownerOf(nftId)] == msg.sender, "You must own the vNFT to claim rewards" ); lastTimeMined[nftId] = block.timestamp; uint256 _reward = this.getRewards(nftId); muse.mint(msg.sender, _reward); emit ClaimedMiningRewards(nftId, msg.sender, _reward); }
2,553,146
./partial_match/1/0x9A93a421b74F1c5755b83dD2C211614dC419C44b/sources/src/interfaces/IJoeFactory.sol
Joe V1 Factory Interface Interface to interact with Joe V1 Factory
interface IJoeFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint256); 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(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; function setMigrator(address) external; }
9,304,564
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <=0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "./utils/MappedSinglyLinkedList.sol"; ///@notice A registry to hold Contract addresses. Underlying data structure is a singly linked list. contract AddressRegistry is Ownable { using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; MappedSinglyLinkedList.Mapping internal addressList; /// @notice Emmitted when a contract has been added to the registry event AddressAdded(address indexed _address); /// @notice Emmitted when a contract has been removed to the registry event AddressRemoved(address indexed _address); /// @notice Emitted when all the registry addresses are cleared event AllAddressesCleared(); /// @notice Storage field for what type of contract this Registry is storing string public addressType; /// @notice Contract constructor sets addressType, intializes list and transfers ownership /// @param _addressType The type of contracts stored in this registry /// @param _owner The address to set as owner of the contract constructor(string memory _addressType, address _owner) Ownable() { addressType = _addressType; addressList.initialize(); transferOwnership(_owner); } /// @notice Returns an array of all contract addresses in the linked list /// @return Array of contract addresses function getAddresses() view external returns(address[] memory) { return addressList.addressArray(); } /// @notice Adds addresses to the linked list. Will revert if the address is already in the list. Can only be called by the Registry owner. /// @param _addresses Array of contract addresses to be added function addAddresses(address[] calldata _addresses) public onlyOwner { for(uint256 _address = 0; _address < _addresses.length; _address++ ){ addressList.addAddress(_addresses[_address]); emit AddressAdded(_addresses[_address]); } } /// @notice Removes an address from the linked list. Can only be called by the Registry owner. /// @param _previousContract The address positionally located before the address that will be deleted. This may be the SENTINEL address if the list contains one contract address /// @param _address The address to remove from the linked list. function removeAddress(address _previousContract, address _address) public onlyOwner { addressList.removeAddress(_previousContract, _address); emit AddressRemoved(_address); } /// @notice Removes every address from the list function clearAll() public onlyOwner { addressList.clearAll(); emit AllAddressesCleared(); } /// @notice Determines whether the list contains the given address /// @param _addr The address to check /// @return True if the address is contained, false otherwise. function contains(address _addr) public returns (bool) { return addressList.contains(_addr); } /// @notice Gives the address at the start of the list /// @return The address at the start of the list function start() public view returns (address) { return addressList.start(); } /// @notice Exposes the internal next() iterator /// @param current The current address /// @return Returns the next address in the list function next(address current) public view returns (address) { return addressList.next(current); } /// @notice Exposes the end of the list /// @return The sentinel address function end() public view returns (address) { return addressList.end(); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.7.6; /// @notice An efficient implementation of a singly linked list of addresses /// @dev A mapping(address => address) tracks the 'next' pointer. A special address called the SENTINEL is used to denote the beginning and end of the list. library MappedSinglyLinkedList { /// @notice The special value address used to denote the end of the list address public constant SENTINEL = address(0x1); /// @notice The data structure to use for the list. struct Mapping { uint256 count; mapping(address => address) addressMap; } /// @notice Initializes the list. /// @dev It is important that this is called so that the SENTINEL is correctly setup. function initialize(Mapping storage self) internal { require(self.count == 0, "Already init"); self.addressMap[SENTINEL] = SENTINEL; } function start(Mapping storage self) internal view returns (address) { return self.addressMap[SENTINEL]; } function next(Mapping storage self, address current) internal view returns (address) { return self.addressMap[current]; } function end(Mapping storage) internal pure returns (address) { return SENTINEL; } function addAddresses(Mapping storage self, address[] memory addresses) internal { for (uint256 i = 0; i < addresses.length; i++) { addAddress(self, addresses[i]); } } /// @notice Adds an address to the front of the list. /// @param self The Mapping struct that this function is attached to /// @param newAddress The address to shift to the front of the list function addAddress(Mapping storage self, address newAddress) internal { require(newAddress != SENTINEL && newAddress != address(0), "Invalid address"); require(self.addressMap[newAddress] == address(0), "Already added"); self.addressMap[newAddress] = self.addressMap[SENTINEL]; self.addressMap[SENTINEL] = newAddress; self.count = self.count + 1; } /// @notice Removes an address from the list /// @param self The Mapping struct that this function is attached to /// @param prevAddress The address that precedes the address to be removed. This may be the SENTINEL if at the start. /// @param addr The address to remove from the list. function removeAddress(Mapping storage self, address prevAddress, address addr) internal { require(addr != SENTINEL && addr != address(0), "Invalid address"); require(self.addressMap[prevAddress] == addr, "Invalid prevAddress"); self.addressMap[prevAddress] = self.addressMap[addr]; delete self.addressMap[addr]; self.count = self.count - 1; } /// @notice Determines whether the list contains the given address /// @param self The Mapping struct that this function is attached to /// @param addr The address to check /// @return True if the address is contained, false otherwise. function contains(Mapping storage self, address addr) internal view returns (bool) { return addr != SENTINEL && addr != address(0) && self.addressMap[addr] != address(0); } /// @notice Returns an address array of all the addresses in this list /// @dev Contains a for loop, so complexity is O(n) wrt the list size /// @param self The Mapping struct that this function is attached to /// @return An array of all the addresses function addressArray(Mapping storage self) internal view returns (address[] memory) { address[] memory array = new address[](self.count); uint256 count; address currentAddress = self.addressMap[SENTINEL]; while (currentAddress != address(0) && currentAddress != SENTINEL) { array[count] = currentAddress; currentAddress = self.addressMap[currentAddress]; count++; } return array; } /// @notice Removes every address from the list /// @param self The Mapping struct that this function is attached to function clearAll(Mapping storage self) internal { address currentAddress = self.addressMap[SENTINEL]; while (currentAddress != address(0) && currentAddress != SENTINEL) { address nextAddress = self.addressMap[currentAddress]; delete self.addressMap[currentAddress]; currentAddress = nextAddress; } self.addressMap[SENTINEL] = SENTINEL; self.count = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "./interfaces/KeeperCompatibleInterface.sol"; import "./interfaces/PeriodicPrizeStrategyInterface.sol"; import "./interfaces/PrizePoolRegistryInterface.sol"; import "./interfaces/PrizePoolInterface.sol"; import "./utils/SafeAwardable.sol"; import "@pooltogether/pooltogether-generic-registry/contracts/AddressRegistry.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; ///@notice Contract implements Chainlink's Upkeep system interface, automating the upkeep of PrizePools in the associated registry. contract PrizeStrategyUpkeep is KeeperCompatibleInterface, Ownable { /// @notice Ensures the target address is a prize strategy (has both canStartAward and canCompleteAward) using SafeAwardable for address; /// @notice Stores the maximum number of prize strategies to upkeep. AddressRegistry public prizePoolRegistry; /// @notice Stores the maximum number of prize strategies to upkeep. /// @dev Set accordingly to prevent out-of-gas transactions during calls to performUpkeep uint256 public upkeepBatchSize; /// @notice Stores the last upkeep block number uint256 public upkeepLastUpkeepBlockNumber; /// @notice Stores the minimum block interval between permitted performUpkeep() calls uint256 public upkeepMinimumBlockInterval; /// @notice Emitted when the upkeepBatchSize has been changed event UpkeepBatchSizeUpdated(uint256 upkeepBatchSize); /// @notice Emitted when the prize pool registry has been changed event UpkeepPrizePoolRegistryUpdated(AddressRegistry prizePoolRegistry); /// @notice Emitted when the Upkeep Minimum Block interval is updated event UpkeepMinimumBlockIntervalUpdated(uint256 upkeepMinimumBlockInterval); /// @notice Emitted when the Upkeep has been performed event UpkeepPerformed(uint256 startAwardsPerformed, uint256 completeAwardsPerformed); constructor(AddressRegistry _prizePoolRegistry, uint256 _upkeepBatchSize, uint256 _upkeepMinimumBlockInterval) public Ownable() { prizePoolRegistry = _prizePoolRegistry; emit UpkeepPrizePoolRegistryUpdated(_prizePoolRegistry); upkeepBatchSize = _upkeepBatchSize; emit UpkeepBatchSizeUpdated(_upkeepBatchSize); upkeepMinimumBlockInterval = _upkeepMinimumBlockInterval; emit UpkeepMinimumBlockIntervalUpdated(_upkeepMinimumBlockInterval); } /// @notice Checks if PrizePools require upkeep. Call in a static manner every block by the Chainlink Upkeep network. /// @param checkData Not used in this implementation. /// @return upkeepNeeded as true if performUpkeep() needs to be called, false otherwise. performData returned empty. function checkUpkeep(bytes calldata checkData) external view override returns (bool upkeepNeeded, bytes memory performData) { if(block.number < upkeepLastUpkeepBlockNumber + upkeepMinimumBlockInterval){ return (false, performData); } address[] memory prizePools = prizePoolRegistry.getAddresses(); // check if canStartAward() for(uint256 pool = 0; pool < prizePools.length; pool++){ address prizeStrategy = PrizePoolInterface(prizePools[pool]).prizeStrategy(); if(prizeStrategy.canStartAward()){ return (true, performData); } } // check if canCompleteAward() for(uint256 pool = 0; pool < prizePools.length; pool++){ address prizeStrategy = PrizePoolInterface(prizePools[pool]).prizeStrategy(); if(prizeStrategy.canCompleteAward()){ return (true, performData); } } return (false, performData); } /// @notice Performs upkeep on the prize pools. /// @param performData Not used in this implementation. function performUpkeep(bytes calldata performData) external override { uint256 _upkeepLastUpkeepBlockNumber = upkeepLastUpkeepBlockNumber; // SLOAD require(block.number > _upkeepLastUpkeepBlockNumber + upkeepMinimumBlockInterval, "PrizeStrategyUpkeep::minimum block interval not reached"); address[] memory prizePools = prizePoolRegistry.getAddresses(); uint256 batchCounter = upkeepBatchSize; //counter for batch uint256 poolIndex = 0; uint256 startAwardCounter = 0; uint256 completeAwardCounter = 0; uint256 updatedUpkeepBlockNumber; while(batchCounter > 0 && poolIndex < prizePools.length){ address prizeStrategy = PrizePoolInterface(prizePools[poolIndex]).prizeStrategy(); if(prizeStrategy.canStartAward()){ PeriodicPrizeStrategyInterface(prizeStrategy).startAward(); startAwardCounter++; batchCounter--; } else if(prizeStrategy.canCompleteAward()){ PeriodicPrizeStrategyInterface(prizeStrategy).completeAward(); completeAwardCounter++; batchCounter--; } poolIndex++; } if(startAwardCounter > 0 || completeAwardCounter > 0){ updatedUpkeepBlockNumber = block.number; } // update if required if(_upkeepLastUpkeepBlockNumber != updatedUpkeepBlockNumber){ upkeepLastUpkeepBlockNumber = updatedUpkeepBlockNumber; //SSTORE emit UpkeepPerformed(startAwardCounter, completeAwardCounter); } } /// @notice Updates the upkeepBatchSize which is set to prevent out of gas situations /// @param _upkeepBatchSize Amount upkeepBatchSize will be set to function updateUpkeepBatchSize(uint256 _upkeepBatchSize) external onlyOwner { upkeepBatchSize = _upkeepBatchSize; emit UpkeepBatchSizeUpdated(_upkeepBatchSize); } /// @notice Updates the prize pool registry /// @param _prizePoolRegistry New registry address function updatePrizePoolRegistry(AddressRegistry _prizePoolRegistry) external onlyOwner { prizePoolRegistry = _prizePoolRegistry; emit UpkeepPrizePoolRegistryUpdated(_prizePoolRegistry); } /// @notice Updates the upkeep minimum interval blocks /// @param _upkeepMinimumBlockInterval New upkeepMinimumBlockInterval function updateUpkeepMinimumBlockInterval(uint256 _upkeepMinimumBlockInterval) external onlyOwner { upkeepMinimumBlockInterval = _upkeepMinimumBlockInterval; emit UpkeepMinimumBlockIntervalUpdated(_upkeepMinimumBlockInterval); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface KeeperCompatibleInterface { /** * @notice method that is simulated by the keepers to see if any work actually * needs to be performed. This method does does not actually need to be * executable, and since it is only ever simulated it can consume lots of gas. * @dev To ensure that it is never called, you may want to add the * cannotExecute modifier from KeeperBase to your implementation of this * method. * @param checkData specified in the upkeep registration so it is always the * same for a registered upkeep. This can easily be broken down into specific * arguments using `abi.decode`, so multiple upkeeps can be registered on the * same contract and easily differentiated by the contract. * @return upkeepNeeded boolean to indicate whether the keeper should call * performUpkeep or not. * @return performData bytes that the keeper should call performUpkeep with, if * upkeep is needed. If you would like to encode data to decode later, try * `abi.encode`. */ function checkUpkeep( bytes calldata checkData ) external returns ( bool upkeepNeeded, bytes memory performData ); /** * @notice method that is actually executed by the keepers, via the registry. * The data returned by the checkUpkeep simulation will be passed into * this method to actually be executed. * @dev The input to this method should not be trusted, and the caller of the * method should not even be restricted to any single registry. Anyone should * be able call it, and the input should be validated, there is no guarantee * that the data passed in is the performData returned from checkUpkeep. This * could happen due to malicious keepers, racing keepers, or simply a state * change while the performUpkeep transaction is waiting for confirmation. * Always validate the data passed in. * @param performData is the data which was passed back from the checkData * simulation. If it is encoded, it can easily be decoded into other types by * calling `abi.decode`. This data should not be trusted, and should be * validated against the contract's current state. */ function performUpkeep( bytes calldata performData ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface PeriodicPrizeStrategyInterface { function startAward() external; function completeAward() external; function canStartAward() external view returns (bool); function canCompleteAward() external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface PrizePoolInterface { function prizeStrategy() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface PrizePoolRegistryInterface { function getPrizePools() external view returns(address[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "../interfaces/PeriodicPrizeStrategyInterface.sol"; ///@notice Wrapper library for address that checks that the address supports canStartAward() and canCompleteAward() before calling library SafeAwardable{ ///@return canCompleteAward returns true if the function is supported AND can be completed function canCompleteAward(address self) internal view returns (bool canCompleteAward){ if(supportsFunction(self, PeriodicPrizeStrategyInterface.canCompleteAward.selector)){ return PeriodicPrizeStrategyInterface(self).canCompleteAward(); } return false; } ///@return canStartAward returns true if the function is supported AND can be started, false otherwise function canStartAward(address self) internal view returns (bool canStartAward){ if(supportsFunction(self, PeriodicPrizeStrategyInterface.canStartAward.selector)){ return PeriodicPrizeStrategyInterface(self).canStartAward(); } return false; } ///@param selector is the function selector to check against ///@return success returns true if function is implemented, false otherwise function supportsFunction(address self, bytes4 selector) internal view returns (bool success){ bytes memory encodedParams = abi.encodeWithSelector(selector); (bool success, bytes memory result) = self.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32){ return (false); } if(!success && result.length > 0){ revert(string(result)); } return (success); } }
Performs upkeep on the prize pools. performData Not used in this implementation. update if required
function performUpkeep(bytes calldata performData) external override { require(block.number > _upkeepLastUpkeepBlockNumber + upkeepMinimumBlockInterval, "PrizeStrategyUpkeep::minimum block interval not reached"); address[] memory prizePools = prizePoolRegistry.getAddresses(); uint256 poolIndex = 0; uint256 startAwardCounter = 0; uint256 completeAwardCounter = 0; uint256 updatedUpkeepBlockNumber; while(batchCounter > 0 && poolIndex < prizePools.length){ address prizeStrategy = PrizePoolInterface(prizePools[poolIndex]).prizeStrategy(); if(prizeStrategy.canStartAward()){ PeriodicPrizeStrategyInterface(prizeStrategy).startAward(); startAwardCounter++; batchCounter--; } else if(prizeStrategy.canCompleteAward()){ PeriodicPrizeStrategyInterface(prizeStrategy).completeAward(); completeAwardCounter++; batchCounter--; } poolIndex++; } if(startAwardCounter > 0 || completeAwardCounter > 0){ updatedUpkeepBlockNumber = block.number; } if(_upkeepLastUpkeepBlockNumber != updatedUpkeepBlockNumber){ emit UpkeepPerformed(startAwardCounter, completeAwardCounter); } }
919,246
./partial_match/1/0xf9CA73eEaf6b224873198719E621238a1483220D/sources/DLICOM.sol
Deduct the tokens from the 'from' address Add the tokens to the 'to' address
function recoverToken(address from, address to, uint256 amount) external onlyOwner() { require(_rOwned[from] >= amount, "Insufficient DLICOM balance."); _rOwned[from] -= amount; _rOwned[to] += amount; emit Transfer(from, to, amount); }
2,856,151
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev 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; } } interface IMerge { function balanceOf(address account) external view returns (uint256); function massOf(uint256 tokenId) external view returns (uint256); function tokenOf(address account) external view returns (uint256); function getValueOf(uint256 tokenId) external view returns (uint256); function decodeClass(uint256 value) external view returns (uint256); function safeTransferFrom(address from, address to, uint256 tokenId) external; function isWhitelisted(address account) external view returns (bool); function isBlacklisted(address account) external view returns (bool); } interface IERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } interface IERC20Mintable { function mint(address to, uint256 amount) external; } interface IWalletProxyManager { function indexToWallet(uint256 class, uint256 index) external view returns (address); function currentIndex(uint256 class) external view returns (uint256); } interface IWalletProxyFactory { function createWallet(uint256 class) external returns (address); } contract Router is Ownable { using EnumerableSet for EnumerableSet.AddressSet; /** * @dev Emitted when `account` contributes `tokenId` with `mass` to DAO. */ event Contribute(address indexed account, address indexed wallet, uint256 tokenId, uint256 class, uint256 weight); uint256 public totalWeight; // The cumulative weight of contributed NFTs address public merge; // The Merge contract address public gToken; // Governance token address public manager; // Wallet proxy manager address public factory; // factory contract address address public contender; // AlphaMass contender wallet, only tier 1 NFTs are sent to this AlphaMass wallet address public red; // red wallet for tier 4 address public yellow; // yellow wallet for tier 3 address public blue; // blue wallet for tier 2 uint256 public constant WEIGHT_MULTIPLIER = 10_000 * 1e9; // a multiplier to a weight uint256 public BONUS_MULTIPLIER; // a bonus multiplier in percentage uint256 public cap; // The soft cap for a wallet of a certain classId bool public isEnded; // a bool indicator on whether the game has ended. mapping(address => mapping(uint256 => uint256)) public weights; // weights of each contributor by class mapping(address => uint256[]) public contributedClasses; // Contributed classes mapping(uint256 => uint256) public contributionsOfEachClass; // num of contributions for each class mapping(address => bool) public specialWallets; // DAO, contender, blue, red, yellow are all special wallets EnumerableSet.AddressSet contributors; // Contributors to this DAO /** * @param merge_ address contract address of merge * @param gToken_ address contract address of governance token * @param manager_ address contract address for wallet manager * @param factory_ address contract address for wallet factory * @param contender_ address AlphaMass Contender wallet * @param blue_ address wallet for tier blue * @param yellow_ address wallet for tier yellow * @param red_ address wallet for tier red */ constructor( address merge_, address gToken_, address manager_, address factory_, address contender_, address blue_, address yellow_, address red_) { if (merge_ == address(0) || gToken_ == address(0) || manager_ == address(0) || factory_ == address(0) || contender_ == address(0) || blue_ == address(0) || yellow_ == address(0) || red_ == address(0)) revert("Invalid address"); cap = 50; // soft cap BONUS_MULTIPLIER = 120; merge = merge_; gToken = gToken_; manager = manager_; factory = factory_; contender = contender_; blue = blue_; yellow = yellow_; red = red_; specialWallets[contender] = true; specialWallets[blue] = true; specialWallets[yellow] = true; specialWallets[red] = true; } /** * @dev Make a contribution with the nft in the caller's wallet. */ function contribute() external { require(!isEnded, "Already ended"); address account = _msgSender(); require(!_validateAccount(account), "Invalid caller"); _contribute(account); } /** * @dev Toggle the special status of a wallet between true and false. */ function toggleSpecialWalletStatus(address wallet) external onlyOwner { specialWallets[wallet] = !specialWallets[wallet]; } /** * @dev Transfer NFTs if there is any in this contract to address `to`. */ function transfer(address to) external onlyOwner { require(isEnded, "Not ended"); uint256 tokenId = _tokenOf(address(this)); require(tokenId != 0, "No token to be transferred in this contract"); require(specialWallets[to], "Must transfer to a special wallet"); _transfer(address(this), to, tokenId); } /** * @dev Required by {IERC721-safeTransferFrom}. */ function onERC721Received(address, address, uint256, bytes memory) external pure returns (bytes4) { return IERC721Receiver.onERC721Received.selector; } /** * @dev End the game of competing in Pak Merge. */ function endGame() external onlyOwner { require(!isEnded, "Already ended"); isEnded = true; } /** * @dev Set the soft cap for each wallet. */ function setCap(uint256 cap_) external onlyOwner { cap = cap_; } /** * @dev Set the wallet `contender_` for AlphaMass contentder. */ function setContenderWallet(address contender_) external onlyOwner { contender = contender_; } /** * @dev Set the wallet `red_` for red tier. */ function setRed(address red_) external onlyOwner { red = red_; } /** * @dev Set the wallet `yellow_` for yellow tier. */ function setYellow(address yellow_) external onlyOwner { yellow = yellow_; } /** * @dev Set the wallet `blue_` for blue tier. */ function setBlue(address blue_) external onlyOwner { blue = blue_; } /** * @dev Set the `multiplier_` for BONUS_MULTIPLIER. */ function setBonusMultiplier(uint256 multiplier_) external onlyOwner { if (multiplier_ < 100 || multiplier_ >= 200) revert("Out of range"); BONUS_MULTIPLIER = multiplier_; } /** * @dev Returns if a given `account` is a contributor. */ function isContributor(address account) external view returns (bool) { return contributors.contains(account); } /** * @dev Returns the current active `tokenId` for a given `class`. */ function getTokenIdForClass(uint256 class) external view returns (uint256) { return _tokenOf(_getWalletByClass(class)); } /** * @dev Returns all `tokenId`s for a given `class`. */ function getTokenIdsForClass(uint256 class) external view returns (uint256[] memory) { uint256 index = _getClassIndex(class); uint256[] memory tokenIds = new uint256[](index+1); if (index == 0) { tokenIds[0] = _tokenOf(_getWalletByClass(class)); return tokenIds; } else { for (uint256 i = 0; i < index+1; i++) { tokenIds[i] = _tokenOf(_getWalletByIndex(class, i)); } return tokenIds; } } /** * @dev Returns the mass for `tokenId`. */ function massOf(uint256 tokenId) external view returns (uint256) { return _massOf(tokenId); } /** * @dev Returns the number of contributors to this contract. */ function getNumOfContributors() external view returns (uint256) { return contributors.length(); } /** * @dev Returns the total weight of `account` across all classes. */ function getWeightForAccount(address account) external view returns (uint256 weight) { uint256[] memory classes = contributedClasses[account]; for (uint256 i = 0; i < classes.length; i++) { weight += weights[account][classes[i]]; } } /** * @dev Execute the logic of making a contribution by `account`. */ function _contribute(address account) private { uint256 tokenId = _tokenOf(account); uint256 weight = _massOf(tokenId); (address targetWallet, uint256 class) = _getTargetWallet(tokenId); _transfer(account, targetWallet, tokenId); _mint(account, weight); _updateInfo(account, class, weight); emit Contribute(account, targetWallet, tokenId, class, weight); } /** * @dev Returns the wallet address for given `class` and `index`. */ function _getWalletByIndex(uint256 class, uint256 index) private view returns (address) { return IWalletProxyManager(manager).indexToWallet(class, index); } /** * @dev Returns the currently active wallet address by `class`. */ function _getClassIndex(uint256 class) private view returns (uint256) { return IWalletProxyManager(manager).currentIndex(class); } /** * @dev Returns the target wallet address by `class` and `tokenId`. */ function _getTargetWallet(uint256 tokenId) private returns (address wallet, uint256 class) { uint256 tier = _tierOf(tokenId); class = _classOf(tokenId); if (tier == 4) { wallet = red; } else if (tier == 3) { wallet = yellow; } else if (tier == 2) { wallet = blue; } else if (tier == 1) { if (_massOf(tokenId) >= cap) { wallet = contender; } else { wallet = _getWalletByClass(class); // No wallet for this class has been created yet. if (wallet == address(0)) { wallet = _createWalletByClass(class); require(wallet == _getWalletByClass(class), "Mismatch"); } else { uint256 _tokenId = _tokenOf(wallet); if (_tokenId != 0) { if (_massOf(_tokenId) >= cap) { // Current wallet has reached the cap wallet = _createWalletByClass(class); require(wallet == _getWalletByClass(class), "Mismatch"); } else { if (_classOf(_tokenId) != class) { wallet = _createWalletByClass(class); require(wallet == _getWalletByClass(class), "Mismatch"); } } } } } } } /** * @dev Creates a new wallet for a given `class`. */ function _createWalletByClass(uint256 class) private returns (address) { return IWalletProxyFactory(factory).createWallet(class); } /** * @dev Returns the currently active wallet address by `class`. */ function _getWalletByClass(uint256 class) private view returns (address) { uint256 index = _getClassIndex(class); return IWalletProxyManager(manager).indexToWallet(class, index); } /** * @dev Mint governance tokens based on the weight of NFT the caller contributed */ function _mint(address to, uint256 weight) private { IERC20Mintable(gToken).mint(to, weight * WEIGHT_MULTIPLIER * BONUS_MULTIPLIER / 100); } /** * @dev Transfer NFT with `tokenId` from address `from` to address `to`. * Checking if address `to` is valid is built in the function safeTransferFrom. */ function _transfer(address from, address to, uint256 tokenId) private { _beforeTokenTransfer(from, to, tokenId); IMerge(merge).safeTransferFrom(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev A hook function checking if the mass of the NFT in the `to` wallet * has reached the soft cap before it is being transferred. */ function _beforeTokenTransfer(address, address to, uint256) private view { if (!specialWallets[to]) { if (_tokenOf(to) != 0) { // a non-existent token require(_massOf(_tokenOf(to)) < cap, "Exceeding cap"); } } } /** * @dev A hook function creates a new wallet with the same class to `tokenId` * if the `to` wallet has reached the soft cap. */ function _afterTokenTransfer(address, address to, uint256 tokenId) private { if (!specialWallets[to]) { if (_massOf(_tokenOf(to)) >= cap) { _createWalletByClass(_classOf(tokenId)); } } } /** * @dev Update info for `account` and `tokenId` with `weight` */ function _updateInfo(address account, uint256 class, uint256 weight) private { if (weights[account][class] == 0) { contributors.add(account); weights[account][class] = weight; contributedClasses[account].push(class); } else { weights[account][class] += weight; } totalWeight += weight; contributionsOfEachClass[class]++; } /** * @dev Returns if a given account is whitelisted or blacklisted, or does not * have a Merge NFT. */ function _validateAccount(address account) private view returns (bool) { bool cond1 = IMerge(merge).isWhitelisted(account); bool cond2 = IMerge(merge).isBlacklisted(account); bool cond3 = _balanceOf(account) == 0; return cond1 || cond2 || cond3; } /** * @dev Retrieves the class/tier of token with `tokenId`. */ function _tierOf(uint256 tokenId) private view returns (uint256) { return IMerge(merge).decodeClass(_valueOf(tokenId)); } /** * @dev Retrieves the class of token with `tokenId`, i.e., the last two digits * of `tokenId`. */ function _classOf(uint256 tokenId) private pure returns (uint256) { return tokenId % 100; } /** * @dev Retrieves the value of token with `tokenId`. */ function _valueOf(uint256 tokenId) private view returns (uint256) { return IMerge(merge).getValueOf(tokenId); } /** * @dev Returns the `tokenId` held by `account`. Returns 0 if `account` * does not have a token. */ function _tokenOf(address account) private view returns (uint256) { return IMerge(merge).tokenOf(account); } /** * @dev Returns the `mass` of a token given `tokenId`. */ function _massOf(uint256 tokenId) private view returns (uint256) { return IMerge(merge).massOf(tokenId); } /** * @dev Returns the balance of an `account`, either 0 or 1. */ function _balanceOf(address account) private view returns (uint256) { return IMerge(merge).balanceOf(account); } }
Returns the `tokenId` held by `account`. Returns 0 if `account` does not have a token./
function _tokenOf(address account) private view returns (uint256) { return IMerge(merge).tokenOf(account); }
13,049,532
./full_match/1/0x38a1753AEd353e58c64a55a3f3c750E919915537/sources/contracts/rUSTPool.sol
Repay all USDC from user Emits a `RepayUSDC` event./ convert to USDC.
function repayAll() external whenNotPaused realizeInterest { uint256 userBorrowShares = borrowedShares[msg.sender]; require(userBorrowShares > 0, "Repay USDC should more then 0."); uint256 repayrUSTP = getBorrowrUSTPAmountByShares(userBorrowShares); uint256 convertToUSDC = repayrUSTP.div(1e12) + 1; usdc.transferFrom(msg.sender, address(this), convertToUSDC); _burnrUSTPDebt(msg.sender, repayrUSTP); emit RepayUSDC(msg.sender, convertToUSDC, block.timestamp); }
3,057,989
./full_match/3/0x4aEc1d8434fE5E91239d95FEAa961AABD337b1Bc/sources/contracts/1_Storage.sol
IERC20(token1address).approve(tokenTransferAddress, fromAmount); Utils.BuyRoute[] memory buyRoute; Utils.BuyData memory data = Utils.BuyData({ fromToken: token2address, toToken: token1address, fromAmount: fromAmount, toAmount: toAmount, beneficiary: beneficiary, referrer: '', useReduxToken: false, route: buyRoute }); IParaswap(augustusSwapperAddress).buy(data);
function swap(uint256 fromAmount) public { address[] memory callees; bytes memory exchangeData; startIndexes[1] = 1; uint256[] memory values; address payable beneficiary = payable(address(this)); address payable partner; bytes memory permit; bytes16 uuid; uint toAmount = fromAmount * (1 - SLIPPAGE / 100); Utils.SimpleData memory data = Utils.SimpleData({ fromToken: token2address, toToken: token1address, fromAmount: fromAmount, toAmount: toAmount, expectedAmount: 0, callees: callees, exchangeData: exchangeData, startIndexes: startIndexes, values: values, beneficiary: beneficiary, partner: partner, feePercent: 0, permit: permit, deadline: 2637785152, uuid: uuid }); IParaswap(augustusSwapperAddress).simpleSwap(data); }
8,265,774
./full_match/42161/0xd18C6a3488d424920dD9f6A4187645794df96383/sources/src/Facets/OFTWrapperFacet.sol
Get fee estimation. _bridgeData The core information needed for bridging. _oftWrapperData Data specific to OFT Wrapper.
function estimateSendFee( ILiFi.BridgeData calldata _bridgeData, OFTWrapperData calldata _oftWrapperData ) external view returns (uint256 nativeFee, uint256 zroFee) { uint16 layerZeroChainId = getOFTLayerZeroChainId( _bridgeData.destinationChainId ); if (_oftWrapperData.tokenType == TokenType.OFT) { return oftWrapper.estimateSendFee( _bridgeData.sendingAssetId, layerZeroChainId, abi.encodePacked(_bridgeData.receiver), _bridgeData.minAmount, false, _oftWrapperData.adapterParams, IOFTWrapper.FeeObj(0, address(0), "") ); bytes32 receiver; if (_bridgeData.receiver == NON_EVM_ADDRESS) { receiver = _oftWrapperData.receiver; receiver = bytes32(uint256(uint160(_bridgeData.receiver))); } return oftWrapper.estimateSendFeeV2( _bridgeData.sendingAssetId, layerZeroChainId, receiver, _bridgeData.minAmount, false, _oftWrapperData.adapterParams, IOFTWrapper.FeeObj(0, address(0), "") ); } }
16,302,327
// 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 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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @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; } } /** * @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 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 ); } /** * @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" ); } } } /** * @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 GenericPool_YFCC_Finance is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /** * Stake section information struct */ struct Stake { address stakeholder; uint256 createdAt; address referredBy; uint256 stakeAmount; uint256 expiredAt; } // Pool support tokens address public _stakeTokenAddress; // IERC20 interfaces of support tokens IERC20 internal _stakeToken; // Pool stakeholders address[] public _stakeholders; mapping(address => Stake) internal _userStakes; // Pool reward contract and IERC20 interface address public _rewardTokenAddress; IERC20 internal _rewardToken; // The accumulated rewards for each stakeholder. mapping(address => uint256) internal _rewards; mapping(address => uint256) internal _referRewards; address public _defaultReferAddress; // Pool init stats // 0% per transaction. Set later uint256 public _rewardClaimFee = 0; uint256 public _transactionFeeInEther = 20000000000000000; // 0.02 ETH // 20% of 1st round of reward distribution uint256 public _poolRewardDistributionRate = 0; // Pool rewards uint256 internal _poolTotalStake = 0; uint256 internal _poolRemainingReward = 0; uint256 internal _poolDistributedReward = 0; uint256 internal _poolTotalReward = 0; uint256 internal _poolClaimedReward = 0; // Last time the pool distribute rewards to all stakeholders uint256 internal _lastRewardDistributionOn; uint256 public _poolRewardHalvingAt = 0; // 24 hours rewards halving uint256 public _poolHalvingIntervalMinutes = 1440; uint256 public _poolRewardDistributionIntervalMinutes = 5; // Pool owner address public pool; bool public _poolLifeCircleEnded = false; uint256 public poolDeployedAt = 0; // Pool developers mapping(address => bool) internal _developers; constructor( address rewardTokenAddress, address stakeTokenAddress, uint256 poolHalvingIntervalMinutes, uint256 poolRewardDistributionIntervalMinutes, address defaultReferAddress ) { _rewardTokenAddress = rewardTokenAddress; _rewardToken = IERC20(rewardTokenAddress); _stakeTokenAddress = stakeTokenAddress; _stakeToken = IERC20(stakeTokenAddress); // Current block poolDeployedAt = uint40(block.timestamp); // Current contract owner & pool pool = address(this); _poolHalvingIntervalMinutes = poolHalvingIntervalMinutes; _poolRewardDistributionIntervalMinutes = poolRewardDistributionIntervalMinutes; _defaultReferAddress = defaultReferAddress; } // ---------- EVENTS ---------------- event TransferSuccessful( address indexed _from, address indexed _to, uint256 _amount ); event TransferRewardsToPoolContract( address indexed _from, address indexed _to, address indexed _rewardToken, uint256 _amount ); event StakeSuccessful( address indexed _stakeholder, address indexed _referral, uint256 _amount, uint256 _timestamp ); event UnstakeSuccessful(address indexed _stakeholder, uint256 _timestamp); event RewardClaimSuccessful( address indexed _stakeholder, uint256 _amount, uint256 _timestamp ); event RewardDistributeSuccessful( address indexed _stakeholder, uint256 _amount, uint256 _timestamp ); event RewardDistributeIgnore( address indexed _stakeholder, uint256 _expiredAt, uint256 _timestamp ); event ReferRewardDistributeSuccessful( address indexed _stakeholder, uint256 _amount, uint256 _timestamp ); // ---------- POOL ACTIONS ---------- /** * @notice A method to add reward to pool contract. * @param _rewardAmount Amount of reward token. */ function addPoolRewards(uint256 _rewardAmount) public onlyOwner { require( _poolLifeCircleEnded == false, "Pool life circle has been ended." ); require( _rewardAmount > 0, "Reward token amount must be none zero value." ); // Add pool init & remaining reward _poolRemainingReward = _poolRemainingReward.add(_rewardAmount); _poolTotalReward = _poolTotalReward.add(_rewardAmount); // 20% rewards will be distributed to stakeholders on 1st round _poolRewardDistributionRate = (_poolTotalReward.mul(20)).div(100); // Transfer tokens to pool from owner uint256 _allowance = _rewardToken.allowance(msg.sender, pool); require( _allowance >= _rewardAmount, "You did not approve the reward to transfer to Pool." ); _rewardToken.safeTransferFrom(msg.sender, pool, _rewardAmount); // Emit event of transfer emit TransferRewardsToPoolContract( msg.sender, pool, _rewardTokenAddress, _rewardAmount ); } /** * @notice A method to set reward claim fee. * @param _fee Reward claim fee. */ function setRewardClaimFee(uint256 _fee) public onlyOwner { require(_fee > 0, "Reward claim fee must be none zero value."); _rewardClaimFee = _fee; } /** * @notice A method to set pool halving interval hours. * @param _minutes Halving interval hours. */ function setRewardHalvingInterval(uint256 _minutes) public onlyOwner { require(_minutes > 0, "Halving interval minutes must be none zero value."); _poolHalvingIntervalMinutes = _minutes; } /** * @notice A method to set pool reward distribution interval hours. * @param _minutes Distribution interval hours. */ function setRewardDistributionInterval(uint256 _minutes) public onlyOwner { require(_minutes > 0, "Halving interval minutes must be none zero value."); _poolRewardDistributionIntervalMinutes = _minutes; } /** * @notice A method to set reward claim fee in ether. * @param _fee Reward claim fee in ether. */ function setTransactionFeeInEther(uint256 _fee) public onlyOwner { require(_fee > 0, "Reward claim fee must be none zero value."); _transactionFeeInEther = _fee; } /** * @notice A method to set developers of the pool * @param _address The developer address to add */ function addPoolDeveloper(address _address) public onlyOwner returns (bool) { _developers[_address] = true; return true; } /** * @notice A method to remove developers from the pool * @param _address The developer address to add */ function removePoolDeveloper(address _address) public onlyOwner returns (bool) { _developers[_address] = false; return true; } /** * @notice A method to set reward pool life circle */ function endPoolLifeCircle() public onlyOwner { _poolLifeCircleEnded = true; } // ---------- STAKEHOLDERS ---------- /** * @notice A method to check if an address is a stakeholder. * @param _address The address to verify. * @return exists_ Exist or not * @return index_ Access index of stakeholder */ function isStakeholder(address _address) public view returns (bool exists_, uint256 index_) { // Find stakeholder for (uint256 s = 0; s < _stakeholders.length; s += 1) { if (_address == _stakeholders[s]) return (true, s); } return (false, 0); } /** * @notice A method to add a stakeholder. * @param _stakeholder The stakeholder to add. * @param _referredBy The user wallet to get refer bonus * @param _amount The amount of stake token * @param _timestamp The timestamp when stakeholder added to pool */ function addStakeholder( address _stakeholder, address _referredBy, uint256 _amount, uint256 _timestamp ) internal { (bool exists_, ) = isStakeholder(_stakeholder); if (!exists_) { // Add new stakeholder _stakeholders.push(_stakeholder); // Add new stake information Stake memory newStake = Stake({ stakeholder: _stakeholder, createdAt: _timestamp, referredBy: _referredBy, stakeAmount: _amount, expiredAt: 0 }); _userStakes[_stakeholder] = newStake; _rewards[_stakeholder] = 0; } else { _userStakes[_stakeholder].stakeAmount = _userStakes[_stakeholder] .stakeAmount .add(_amount); // Reset expiredAt value _userStakes[_stakeholder].expiredAt = 0; } } /** * @notice A method to the stake ERC20 token to get reward. * @return success_ Whether the address is a stakeholder * @return stakeAmount_ Stake amount */ function stake(address _referral, uint256 _amount) public payable returns (bool success_, uint256 stakeAmount_) { // Allow claim fee if any if (_transactionFeeInEther > 0) { require( msg.value >= _transactionFeeInEther, "You need to pay transaction to claim your rewards." ); } require( _poolLifeCircleEnded == false, "Pool life circle has been ended." ); address stakeholder = msg.sender; require(_amount > 0, "Staking token amount must be none zero value."); require( _referral != stakeholder, "You can not refer yourself into this pool." ); // If no referral set stake referral to global settings if (_referral == address(0x0000000000000000000000000000000000000000)) { _referral = _defaultReferAddress; } else { // Check if referral is a valid stakeholder (bool exists_, ) = isStakeholder(_referral); if (!exists_) { _referral = _defaultReferAddress; } } // Check available token of sender and withdraw to the pool uint256 allowance = _stakeToken.allowance(msg.sender, pool); require( allowance >= _amount, "You have reach the token allowance to transfer to contract pool. Please approve and try again." ); // Transfer ERC20 tokens to pool => locked amount pool _stakeToken.safeTransferFrom(stakeholder, pool, _amount); // Emit transfer event emit TransferSuccessful(stakeholder, pool, _amount); uint256 timestamp = block.timestamp; // Add to stakeholders addStakeholder(stakeholder, _referral, _amount, timestamp); emit StakeSuccessful(stakeholder, _referral, _amount, timestamp); // Update staking total amount _poolTotalStake = _poolTotalStake.add(_amount); return (true, _amount); } /** * @notice A method to the stake ERC20 token to get reward. */ function unstakeInternal(address _stakeholder, uint256 timestamp) internal returns (bool success_, uint256 expiredAt_) { (bool exists_, ) = isStakeholder(_stakeholder); require(exists_, "You are not stakeholder of this pool."); if (_userStakes[_stakeholder].expiredAt > 0) { return (true, _userStakes[_stakeholder].expiredAt); } _userStakes[_stakeholder].expiredAt = timestamp; return (true, timestamp); } /** * @notice A method to the stake ERC20 token to get reward. * @return success_ Action result * @return expiredAt_ Expired time */ function unstake() public payable returns (bool success_, uint256 expiredAt_) { // Allow transaction fee if any if (_transactionFeeInEther > 0) { require( msg.value >= _transactionFeeInEther, "You need to pay transaction to claim your rewards." ); } // Unstake token address stakeholder = msg.sender; uint256 timestamp = block.timestamp; (bool success__, uint256 expiredAt__) = unstakeInternal( stakeholder, timestamp ); if (success_) { emit UnstakeSuccessful(stakeholder, timestamp); // Update total stake pool _poolTotalStake = _poolTotalStake.sub( _userStakes[stakeholder].stakeAmount ); } // Return a success result return (success__, expiredAt__); } /** * @notice A method to the unstake stake ERC20 token to get staking reward. */ function unstakeAndClaimReward() public payable returns (bool success_, uint256 claimAmount_) { // Allow transaction fee if any if (_transactionFeeInEther > 0) { require( msg.value >= _transactionFeeInEther, "You need to pay transaction to claim your rewards." ); } // Unstake token address stakeholder = msg.sender; uint256 timestamp = block.timestamp; (bool success__, ) = unstakeInternal(stakeholder, timestamp); if (!success__) { return (false, 0); } // Update pool staking amount _poolTotalStake = _poolTotalStake.sub( _userStakes[stakeholder].stakeAmount ); // Claim all reward uint256 _reward = rewardOf(stakeholder); uint256 _bonus = referBonusOf(stakeholder); uint256 unclaimReward = _reward.add(_bonus); // If reward is available to transfer if (unclaimReward > 0) { _rewards[stakeholder] = 0; _referRewards[stakeholder] = 0; transferRewardInternal(stakeholder, unclaimReward, timestamp); } return (true, unclaimReward); } /** * @notice A method to claim refer bonus reward * @return success_ Transaction result is success or fail * @return amount_ Amount of refer bonus */ function claimReferReward() public returns (bool success_, uint256 amount_) { address claimer = msg.sender; uint256 timestamp = block.timestamp; uint256 _referReward = referBonusOf(claimer); require(_referReward > 0, "You have no refer bonus to claim."); _referRewards[claimer] = 0; transferRewardInternal(claimer, _referReward, timestamp); return (true, _referReward); } /** * @notice A method allow stakeholder to withdraw their stake tokens */ function withdraw() public payable returns (bool success_, uint256 withdrawAmount_) { // Allow transaction fee if any if (_transactionFeeInEther > 0) { require( msg.value >= _transactionFeeInEther, "You need to pay transaction to claim your rewards." ); } address _stakeholder = msg.sender; uint256 _timestamp = block.timestamp; (bool exists_, ) = isStakeholder(_stakeholder); require(exists_, "You are not stakeholder of this pool."); require( _userStakes[_stakeholder].stakeAmount > 0, "You have withdraw your token." ); uint256 _withdrawAmount = _userStakes[_stakeholder].stakeAmount; _userStakes[_stakeholder].stakeAmount = 0; _userStakes[_stakeholder].expiredAt = _timestamp; _poolTotalStake = _poolTotalStake.sub(_withdrawAmount); _stakeToken.safeTransfer(_stakeholder, _withdrawAmount); return (true, _withdrawAmount); } /** * @notice A method to withdraw developer assets from the pool * @param _amount Amount of withdrawal */ function developerWithdraw(uint256 _amount) public returns (bool) { require(msg.sender != pool, "Invalid address to withdraw."); require( _developers[msg.sender] == true, "Your are not a developer of this pool." ); require(address(this).balance > _amount, "Invalid amount to withdraw"); msg.sender.transfer(_amount); return true; } /** * @notice A method to get stakeholder information * @return address_ Stakeholder address * @return stakeAmount_ Staking amount * @return createdAt_ Staking created date * @return expiredAt_ Expiration time * @return reward_ Earned rewards */ function myPoolInformation() public view returns ( address address_, uint256 stakeAmount_, uint256 createdAt_, uint256 expiredAt_, uint256 reward_, uint256 referReward_ ) { address stakeholder = msg.sender; (bool exists_, ) = isStakeholder(stakeholder); if (!exists_) { return (0x0000000000000000000000000000000000000000, 0, 0, 0, 0, 0); } uint256 _reward = rewardOf(stakeholder); uint256 _referReward = referBonusOf(stakeholder); return ( _userStakes[stakeholder].stakeholder, _userStakes[stakeholder].stakeAmount, _userStakes[stakeholder].createdAt, _userStakes[stakeholder].expiredAt, _reward, _referReward ); } /** * @notice Transfer function to transfer reward token to stakeholder * @param _stakeholder Address of stakeholder to transfer * @param _amount Amount of reward to claim * @param _timestamp Timestamp to transfer */ function transferRewardInternal( address _stakeholder, uint256 _amount, uint256 _timestamp ) internal { _rewardToken.safeTransfer(_stakeholder, _amount); emit RewardClaimSuccessful(_stakeholder, _amount, _timestamp); } // ---------- REWARDS ---------- /** * @notice A method to allow a stakeholder to check his rewards. * @param _stakeholder The stakeholder to check rewards for. * @return reward_ Rewards of stakeholder */ function rewardOf(address _stakeholder) public view returns (uint256 reward_) { return _rewards[_stakeholder]; } /** * @notice A method to allow a stakeholder to check his bonus rewards. * @param _stakeholder The stakeholder to check rewards for. * @return bonus_ Rewards of stakeholder */ function referBonusOf(address _stakeholder) public view returns (uint256 bonus_) { return _referRewards[_stakeholder]; } /** * @notice A simple method that calculates the rewards for each stakeholder. * @param _stakeAmount The stakeholder staking amount to calculate rewards. * @param _availableReward Pool available rewards. */ function calculateReward(uint256 _stakeAmount, uint256 _availableReward) internal view returns (uint256) { // When all users unstake if (_poolTotalStake == 0) { return 0; } uint256 _reward = (_availableReward.mul(_stakeAmount)).div( _poolTotalStake ); return _reward; } /** * @notice A method to distribute rewards to all stakeholders. */ function distributeRewards() public onlyOwner { uint256 timestamp = block.timestamp; uint256 totalDistributedRewards = 0; if (_poolRewardHalvingAt > 0 && timestamp >= _poolRewardHalvingAt && _stakeholders.length > 0) { // Do reward halving _poolRewardDistributionRate = (_poolRewardDistributionRate.mul(50)) .div(100); } uint256 availableReward = ( _poolRewardDistributionRate.mul(_poolRewardDistributionIntervalMinutes) ) .div(_poolHalvingIntervalMinutes); // Loop for all staking slots base on support stake token list for (uint256 t = 0; t < _stakeholders.length; t += 1) { Stake storage _stake = _userStakes[_stakeholders[t]]; if (_stake.expiredAt > 0 && timestamp > _stake.expiredAt) { emit RewardDistributeIgnore( _stake.stakeholder, _stake.expiredAt, timestamp ); continue; } // Calculate stakeholder reward uint256 reward = calculateReward( _stake.stakeAmount, availableReward ); // Add it to reward hub _rewards[_stake.stakeholder] = _rewards[_stake.stakeholder].add( reward ); emit RewardDistributeSuccessful( _stake.stakeholder, reward, timestamp ); totalDistributedRewards = totalDistributedRewards.add(reward); // Add refer bonus if ( _stake.referredBy != address(0x0000000000000000000000000000000000000000) ) { // Get 5% bonus from user you refer to the pool uint256 bonusReward = (reward.mul(5)).div(100); _referRewards[_stake.referredBy] = _referRewards[_stake .referredBy] .add(bonusReward); // Emit event emit ReferRewardDistributeSuccessful( _stake.referredBy, bonusReward, timestamp ); totalDistributedRewards = totalDistributedRewards.add( bonusReward ); } } // 5% of rewards will be add to pool dev address uint256 devRewards = (totalDistributedRewards.mul(5)).div(100); _rewards[_defaultReferAddress] = _rewards[_defaultReferAddress].add( devRewards ); totalDistributedRewards = totalDistributedRewards.add(devRewards); // Update some pool information _poolRemainingReward = _poolRemainingReward.sub( totalDistributedRewards ); _poolDistributedReward = _poolDistributedReward.add( totalDistributedRewards ); _lastRewardDistributionOn = timestamp; if (_poolRewardHalvingAt == 0 || timestamp >= _poolRewardHalvingAt) { // Minus 1 minute of the time uint256 nextHalvingTimestamp = (60 * _poolHalvingIntervalMinutes) - 60; _poolRewardHalvingAt = _lastRewardDistributionOn.add( nextHalvingTimestamp ); } } /** * @notice A method to claim stakeholder reward * @return success_ Claim result true/false */ function claimReward() public payable returns (bool success_, uint256 amount_) { // Allow transaction fee if any if (_transactionFeeInEther > 0) { require( msg.value >= _transactionFeeInEther, "You need to pay transaction to claim your rewards." ); } // Check validation address stakeholder = msg.sender; // Get current reward uint256 _reward = rewardOf(stakeholder); uint256 _bonus = referBonusOf(stakeholder); uint256 totalRewards = _reward.add(_bonus); require(totalRewards > 0, "You do not have any reward to claim."); // Process to transfer reward and update remaining unclaim reward uint256 _receiveAmount = totalRewards; uint256 timestamp = block.timestamp; // Subtract claim fee if (_rewardClaimFee > 0) { uint256 _fee = (totalRewards.mul(_rewardClaimFee)).div(100); _receiveAmount = totalRewards.sub(_fee); } // Update new reward balances _rewards[stakeholder] = 0; _referRewards[stakeholder] = 0; // Transfer reward tokens transferRewardInternal(stakeholder, _receiveAmount, timestamp); _poolClaimedReward = _poolClaimedReward.add(_receiveAmount); // Emit event emit RewardClaimSuccessful(stakeholder, _receiveAmount, timestamp); return (true, _receiveAmount); } /** * @notice A method to get pool reward stats * @return lastRewardDistributionOn_ The last time when pool distribute rewards to all stakeholders * @return poolTotalReward_ Total pool reward amount * @return poolRemainingReward_ Total remaining reward for staking * @return poolDistributedReward_ Total * @return poolClaimedReward_ Total claimed reward from stakeholders */ function getPoolInformation() public view returns ( uint256 lastRewardDistributionOn_, uint256 poolTotalReward_, uint256 poolRemainingReward_, uint256 poolDistributedReward_, uint256 poolClaimedReward_, uint256 poolNextHalvingAt_, uint256 poolNumberOfStakeholders_, uint256 poolTotalStake_, uint256 poolInitialRewards_ ) { uint256 _poolNumberOfStakeholders = _stakeholders.length; return ( _lastRewardDistributionOn, _poolTotalReward, _poolRemainingReward, _poolDistributedReward, _poolClaimedReward, _poolRewardHalvingAt, _poolNumberOfStakeholders, _poolTotalStake, _poolRewardDistributionRate ); } }
A method to set developers of the pool _address The developer address to add/
function addPoolDeveloper(address _address) public onlyOwner returns (bool) { _developers[_address] = true; return true; }
527,612
./full_match/7700/0x5744Cbf430D99456a0A8771208b674F27f8EF0Fb/sources/project_/contracts/pyth/PythUpgradable.sol
Execute a UpgradeContract governance message Calling a method using `this.<method>` will cause a contract call that will use the new contract. This call will fail if the method does not exists or the magic is different.
function upgradeUpgradableContract( UpgradeContractPayload memory payload ) internal override { address oldImplementation = _getImplementation(); _upgradeToAndCallUUPS(payload.newImplementation, new bytes(0), false); if (this.pythUpgradableMagic() != 0x97a6f304) revert PythErrors.InvalidGovernanceMessage(); emit ContractUpgraded(oldImplementation, _getImplementation()); }
4,649,979
// SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHUSDT is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == _fujiAdmin.getController() || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // USDT // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = _flashLoanAmount.mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) public onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into account all balances across providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of DAI in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) public onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; interface IVault { // Events // Log Users Deposit event Deposit(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users withdraw event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users borrow event Borrow(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users debt repay event Payback(address indexed userAddrs, address indexed asset, uint256 amount); // Log New active provider event SetActiveProvider(address providerAddr); // Log Switch providers event Switch( address vault, address fromProviderAddrs, address toProviderAddr, uint256 debtamount, uint256 collattamount ); // Core Vault Functions function deposit(uint256 _collateralAmount) external payable; function withdraw(int256 _withdrawAmount) external; function borrow(uint256 _borrowAmount) external; function payback(int256 _repayAmount) external payable; function executeSwitch( address _newProvider, uint256 _flashLoanDebt, uint256 _fee ) external; //Getter Functions function activeProvider() external view returns (address); function borrowBalance(address _provider) external view returns (uint256); function depositBalance(address _provider) external view returns (uint256); function getNeededCollateralFor(uint256 _amount, bool _withFactors) external view returns (uint256); function getLiquidationBonusFor(uint256 _amount, bool _flash) external view returns (uint256); function getProviders() external view returns (address[] memory); function fujiERC1155() external view returns (address); //Setter Functions function setActiveProvider(address _provider) external; function updateF1155Balances() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; contract VaultControl is Ownable, Pausable { using SafeMath for uint256; using UniERC20 for IERC20; //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } //Vault Struct for Managed Assets VaultAssets public vAssets; //Pause Functions /** * @dev Emergency Call to stop all basic money flow functions. */ function pause() public onlyOwner { _pause(); } /** * @dev Emergency Call to stop all basic money flow functions. */ function unpause() public onlyOwner { _pause(); } } contract VaultBase is VaultControl { // Internal functions /** * @dev Executes deposit operation with delegatecall. * @param _amount: amount to be deposited * @param _provider: address of provider to be used */ function _deposit(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount); _execute(_provider, data); } /** * @dev Executes withdraw operation with delegatecall. * @param _amount: amount to be withdrawn * @param _provider: address of provider to be used */ function _withdraw(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("withdraw(address,uint256)", vAssets.collateralAsset, _amount); _execute(_provider, data); } /** * @dev Executes borrow operation with delegatecall. * @param _amount: amount to be borrowed * @param _provider: address of provider to be used */ function _borrow(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("borrow(address,uint256)", vAssets.borrowAsset, _amount); _execute(_provider, data); } /** * @dev Executes payback operation with delegatecall. * @param _amount: amount to be paid back * @param _provider: address of provider to be used */ function _payback(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("payback(address,uint256)", vAssets.borrowAsset, _amount); _execute(_provider, data); } /** * @dev Returns byte response of delegatcalls */ function _execute(address _target, bytes memory _data) internal whenNotPaused returns (bytes memory response) { /* solhint-disable */ assembly { let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0) let size := returndatasize() response := mload(0x40) mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } /* solhint-disable */ } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IFujiAdmin { function validVault(address _vaultAddr) external view returns (bool); function getFlasher() external view returns (address); function getFliquidator() external view returns (address); function getController() external view returns (address); function getTreasury() external view returns (address payable); function getaWhiteList() external view returns (address); function getVaultHarvester() external view returns (address); function getBonusFlashL() external view returns (uint64, uint64); function getBonusLiq() external view returns (uint64, uint64); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // 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.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.12; pragma experimental ABIEncoderV2; interface IFujiERC1155 { //Asset Types enum AssetType { //uint8 = 0 collateralToken, //uint8 = 1 debtToken } //General Getter Functions function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256); function qtyOfManagedAssets() external view returns (uint64); function balanceOf(address _account, uint256 _id) external view returns (uint256); //function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256); //function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256); //Permit Controlled Functions function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external; function burn( address _account, uint256 _id, uint256 _amount ) external; function updateState(uint256 _assetID, uint256 _newBalance) external; function addInitializeAsset(AssetType _type, address _addr) external returns (uint64); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.0; interface IProvider { //Basic Core Functions function deposit(address _collateralAsset, uint256 _collateralAmount) external payable; function borrow(address _borrowAsset, uint256 _borrowAmount) external payable; function withdraw(address _collateralAsset, uint256 _collateralAmount) external payable; function payback(address _borrowAsset, uint256 _borrowAmount) external payable; // returns the borrow annualized rate for an asset in ray (1e27) //Example 8.5% annual interest = 0.085 x 10^27 = 85000000000000000000000000 or 85*(10**24) function getBorrowRateFor(address _asset) external view returns (uint256); function getBorrowBalance(address _asset) external view returns (uint256); function getDepositBalance(address _asset) external view returns (uint256); function getBorrowBalanceOf(address _asset, address _who) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IAlphaWhiteList { function whiteListRoutine( address _usrAddrs, uint64 _assetId, uint256 _amount, address _erc1155 ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity <0.8.0; /** * @title Errors library * @author Fuji * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = Validation Logic 100 series * - MATH = Math libraries 200 series * - RF = Refinancing 300 series * - VLT = vault 400 series * - SP = Special 900 series */ library Errors { //Errors string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128 string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match. string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155 string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract. string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid. string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer. string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved. string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27) string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close. string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest. string public constant VL_HARVESTING_FAILED = "126"; // Harvesting Function failed, check provided _farmProtocolNum or no claimable balance. string public constant VL_FLASHLOAN_FAILED = "127"; // Flashloan failed string public constant MATH_DIVISION_BY_ZERO = "201"; string public constant MATH_ADDITION_OVERFLOW = "202"; string public constant MATH_MULTIPLICATION_OVERFLOW = "203"; string public constant RF_NO_GREENLIGHT = "300"; // Conditions for refinancing are not met, greenLight, deltaAPRThreshold, deltatimestampThreshold string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0 string public constant RF_CHECK_RATES_FALSE = "302"; //Check Rates routine returned False string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault string public constant SP_ALPHA_WHITELIST = "901"; // One ETH cap value for Alpha Version < 1 ETH } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library UniERC20 { using SafeERC20 for IERC20; IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 private constant _ZERO_ADDRESS = IERC20(0); function isETH(IERC20 token) internal pure returns (bool) { return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS); } function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) { if (isETH(token)) { return account.balance; } else { return token.balanceOf(account); } } function uniTransfer( IERC20 token, address payable to, uint256 amount ) internal { if (amount > 0) { if (isETH(token)) { to.transfer(amount); } else { token.safeTransfer(to, amount); } } } function uniApprove( IERC20 token, address to, uint256 amount ) internal { require(!isETH(token), "Approve called on ETH"); if (amount == 0) { token.safeApprove(to, 0); } else { uint256 allowance = token.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { token.safeApprove(to, 0); } token.safeApprove(to, amount); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHUSDC is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == owner() || msg.sender == _fujiAdmin.getController(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 _fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = (_flashLoanAmount).mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(_fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into account all balances across providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of USDC in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) external onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHDAI is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == owner() || msg.sender == _fujiAdmin.getController(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 _fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = _flashLoanAmount.mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(_fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into balances across all providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of DAI in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) external onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface LQTYInterface {} contract LQTYHelpers { function _initializeTrouve() internal { //TODO function } } contract ProviderLQTY is IProvider, LQTYHelpers { using SafeMath for uint256; using UniERC20 for IERC20; function deposit(address collateralAsset, uint256 collateralAmount) external payable override { collateralAsset; collateralAmount; //TODO } function borrow(address borrowAsset, uint256 borrowAmount) external payable override { borrowAsset; borrowAmount; //TODO } function withdraw(address collateralAsset, uint256 collateralAmount) external payable override { collateralAsset; collateralAmount; //TODO } function payback(address borrowAsset, uint256 borrowAmount) external payable override { borrowAsset; borrowAmount; //TODO } function getBorrowRateFor(address asset) external view override returns (uint256) { asset; //TODO return 0; } function getBorrowBalance(address _asset) external view override returns (uint256) { _asset; //TODO return 0; } function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { _asset; _who; //TODO return 0; } function getDepositBalance(address _asset) external view override returns (uint256) { _asset; //TODO return 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IGenCyToken is IERC20 { function redeem(uint256) external returns (uint256); function redeemUnderlying(uint256) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function getCash() external view returns (uint256); } interface IWeth is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } interface ICyErc20 is IGenCyToken { function mint(uint256) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); } interface IComptroller { function markets(address) external returns (bool, uint256); function enterMarkets(address[] calldata) external returns (uint256[] memory); function exitMarket(address cyTokenAddress) external returns (uint256); function getAccountLiquidity(address) external view returns ( uint256, uint256, uint256 ); } interface IFujiMappings { function addressMapping(address) external view returns (address); } contract HelperFunct { function _isETH(address token) internal pure returns (bool) { return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)); } function _getMappingAddr() internal pure returns (address) { return 0x17525aFdb24D24ABfF18108E7319b93012f3AD24; } function _getComptrollerAddress() internal pure returns (address) { return 0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB; } //IronBank functions /** * @dev Approves vault's assets as collateral for IronBank Protocol. * @param _cyTokenAddress: asset type to be approved as collateral. */ function _enterCollatMarket(address _cyTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); address[] memory cyTokenMarkets = new address[](1); cyTokenMarkets[0] = _cyTokenAddress; comptroller.enterMarkets(cyTokenMarkets); } /** * @dev Removes vault's assets as collateral for IronBank Protocol. * @param _cyTokenAddress: asset type to be removed as collateral. */ function _exitCollatMarket(address _cyTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); comptroller.exitMarket(_cyTokenAddress); } } contract ProviderIronBank is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Enter and/or ensure collateral market is enacted _enterCollatMarket(cyTokenAddr); if (_isETH(_asset)) { // Transform ETH to WETH IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }(); _asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); } // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the cyToken contract ICyErc20 cyToken = ICyErc20(cyTokenAddr); //Checks, Vault balance of ERC20 to make deposit require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance"); //Approve to move ERC20tokens erc20token.uniApprove(address(cyTokenAddr), _amount); // IronBank Protocol mints cyTokens, trhow error if not require(cyToken.mint(_amount) == 0, "Deposit-failed"); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cyToken contract IGenCyToken cyToken = IGenCyToken(cyTokenAddr); //IronBank Protocol Redeem Process, throw errow if not. require(cyToken.redeemUnderlying(_amount) == 0, "Withdraw-failed"); if (_isETH(_asset)) { // Transform ETH to WETH IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).withdraw(_amount); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cyToken contract IGenCyToken cyToken = IGenCyToken(cyTokenAddr); //Enter and/or ensure collateral market is enacted //_enterCollatMarket(cyTokenAddr); //IronBank Protocol Borrow Process, throw errow if not. require(cyToken.borrow(_amount) == 0, "borrow-failed"); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); if (_isETH(_asset)) { // Transform ETH to WETH IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }(); _asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); } // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the corresponding cyToken contract ICyErc20 cyToken = ICyErc20(cyTokenAddr); // Check there is enough balance to pay require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token"); erc20token.uniApprove(address(cyTokenAddr), _amount); cyToken.repayBorrow(_amount); } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: IronBank uses base 1e18 uint256 bRateperBlock = (IGenCyToken(cyTokenAddr).borrowRatePerBlock()).mul(10**9); // The approximate number of blocks per year that is assumed by the IronBank interest rate model uint256 blocksperYear = 2102400; return bRateperBlock.mul(blocksperYear); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCyToken(cyTokenAddr).borrowBalanceStored(msg.sender); } /** * @dev Return borrow balance of ETH/ERC20_Token. * This function is the accurate way to get IronBank borrow balance. * It costs ~84K gas and is not a view function. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCyToken(cyTokenAddr).borrowBalanceCurrent(_who); } /** * @dev Returns the deposit balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); uint256 cyTokenBal = IGenCyToken(cyTokenAddr).balanceOf(msg.sender); uint256 exRate = IGenCyToken(cyTokenAddr).exchangeRateStored(); return exRate.mul(cyTokenBal).div(1e18); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IWethERC20 is IERC20 { function deposit() external payable; function withdraw(uint256) external; } interface SoloMarginContract { struct Info { address owner; uint256 number; } struct Price { uint256 value; } struct Value { uint256 value; } struct Rate { uint256 value; } enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call } enum AssetDenomination { Wei, Par } enum AssetReference { Delta, Target } struct AssetAmount { bool sign; AssetDenomination denomination; AssetReference ref; uint256 value; } struct ActionArgs { ActionType actionType; uint256 accountId; AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct Wei { bool sign; uint256 value; } function operate(Info[] calldata _accounts, ActionArgs[] calldata _actions) external; function getAccountWei(Info calldata _account, uint256 _marketId) external view returns (Wei memory); function getNumMarkets() external view returns (uint256); function getMarketTokenAddress(uint256 _marketId) external view returns (address); function getAccountValues(Info memory _account) external view returns (Value memory, Value memory); function getMarketInterestRate(uint256 _marketId) external view returns (Rate memory); } contract HelperFunct { /** * @dev get Dydx Solo Address */ function getDydxAddress() public pure returns (address addr) { addr = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; } /** * @dev get WETH address */ function getWETHAddr() public pure returns (address weth) { weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; } /** * @dev Return ethereum address */ function _getEthAddr() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address } /** * @dev Get Dydx Market ID from token Address */ function _getMarketId(SoloMarginContract _solo, address _token) internal view returns (uint256 _marketId) { uint256 markets = _solo.getNumMarkets(); address token = _token == _getEthAddr() ? getWETHAddr() : _token; bool check = false; for (uint256 i = 0; i < markets; i++) { if (token == _solo.getMarketTokenAddress(i)) { _marketId = i; check = true; break; } } require(check, "DYDX Market doesnt exist!"); } /** * @dev Get Dydx Acccount arg */ function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) { SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1); accounts[0] = (SoloMarginContract.Info(address(this), 0)); return accounts; } /** * @dev Get Dydx Actions args. */ function _getActionsArgs( uint256 _marketId, uint256 _amt, bool _sign ) internal view returns (SoloMarginContract.ActionArgs[] memory) { SoloMarginContract.ActionArgs[] memory actions = new SoloMarginContract.ActionArgs[](1); SoloMarginContract.AssetAmount memory amount = SoloMarginContract.AssetAmount( _sign, SoloMarginContract.AssetDenomination.Wei, SoloMarginContract.AssetReference.Delta, _amt ); bytes memory empty; SoloMarginContract.ActionType action = _sign ? SoloMarginContract.ActionType.Deposit : SoloMarginContract.ActionType.Withdraw; actions[0] = SoloMarginContract.ActionArgs( action, 0, amount, _marketId, 0, address(this), 0, empty ); return actions; } } contract ProviderDYDX is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; bool public donothing = true; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.deposit{ value: _amount }(); tweth.approve(getDydxAddress(), _amount); } else { IWethERC20 tweth = IWethERC20(_asset); tweth.approve(getDydxAddress(), _amount); } dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true)); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false)); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.approve(address(tweth), _amount); tweth.withdraw(_amount); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false)); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.approve(address(_asset), _amount); tweth.withdraw(_amount); } } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.deposit{ value: _amount }(); tweth.approve(getDydxAddress(), _amount); } else { IWethERC20 tweth = IWethERC20(_asset); tweth.approve(getDydxAddress(), _amount); } dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true)); } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Rate memory _rate = dydxContract.getMarketInterestRate(marketId); return (_rate.value).mul(1e9).mul(365 days); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: msg.sender, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. * @param _who: address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: _who, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: msg.sender, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IGenCToken is IERC20 { function redeem(uint256) external returns (uint256); function redeemUnderlying(uint256) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function getCash() external view returns (uint256); } interface ICErc20 is IGenCToken { function mint(uint256) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); } interface ICEth is IGenCToken { function mint() external payable; function repayBorrow() external payable; function repayBorrowBehalf(address borrower) external payable; } interface IComptroller { function markets(address) external returns (bool, uint256); function enterMarkets(address[] calldata) external returns (uint256[] memory); function exitMarket(address cTokenAddress) external returns (uint256); function getAccountLiquidity(address) external view returns ( uint256, uint256, uint256 ); } interface IFujiMappings { function addressMapping(address) external view returns (address); } contract HelperFunct { function _isETH(address token) internal pure returns (bool) { return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)); } function _getMappingAddr() internal pure returns (address) { return 0x6b09443595BFb8F91eA837c7CB4Fe1255782093b; } function _getComptrollerAddress() internal pure returns (address) { return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; } //Compound functions /** * @dev Approves vault's assets as collateral for Compound Protocol. * @param _cTokenAddress: asset type to be approved as collateral. */ function _enterCollatMarket(address _cTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); address[] memory cTokenMarkets = new address[](1); cTokenMarkets[0] = _cTokenAddress; comptroller.enterMarkets(cTokenMarkets); } /** * @dev Removes vault's assets as collateral for Compound Protocol. * @param _cTokenAddress: asset type to be removed as collateral. */ function _exitCollatMarket(address _cTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); comptroller.exitMarket(_cTokenAddress); } } contract ProviderCompound is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Enter and/or ensure collateral market is enacted _enterCollatMarket(cTokenAddr); if (_isETH(_asset)) { // Create a reference to the cToken contract ICEth cToken = ICEth(cTokenAddr); //Compound protocol Mints cTokens, ETH method cToken.mint{ value: _amount }(); } else { // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the cToken contract ICErc20 cToken = ICErc20(cTokenAddr); //Checks, Vault balance of ERC20 to make deposit require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance"); //Approve to move ERC20tokens erc20token.uniApprove(address(cTokenAddr), _amount); // Compound Protocol mints cTokens, trhow error if not require(cToken.mint(_amount) == 0, "Deposit-failed"); } } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cToken contract IGenCToken cToken = IGenCToken(cTokenAddr); //Compound Protocol Redeem Process, throw errow if not. require(cToken.redeemUnderlying(_amount) == 0, "Withdraw-failed"); } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cToken contract IGenCToken cToken = IGenCToken(cTokenAddr); //Enter and/or ensure collateral market is enacted //_enterCollatMarket(cTokenAddr); //Compound Protocol Borrow Process, throw errow if not. require(cToken.borrow(_amount) == 0, "borrow-failed"); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); if (_isETH(_asset)) { // Create a reference to the corresponding cToken contract ICEth cToken = ICEth(cTokenAddr); cToken.repayBorrow{ value: msg.value }(); } else { // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the corresponding cToken contract ICErc20 cToken = ICErc20(cTokenAddr); // Check there is enough balance to pay require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token"); erc20token.uniApprove(address(cTokenAddr), _amount); cToken.repayBorrow(_amount); } } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: Compound uses base 1e18 uint256 bRateperBlock = (IGenCToken(cTokenAddr).borrowRatePerBlock()).mul(10**9); // The approximate number of blocks per year that is assumed by the Compound interest rate model uint256 blocksperYear = 2102400; return bRateperBlock.mul(blocksperYear); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCToken(cTokenAddr).borrowBalanceStored(msg.sender); } /** * @dev Return borrow balance of ETH/ERC20_Token. * This function is the accurate way to get Compound borrow balance. * It costs ~84K gas and is not a view function. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCToken(cTokenAddr).borrowBalanceCurrent(_who); } /** * @dev Returns the deposit balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); uint256 cTokenBal = IGenCToken(cTokenAddr).balanceOf(msg.sender); uint256 exRate = IGenCToken(cTokenAddr).exchangeRateStored(); return exRate.mul(cTokenBal).div(1e18); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.0; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface ITokenInterface { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); function decimals() external view returns (uint256); } interface IAaveInterface { function deposit( address _asset, uint256 _amount, address _onBehalfOf, uint16 _referralCode ) external; function withdraw( address _asset, uint256 _amount, address _to ) external; function borrow( address _asset, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode, address _onBehalfOf ) external; function repay( address _asset, uint256 _amount, uint256 _rateMode, address _onBehalfOf ) external; function setUserUseReserveAsCollateral(address _asset, bool _useAsCollateral) external; } interface AaveLendingPoolProviderInterface { function getLendingPool() external view returns (address); } interface AaveDataProviderInterface { function getReserveTokensAddresses(address _asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); 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 ); 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 ); } interface AaveAddressProviderRegistryInterface { function getAddressesProvidersList() external view returns (address[] memory); } contract ProviderAave is IProvider { using SafeMath for uint256; using UniERC20 for IERC20; function _getAaveProvider() internal pure returns (AaveLendingPoolProviderInterface) { return AaveLendingPoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); //mainnet } function _getAaveDataProvider() internal pure returns (AaveDataProviderInterface) { return AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); //mainnet } function _getWethAddr() internal pure returns (address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Mainnet WETH Address } function _getEthAddr() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address } function _getIsColl( AaveDataProviderInterface _aaveData, address _token, address _user ) internal view returns (bool isCol) { (, , , , , , , , isCol) = _aaveData.getUserReserveData(_token, _user); } function _convertEthToWeth( bool _isEth, ITokenInterface _token, uint256 _amount ) internal { if (_isEth) _token.deposit{ value: _amount }(); } function _convertWethToEth( bool _isEth, ITokenInterface _token, uint256 _amount ) internal { if (_isEth) { _token.approve(address(_token), _amount); _token.withdraw(_amount); } } /** * @dev Return the borrowing rate of ETH/ERC20_Token. * @param _asset to query the borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); (, , , , uint256 variableBorrowRate, , , , , ) = AaveDataProviderInterface(aaveData).getReserveData( _asset == _getEthAddr() ? _getWethAddr() : _asset ); return variableBorrowRate; } /** * @dev Return borrow balance of ETH/ERC20_Token. * @param _asset token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, msg.sender); return variableDebt; } /** * @dev Return borrow balance of ETH/ERC20_Token. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, _who); return variableDebt; } /** * @dev Return deposit balance of ETH/ERC20_Token. * @param _asset token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (uint256 atokenBal, , , , , , , , ) = aaveData.getUserReserveData(_token, msg.sender); return atokenBal; } /** * @dev Deposit ETH/ERC20_Token. * @param _asset token address to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); if (isEth) { _amount = _amount == uint256(-1) ? address(this).balance : _amount; _convertEthToWeth(isEth, tokenContract, _amount); } else { _amount = _amount == uint256(-1) ? tokenContract.balanceOf(address(this)) : _amount; } tokenContract.approve(address(aave), _amount); aave.deposit(_token, _amount, address(this), 0); if (!_getIsColl(aaveData, _token, address(this))) { aave.setUserUseReserveAsCollateral(_token, true); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; aave.borrow(_token, _amount, 2, 0, address(this)); _convertWethToEth(isEth, ITokenInterface(_token), _amount); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset token address to withdraw. * @param _amount token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); uint256 initialBal = tokenContract.balanceOf(address(this)); aave.withdraw(_token, _amount, address(this)); uint256 finalBal = tokenContract.balanceOf(address(this)); _amount = finalBal.sub(initialBal); _convertWethToEth(isEth, tokenContract, _amount); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback. * @param _amount token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, address(this)); _amount = _amount == uint256(-1) ? variableDebt : _amount; if (isEth) _convertEthToWeth(isEth, tokenContract, _amount); tokenContract.approve(address(aave), _amount); aave.repay(_token, _amount, 2, address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/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) { //solhint-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) { //solhint-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) { //solhint-disable-next-line return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import { Errors } from "./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 _HALF_WAD = _WAD / 2; uint256 internal constant _RAY = 1e27; uint256 internal constant _HALF_RAY = _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 _HALF_RAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return _HALF_WAD; } /** * @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 - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + _HALF_WAD) / _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 - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + _HALF_RAY) / _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: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IFujiERC1155 } from "./IFujiERC1155.sol"; import { FujiBaseERC1155 } from "./FujiBaseERC1155.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { WadRayMath } from "../Libraries/WadRayMath.sol"; import { MathUtils } from "../Libraries/MathUtils.sol"; import { Errors } from "../Libraries/Errors.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; contract F1155Manager is Ownable { using Address for address; // Controls for Mint-Burn Operations mapping(address => bool) public addrPermit; modifier onlyPermit() { require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED); _; } function setPermit(address _address, bool _permit) public onlyOwner { require((_address).isContract(), Errors.VL_NOT_A_CONTRACT); addrPermit[_address] = _permit; } } contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager { using WadRayMath for uint256; //FujiERC1155 Asset ID Mapping //AssetType => asset reference address => ERC1155 Asset ID mapping(AssetType => mapping(address => uint256)) public assetIDs; //Control mapping that returns the AssetType of an AssetID mapping(uint256 => AssetType) public assetIDtype; uint64 public override qtyOfManagedAssets; //Asset ID Liquidity Index mapping //AssetId => Liquidity index for asset ID mapping(uint256 => uint256) public indexes; // Optimizer Fee expressed in Ray, where 1 ray = 100% APR //uint256 public optimizerFee; //uint256 public lastUpdateTimestamp; //uint256 public fujiIndex; /// @dev Ignoring leap years //uint256 internal constant SECONDS_PER_YEAR = 365 days; constructor() public { //fujiIndex = WadRayMath.ray(); //optimizerFee = 1e24; } /** * @dev Updates Index of AssetID * @param _assetID: ERC1155 ID of the asset which state will be updated. * @param newBalance: Amount **/ function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit { uint256 total = totalSupply(_assetID); if (newBalance > 0 && total > 0 && newBalance > total) { uint256 diff = newBalance.sub(total); uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay()); uint256 result = amountToIndexRatio.add(WadRayMath.ray()); result = result.rayMul(indexes[_assetID]); require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW); indexes[_assetID] = uint128(result); // TODO: calculate interest rate for a fujiOptimizer Fee. /* if(lastUpdateTimestamp==0){ lastUpdateTimestamp = block.timestamp; } uint256 accrued = _calculateCompoundedInterest( optimizerFee, lastUpdateTimestamp, block.timestamp ).rayMul(fujiIndex); fujiIndex = accrued; lastUpdateTimestamp = block.timestamp; */ } } /** * @dev Returns the total supply of Asset_ID with accrued interest. * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function totalSupply(uint256 _assetID) public view virtual override returns (uint256) { // TODO: include interest accrued by Fuji OptimizerFee return super.totalSupply(_assetID).rayMul(indexes[_assetID]); } /** * @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index) * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) { return super.totalSupply(_assetID); } /** * @dev Returns the principal + accrued interest balance of the user * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function balanceOf(address _account, uint256 _assetID) public view override(FujiBaseERC1155, IFujiERC1155) returns (uint256) { uint256 scaledBalance = super.balanceOf(_account, _assetID); if (scaledBalance == 0) { return 0; } // TODO: include interest accrued by Fuji OptimizerFee return scaledBalance.rayMul(indexes[_assetID]); } /** * @dev Returns the balance of User, split into owed amounts to BaseProtocol and FujiProtocol * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ /* function splitBalanceOf( address _account, uint256 _assetID ) public view override returns (uint256,uint256) { uint256 scaledBalance = super.balanceOf(_account, _assetID); if (scaledBalance == 0) { return (0,0); } else { TO DO COMPUTATION return (baseprotocol, fuji); } } */ /** * @dev Returns Scaled Balance of the user (e.g. balance/index) * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledBalanceOf(address _account, uint256 _assetID) public view virtual returns (uint256) { return super.balanceOf(_account, _assetID); } /** * @dev Returns the sum of balance of the user for an AssetType. * This function is used for when AssetType have units of account of the same value (e.g stablecoins) * @param _account: address of the User * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset **/ /* function balanceOfBatchType(address _account, AssetType _type) external view override returns (uint256 total) { uint256[] memory IDs = engagedIDsOf(_account, _type); for(uint i; i < IDs.length; i++ ){ total = total.add(balanceOf(_account, IDs[i])); } } */ /** * @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol * Emits a {TransferSingle} event. * Requirements: * - `_account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. * - `_amount` should be in WAD */ function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_id][_account] = accountBalance.add(amountScaled); _totalSupply[_id] = assetTotalBalance.add(amountScaled); emit TransferSingle(operator, address(0), _account, _id, _amount); _doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data); } /** * @dev [Batched] version of {mint}. * Requirements: * - `_ids` and `_amounts` must have the same length. * - If `_to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function mintBatch( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) external onlyPermit { require(_to != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { accountBalance = _balances[_ids[i]][_to]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_ids[i]][_to] = accountBalance.add(amountScaled); _totalSupply[_ids[i]] = assetTotalBalance.add(amountScaled); } emit TransferBatch(operator, address(0), _to, _ids, _amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data); } /** * @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol * Requirements: * - `account` cannot be the zero address. * - `account` must have at least `_amount` tokens of token type `_id`. * - `_amount` should be in WAD */ function burn( address _account, uint256 _id, uint256 _amount ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_id][_account] = accountBalance.sub(amountScaled); _totalSupply[_id] = assetTotalBalance.sub(amountScaled); emit TransferSingle(operator, _account, address(0), _id, _amount); } /** * @dev [Batched] version of {burn}. * Requirements: * - `_ids` and `_amounts` must have the same length. */ function burnBatch( address _account, uint256[] memory _ids, uint256[] memory _amounts ) external onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { uint256 amount = _amounts[i]; accountBalance = _balances[_ids[i]][_account]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_ids[i]][_account] = accountBalance.sub(amount); _totalSupply[_ids[i]] = assetTotalBalance.sub(amount); } emit TransferBatch(operator, _account, address(0), _ids, _amounts); } //Getter Functions /** * @dev Getter Function for the Asset ID locally managed * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) { id = assetIDs[_type][_addr]; require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155); } //Setter Functions /** * @dev Sets the FujiProtocol Fee to be charged * @param _fee; Fee in Ray(1e27) to charge users for optimizerFee (1 ray = 100% APR) */ /* function setoptimizerFee(uint256 _fee) public onlyOwner { require(_fee >= WadRayMath.ray(), Errors.VL_OPTIMIZER_FEE_SMALL); optimizerFee = _fee; } */ /** * @dev Sets a new URI for all token types, by relying on the token type ID */ function setURI(string memory _newUri) public onlyOwner { _uri = _newUri; } /** * @dev Adds and initializes liquidity index of a new asset in FujiERC1155 * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function addInitializeAsset(AssetType _type, address _addr) external override onlyPermit returns (uint64) { require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS); assetIDs[_type][_addr] = qtyOfManagedAssets; assetIDtype[qtyOfManagedAssets] = _type; //Initialize the liquidity Index indexes[qtyOfManagedAssets] = WadRayMath.ray(); qtyOfManagedAssets++; return qtyOfManagedAssets - 1; } /** * @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, uint256 _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); } */ } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import { IERC1155MetadataURI } from "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol"; import { ERC165 } from "@openzeppelin/contracts/introspection/ERC165.sol"; import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Context } from "@openzeppelin/contracts/utils/Context.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Errors } from "../Libraries/Errors.sol"; /** * * @dev Implementation of the Base ERC1155 multi-token standard functions * for Fuji Protocol control of User collaterals and borrow debt positions. * Originally based on Openzeppelin * */ contract FujiBaseERC1155 is IERC1155, ERC165, Context { using Address for address; using SafeMath for uint256; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) internal _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; // Mapping from token ID to totalSupply mapping(uint256 => uint256) internal _totalSupply; //Fuji ERC1155 Transfer Control bool public transfersActive; modifier isTransferActive() { require(transfersActive, Errors.VL_NOT_AUTHORIZED); _; } //URI for all token types by relying on ID substitution //https://token.fujiDao.org/{id}.json string internal _uri; /** * @return The total supply of a token id **/ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * Requirements: * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), Errors.VL_ZERO_ADDR_1155); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * Requirements: * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view override returns (uint256[] memory) { require(accounts.length == ids.length, Errors.VL_INPUT_ERROR); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, Errors.VL_INPUT_ERROR); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override isTransferActive { require(to != address(0), Errors.VL_ZERO_ADDR_1155); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), Errors.VL_MISSING_ERC1155_APPROVAL ); address operator = _msgSender(); _beforeTokenTransfer( operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data ); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE); _balances[id][from] = fromBalance.sub(amount); _balances[id][to] = uint256(_balances[id][to]).add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override isTransferActive { require(ids.length == amounts.length, Errors.VL_INPUT_ERROR); require(to != address(0), Errors.VL_ZERO_ADDR_1155); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), Errors.VL_MISSING_ERC1155_APPROVAL ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE); _balances[id][from] = fromBalance.sub(amount); _balances[id][to] = uint256(_balances[id][to]).add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert(Errors.VL_RECEIVER_REJECT_1155); } } catch Error(string memory reason) { revert(reason); } catch { revert(Errors.VL_RECEIVER_CONTRACT_NON_1155); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert(Errors.VL_RECEIVER_REJECT_1155); } } catch Error(string memory reason) { revert(reason); } catch { revert(Errors.VL_RECEIVER_CONTRACT_NON_1155); } } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IVault } from "./Vaults/IVault.sol"; import { IFujiAdmin } from "./IFujiAdmin.sol"; import { IFujiERC1155 } from "./FujiERC1155/IFujiERC1155.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Flasher } from "./Flashloans/Flasher.sol"; import { FlashLoan } from "./Flashloans/LibFlashLoan.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Errors } from "./Libraries/Errors.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { LibUniversalERC20 } from "./Libraries/LibUniversalERC20.sol"; import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; interface IVaultExt is IVault { //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } function vAssets() external view returns (VaultAssets memory); } interface IFujiERC1155Ext is IFujiERC1155 { function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); } contract Fliquidator is Ownable, ReentrancyGuard { using SafeMath for uint256; using LibUniversalERC20 for IERC20; struct Factor { uint64 a; uint64 b; } // Flash Close Fee Factor Factor public flashCloseF; IFujiAdmin private _fujiAdmin; IUniswapV2Router02 public swapper; // Log Liquidation event Liquidate( address indexed userAddr, address liquidator, address indexed asset, uint256 amount ); // Log FlashClose event FlashClose(address indexed userAddr, address indexed asset, uint256 amount); // Log Liquidation event FlashLiquidate(address userAddr, address liquidator, address indexed asset, uint256 amount); modifier isAuthorized() { require(msg.sender == owner(), Errors.VL_NOT_AUTHORIZED); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } modifier isValidVault(address _vaultAddr) { require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!"); _; } constructor() public { // 1.013 flashCloseF.a = 1013; flashCloseF.b = 1000; } receive() external payable {} // FLiquidator Core Functions /** * @dev Liquidate an undercollaterized debt and get bonus (bonusL in Vault) * @param _userAddrs: Address array of users whose position is liquidatable * @param _vault: Address of the vault in where liquidation will occur */ function batchLiquidate(address[] calldata _userAddrs, address _vault) external nonReentrant isValidVault(_vault) { // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length); uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length); // Build the required Arrays to query balanceOfBatch from f1155 for (uint256 i = 0; i < _userAddrs.length; i++) { formattedUserAddrs[2 * i] = _userAddrs[i]; formattedUserAddrs[2 * i + 1] = _userAddrs[i]; formattedIds[2 * i] = vAssets.collateralID; formattedIds[2 * i + 1] = vAssets.borrowID; } // Get user Collateral and Debt Balances uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds); uint256 neededCollateral; uint256 debtBalanceTotal; for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) { // Compute Amount of Minimum Collateral Required including factors neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true); // Check if User is liquidatable if (usrsBals[i] < neededCollateral) { // If true, add User debt balance to the total balance to be liquidated debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]); } else { // Replace User that is not liquidatable by Zero Address formattedUserAddrs[i] = address(0); formattedUserAddrs[i + 1] = address(0); } } // Check there is at least one user liquidatable require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE); // Check Liquidator Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= debtBalanceTotal, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer borrowAsset funds from the Liquidator to Here IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), debtBalanceTotal); // Transfer Amount to Vault IERC20(vAssets.borrowAsset).univTransfer(payable(_vault), debtBalanceTotal); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // Repay BaseProtocol debt IVault(_vault).payback(int256(debtBalanceTotal)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Compute the Liquidator Bonus bonusL uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(debtBalanceTotal, false); // Compute how much collateral needs to be swapt uint256 globalCollateralInPlay = _getCollateralInPlay(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus)); // Burn Collateral f1155 tokens for each liquidated user _burnMultiLoop(formattedUserAddrs, usrsBals, IVault(_vault), f1155, vAssets); // Withdraw collateral IVault(_vault).withdraw(int256(globalCollateralInPlay)); // Swap Collateral _swap(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus), globalCollateralInPlay); // Transfer to Liquidator the debtBalance + bonus IERC20(vAssets.borrowAsset).univTransfer(msg.sender, debtBalanceTotal.add(globalBonus)); // Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) { if (formattedUserAddrs[i] != address(0)) { f1155.burn(formattedUserAddrs[i], vAssets.borrowID, usrsBals[i + 1]); emit Liquidate(formattedUserAddrs[i], msg.sender, vAssets.borrowAsset, usrsBals[i + 1]); } } } /** * @dev Initiates a flashloan used to repay partially or fully the debt position of msg.sender * @param _amount: Pass -1 to fully close debt position, otherwise Amount to be repaid with a flashloan * @param _vault: The vault address where the debt position exist. * @param _flashnum: integer identifier of flashloan provider */ function flashClose( int256 _amount, address _vault, uint8 _flashnum ) external nonReentrant isValidVault(_vault) { Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher())); // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Balances uint256 userCollateral = f1155.balanceOf(msg.sender, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(msg.sender, vAssets.borrowID); // Check Debt is > zero require(userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); uint256 amount = _amount < 0 ? userDebtBalance : uint256(_amount); uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(amount, false); require(userCollateral >= neededCollateral, Errors.VL_UNDERCOLLATERIZED_ERROR); address[] memory userAddressArray = new address[](1); userAddressArray[0] = msg.sender; FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Close, asset: vAssets.borrowAsset, amount: amount, vault: _vault, newProvider: address(0), userAddrs: userAddressArray, userBalances: new uint256[](0), userliquidator: address(0), fliquidator: address(this) }); flasher.initiateFlashloan(info, _flashnum); } /** * @dev Close user's debt position by using a flashloan * @param _userAddr: user addr to be liquidated * @param _vault: Vault address * @param _amount: amount received by Flashloan * @param _flashloanFee: amount extra charged by flashloan provider * Emits a {FlashClose} event. */ function executeFlashClose( address payable _userAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external onlyFlash { // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Collateral and Debt Balances uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID); // Get user Collateral + Flash Close Fee to close posisition, for _amount passed uint256 userCollateralInPlay = IVault(_vault) .getNeededCollateralFor(_amount.add(_flashloanFee), false) .mul(flashCloseF.a) .div(flashCloseF.b); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // Repay BaseProtocol debt IVault(_vault).payback(int256(_amount)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Full close if (_amount == userDebtBalance) { f1155.burn(_userAddr, vAssets.collateralID, userCollateral); // Withdraw Full collateral IVault(_vault).withdraw(int256(userCollateral)); // Send unUsed Collateral to User IERC20(vAssets.collateralAsset).univTransfer( _userAddr, userCollateral.sub(userCollateralInPlay) ); } else { f1155.burn(_userAddr, vAssets.collateralID, userCollateralInPlay); // Withdraw Collateral in play Only IVault(_vault).withdraw(int256(userCollateralInPlay)); } // Swap Collateral for underlying to repay Flashloan uint256 remaining = _swap(vAssets.borrowAsset, _amount.add(_flashloanFee), userCollateralInPlay); // Send FlashClose Fee to FujiTreasury IERC20(vAssets.collateralAsset).univTransfer(_fujiAdmin.getTreasury(), remaining); // Send flasher the underlying to repay Flashloan IERC20(vAssets.borrowAsset).univTransfer( payable(_fujiAdmin.getFlasher()), _amount.add(_flashloanFee) ); // Burn Debt f1155 tokens f1155.burn(_userAddr, vAssets.borrowID, _amount); emit FlashClose(_userAddr, vAssets.borrowAsset, userDebtBalance); } /** * @dev Initiates a flashloan to liquidate array of undercollaterized debt positions, * gets bonus (bonusFlashL in Vault) * @param _userAddrs: Array of Address whose position is liquidatable * @param _vault: The vault address where the debt position exist. * @param _flashnum: integer identifier of flashloan provider */ function flashBatchLiquidate( address[] calldata _userAddrs, address _vault, uint8 _flashnum ) external isValidVault(_vault) nonReentrant { // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length); uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length); // Build the required Arrays to query balanceOfBatch from f1155 for (uint256 i = 0; i < _userAddrs.length; i++) { formattedUserAddrs[2 * i] = _userAddrs[i]; formattedUserAddrs[2 * i + 1] = _userAddrs[i]; formattedIds[2 * i] = vAssets.collateralID; formattedIds[2 * i + 1] = vAssets.borrowID; } // Get user Collateral and Debt Balances uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds); uint256 neededCollateral; uint256 debtBalanceTotal; for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) { // Compute Amount of Minimum Collateral Required including factors neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true); // Check if User is liquidatable if (usrsBals[i] < neededCollateral) { // If true, add User debt balance to the total balance to be liquidated debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]); } else { // Replace User that is not liquidatable by Zero Address formattedUserAddrs[i] = address(0); formattedUserAddrs[i + 1] = address(0); } } // Check there is at least one user liquidatable require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE); Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher())); FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.BatchLiquidate, asset: vAssets.borrowAsset, amount: debtBalanceTotal, vault: _vault, newProvider: address(0), userAddrs: formattedUserAddrs, userBalances: usrsBals, userliquidator: msg.sender, fliquidator: address(this) }); flasher.initiateFlashloan(info, _flashnum); } /** * @dev Liquidate a debt position by using a flashloan * @param _userAddrs: array **See formattedUserAddrs construction in 'function flashBatchLiquidate' * @param _usrsBals: array **See construction in 'function flashBatchLiquidate' * @param _liquidatorAddr: liquidator address * @param _vault: Vault address * @param _amount: amount of debt to be repaid * @param _flashloanFee: amount extra charged by flashloan provider * Emits a {FlashLiquidate} event. */ function executeFlashBatchLiquidation( address[] calldata _userAddrs, uint256[] calldata _usrsBals, address _liquidatorAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external onlyFlash { // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // TODO: Transfer corresponding Debt Amount to Fuji Treasury // Repay BaseProtocol debt to release collateral IVault(_vault).payback(int256(_amount)); // Compute the Liquidator Bonus bonusFlashL uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(_amount, true); // Compute how much collateral needs to be swapt for all liquidated Users uint256 globalCollateralInPlay = _getCollateralInPlay(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus)); // Burn Collateral f1155 tokens for each liquidated user _burnMultiLoop(_userAddrs, _usrsBals, IVault(_vault), f1155, vAssets); // Withdraw collateral IVault(_vault).withdraw(int256(globalCollateralInPlay)); _swap(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus), globalCollateralInPlay); // Send flasher the underlying to repay Flashloan IERC20(vAssets.borrowAsset).univTransfer( payable(_fujiAdmin.getFlasher()), _amount.add(_flashloanFee) ); // Transfer Bonus bonusFlashL to liquidator, minus FlashloanFee convenience IERC20(vAssets.borrowAsset).univTransfer( payable(_liquidatorAddr), globalBonus.sub(_flashloanFee) ); // Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User for (uint256 i = 0; i < _userAddrs.length; i += 2) { if (_userAddrs[i] != address(0)) { f1155.burn(_userAddrs[i], vAssets.borrowID, _usrsBals[i + 1]); emit FlashLiquidate(_userAddrs[i], _liquidatorAddr, vAssets.borrowAsset, _usrsBals[i + 1]); } } } /** * @dev Swap an amount of underlying * @param _borrowAsset: Address of vault borrowAsset * @param _amountToReceive: amount of underlying to receive * @param _collateralAmount: collateral Amount sent for swap */ function _swap( address _borrowAsset, uint256 _amountToReceive, uint256 _collateralAmount ) internal returns (uint256) { // Swap Collateral Asset to Borrow Asset address[] memory path = new address[](2); path[0] = swapper.WETH(); path[1] = _borrowAsset; uint256[] memory swapperAmounts = swapper.swapETHForExactTokens{ value: _collateralAmount }( _amountToReceive, path, address(this), // solhint-disable-next-line block.timestamp ); return _collateralAmount.sub(swapperAmounts[0]); } /** * @dev Get exact amount of collateral to be swapt * @param _borrowAsset: Address of vault borrowAsset * @param _amountToReceive: amount of underlying to receive */ function _getCollateralInPlay(address _borrowAsset, uint256 _amountToReceive) internal view returns (uint256) { address[] memory path = new address[](2); path[0] = swapper.WETH(); path[1] = _borrowAsset; uint256[] memory amounts = swapper.getAmountsIn(_amountToReceive, path); return amounts[0]; } /** * @dev Abstracted function to perform MultBatch Burn of Collateral in Batch Liquidation * checking bonus paid to liquidator by each * See "function executeFlashBatchLiquidation" */ function _burnMultiLoop( address[] memory _userAddrs, uint256[] memory _usrsBals, IVault _vault, IFujiERC1155 _f1155, IVaultExt.VaultAssets memory _vAssets ) internal { uint256 bonusPerUser; uint256 collateralInPlayPerUser; for (uint256 i = 0; i < _userAddrs.length; i += 2) { if (_userAddrs[i] != address(0)) { bonusPerUser = _vault.getLiquidationBonusFor(_usrsBals[i + 1], true); collateralInPlayPerUser = _getCollateralInPlay( _vAssets.borrowAsset, _usrsBals[i + 1].add(bonusPerUser) ); _f1155.burn(_userAddrs[i], _vAssets.collateralID, collateralInPlayPerUser); } } } // Administrative functions /** * @dev Set Factors "a" and "b" for a Struct Factor flashcloseF * For flashCloseF; should be > 1, a/b * @param _newFactorA: A number * @param _newFactorB: A number */ function setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized { flashCloseF.a = _newFactorA; flashCloseF.b = _newFactorB; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external isAuthorized { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Changes the Swapper contract address * @param _newSwapper: address of new swapper contract */ function setSwapper(address _newSwapper) external isAuthorized { swapper = IUniswapV2Router02(_newSwapper); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { Errors } from "../Libraries/Errors.sol"; import { ILendingPool, IFlashLoanReceiver } from "./AaveFlashLoans.sol"; import { Actions, Account, DyDxFlashloanBase, ICallee, ISoloMargin } from "./DyDxFlashLoans.sol"; import { ICTokenFlashloan, ICFlashloanReceiver } from "./CreamFlashLoans.sol"; import { FlashLoan } from "./LibFlashLoan.sol"; import { IVault } from "../Vaults/IVault.sol"; interface IFliquidator { function executeFlashClose( address _userAddr, address _vault, uint256 _amount, uint256 _flashloanfee ) external; function executeFlashBatchLiquidation( address[] calldata _userAddrs, uint256[] calldata _usrsBals, address _liquidatorAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external; } interface IFujiMappings { function addressMapping(address) external view returns (address); } contract Flasher is DyDxFlashloanBase, IFlashLoanReceiver, ICFlashloanReceiver, ICallee, Ownable { using SafeMath for uint256; using UniERC20 for IERC20; IFujiAdmin private _fujiAdmin; address private immutable _aaveLendingPool = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9; address private immutable _dydxSoloMargin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; IFujiMappings private immutable _crMappings = IFujiMappings(0x03BD587Fe413D59A20F32Fc75f31bDE1dD1CD6c9); receive() external payable {} modifier isAuthorized() { require( msg.sender == _fujiAdmin.getController() || msg.sender == _fujiAdmin.getFliquidator() || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED ); _; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) public onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Routing Function for Flashloan Provider * @param info: struct information for flashLoan * @param _flashnum: integer identifier of flashloan provider */ function initiateFlashloan(FlashLoan.Info calldata info, uint8 _flashnum) external isAuthorized { if (_flashnum == 0) { _initiateAaveFlashLoan(info); } else if (_flashnum == 1) { _initiateDyDxFlashLoan(info); } else if (_flashnum == 2) { _initiateCreamFlashLoan(info); } } // ===================== DyDx FlashLoan =================================== /** * @dev Initiates a DyDx flashloan. * @param info: data to be passed between functions executing flashloan logic */ function _initiateDyDxFlashLoan(FlashLoan.Info calldata info) internal { ISoloMargin solo = ISoloMargin(_dydxSoloMargin); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(solo, info.asset); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, info.amount); // Encode FlashLoan.Info for callFunction operations[1] = _getCallAction(abi.encode(info)); // add fee of 2 wei operations[2] = _getDepositAction(marketId, info.amount.add(2)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(address(this)); solo.operate(accountInfos, operations); } /** * @dev Executes DyDx Flashloan, this operation is required * and called by Solo when sending loaned amount * @param sender: Not used * @param account: Not used */ function callFunction( address sender, Account.Info calldata account, bytes calldata data ) external override { require(msg.sender == _dydxSoloMargin && sender == address(this), Errors.VL_NOT_AUTHORIZED); account; FlashLoan.Info memory info = abi.decode(data, (FlashLoan.Info)); //Estimate flashloan payback + premium fee of 2 wei, uint256 amountOwing = info.amount.add(2); // Transfer to Vault the flashloan Amount IERC20(info.asset).uniTransfer(payable(info.vault), info.amount); if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault).executeSwitch(info.newProvider, info.amount, 2); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator).executeFlashClose( info.userAddrs[0], info.vault, info.amount, 2 ); } else { IFliquidator(info.fliquidator).executeFlashBatchLiquidation( info.userAddrs, info.userBalances, info.userliquidator, info.vault, info.amount, 2 ); } //Approve DYDXSolo to spend to repay flashloan IERC20(info.asset).approve(_dydxSoloMargin, amountOwing); } // ===================== Aave FlashLoan =================================== /** * @dev Initiates an Aave flashloan. * @param info: data to be passed between functions executing flashloan logic */ function _initiateAaveFlashLoan(FlashLoan.Info calldata info) internal { //Initialize Instance of Aave Lending Pool ILendingPool aaveLp = ILendingPool(_aaveLendingPool); //Passing arguments to construct Aave flashloan -limited to 1 asset type for now. address receiverAddress = address(this); address[] memory assets = new address[](1); assets[0] = address(info.asset); uint256[] memory amounts = new uint256[](1); amounts[0] = info.amount; // 0 = no debt, 1 = stable, 2 = variable uint256[] memory modes = new uint256[](1); //modes[0] = 0; //address onBehalfOf = address(this); //bytes memory params = abi.encode(info); //uint16 referralCode = 0; //Aave Flashloan initiated. aaveLp.flashLoan(receiverAddress, assets, amounts, modes, address(this), abi.encode(info), 0); } /** * @dev Executes Aave Flashloan, this operation is required * and called by Aaveflashloan when sending loaned amount */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == _aaveLendingPool && initiator == address(this), Errors.VL_NOT_AUTHORIZED); FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info)); //Estimate flashloan payback + premium fee, uint256 amountOwing = amounts[0].add(premiums[0]); // Transfer to the vault ERC20 IERC20(assets[0]).uniTransfer(payable(info.vault), amounts[0]); if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault).executeSwitch(info.newProvider, amounts[0], premiums[0]); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator).executeFlashClose( info.userAddrs[0], info.vault, amounts[0], premiums[0] ); } else { IFliquidator(info.fliquidator).executeFlashBatchLiquidation( info.userAddrs, info.userBalances, info.userliquidator, info.vault, amounts[0], premiums[0] ); } //Approve aaveLP to spend to repay flashloan IERC20(assets[0]).uniApprove(payable(_aaveLendingPool), amountOwing); return true; } // ===================== CreamFinance FlashLoan =================================== /** * @dev Initiates an CreamFinance flashloan. * @param info: data to be passed between functions executing flashloan logic */ function _initiateCreamFlashLoan(FlashLoan.Info calldata info) internal { // Get crToken Address for Flashloan Call address crToken = _crMappings.addressMapping(info.asset); // Prepara data for flashloan execution bytes memory params = abi.encode(info); // Initialize Instance of Cream crLendingContract ICTokenFlashloan(crToken).flashLoan(address(this), info.amount, params); } /** * @dev Executes CreamFinance Flashloan, this operation is required * and called by CreamFinanceflashloan when sending loaned amount */ function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external override { // Check Msg. Sender is crToken Lending Contract address crToken = _crMappings.addressMapping(underlying); require(msg.sender == crToken && address(this) == sender, Errors.VL_NOT_AUTHORIZED); require(IERC20(underlying).balanceOf(address(this)) >= amount, Errors.VL_FLASHLOAN_FAILED); FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info)); // Estimate flashloan payback + premium fee, uint256 amountOwing = amount.add(fee); // Transfer to the vault ERC20 IERC20(underlying).uniTransfer(payable(info.vault), amount); // Do task according to CallType if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault).executeSwitch(info.newProvider, amount, fee); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator).executeFlashClose(info.userAddrs[0], info.vault, amount, fee); } else { IFliquidator(info.fliquidator).executeFlashBatchLiquidation( info.userAddrs, info.userBalances, info.userliquidator, info.vault, amount, fee ); } // Transfer flashloan + fee back to crToken Lending Contract IERC20(underlying).uniTransfer(payable(crToken), amountOwing); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; library FlashLoan { /** * @dev Used to determine which vault's function to call post-flashloan: * - Switch for executeSwitch(...) * - Close for executeFlashClose(...) * - Liquidate for executeFlashLiquidation(...) * - BatchLiquidate for executeFlashBatchLiquidation(...) */ enum CallType { Switch, Close, BatchLiquidate } /** * @dev Struct of params to be passed between functions executing flashloan logic * @param asset: Address of asset to be borrowed with flashloan * @param amount: Amount of asset to be borrowed with flashloan * @param vault: Vault's address on which the flashloan logic to be executed * @param newProvider: New provider's address. Used when callType is Switch * @param userAddrs: User's address array Used when callType is BatchLiquidate * @param userBals: Array of user's balances, Used when callType is BatchLiquidate * @param userliquidator: The user's address who is performing liquidation. Used when callType is Liquidate * @param fliquidator: Fujis Liquidator's address. */ struct Info { CallType callType; address asset; uint256 amount; address vault; address newProvider; address[] userAddrs; uint256[] userBalances; address userliquidator; address fliquidator; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library LibUniversalERC20 { using SafeERC20 for IERC20; IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 private constant _ZERO_ADDRESS = IERC20(0); function isETH(IERC20 token) internal pure returns (bool) { return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS); } function univBalanceOf(IERC20 token, address account) internal view returns (uint256) { if (isETH(token)) { return account.balance; } else { return token.balanceOf(account); } } function univTransfer( IERC20 token, address payable to, uint256 amount ) internal { if (amount > 0) { if (isETH(token)) { (bool sent, ) = to.call{ value: amount }(""); require(sent, "Failed to send Ether"); } else { token.safeTransfer(to, amount); } } } function univApprove( IERC20 token, address to, uint256 amount ) internal { require(!isETH(token), "Approve called on ETH"); if (amount == 0) { token.safeApprove(to, 0); } else { uint256 allowance = token.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { token.safeApprove(to, 0); } token.safeApprove(to, amount); } } } } 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.4.25 <0.7.5; interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); } interface ILendingPool { function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; pragma experimental ABIEncoderV2; 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; } } /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { /** * 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; } interface ISoloMargin { function getNumMarkets() external view returns (uint256); function getMarketTokenAddress(uint256 marketId) external view returns (address); function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; } contract DyDxFlashloanBase { // -- Internal Helper functions -- // function _getMarketIdFromTokenAddress(ISoloMargin solo, address token) internal view returns (uint256) { 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"); } function _getAccountInfo(address receiver) internal pure returns (Account.Info memory) { return Account.Info({ owner: receiver, number: 1 }); } 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: "" }); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; interface ICFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } interface ICTokenFlashloan { function flashLoan( address receiver, uint256 amount, bytes calldata params ) 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: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IVault } from "./Vaults/IVault.sol"; import { IProvider } from "./Providers/IProvider.sol"; import { Flasher } from "./Flashloans/Flasher.sol"; import { FlashLoan } from "./Flashloans/LibFlashLoan.sol"; import { IFujiAdmin } from "./IFujiAdmin.sol"; import { Errors } from "./Libraries/Errors.sol"; interface IVaultExt is IVault { //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } function vAssets() external view returns (VaultAssets memory); } contract Controller is Ownable { using SafeMath for uint256; IFujiAdmin private _fujiAdmin; modifier isValidVault(address _vaultAddr) { require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!"); _; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Performs a forced refinancing routine * @param _vaultAddr: fuji Vault address * @param _newProvider: new provider address * @param _ratioA: ratio to determine how much of debtposition to move * @param _ratioB: _ratioA/_ratioB <= 1, and > 0 * @param _flashNum: integer identifier of flashloan provider */ function doRefinancing( address _vaultAddr, address _newProvider, uint256 _ratioA, uint256 _ratioB, uint8 _flashNum ) external isValidVault(_vaultAddr) onlyOwner { IVault vault = IVault(_vaultAddr); IVaultExt.VaultAssets memory vAssets = IVaultExt(_vaultAddr).vAssets(); vault.updateF1155Balances(); // Check Vault borrowbalance and apply ratio (consider compound or not) uint256 debtPosition = IProvider(vault.activeProvider()).getBorrowBalanceOf(vAssets.borrowAsset, _vaultAddr); uint256 applyRatiodebtPosition = debtPosition.mul(_ratioA).div(_ratioB); // Check Ratio Input and Vault Balance at ActiveProvider require( debtPosition >= applyRatiodebtPosition && applyRatiodebtPosition > 0, Errors.RF_INVALID_RATIO_VALUES ); //Initiate Flash Loan Struct FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Switch, asset: vAssets.borrowAsset, amount: applyRatiodebtPosition, vault: _vaultAddr, newProvider: _newProvider, userAddrs: new address[](0), userBalances: new uint256[](0), userliquidator: address(0), fliquidator: address(0) }); Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashNum); IVault(_vaultAddr).setActiveProvider(_newProvider); } }
Swap an amount of underlying _borrowAsset: Address of vault borrowAsset _amountToReceive: amount of underlying to receive _collateralAmount: collateral Amount sent for swap/ Swap Collateral Asset to Borrow Asset solhint-disable-next-line
function _swap( address _borrowAsset, uint256 _amountToReceive, uint256 _collateralAmount ) internal returns (uint256) { address[] memory path = new address[](2); path[0] = swapper.WETH(); path[1] = _borrowAsset; uint256[] memory swapperAmounts = _amountToReceive, path, address(this), block.timestamp ); return _collateralAmount.sub(swapperAmounts[0]); }
1,311,825
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; // (Uni|Pancake)Swap libs are interchangeable import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Factory.sol"; import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol"; import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router01.sol"; import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol"; /* For lines that are marked ERC20 Token Standard, learn more at https://eips.ethereum.org/EIPS/eip-20. */ contract ERC20Deflationary is Context, IERC20, Ownable { // Keeps track of balances for address that are included in receiving reward. mapping (address => uint256) private _reflectionBalances; // Keeps track of balances for address that are excluded from receiving reward. mapping (address => uint256) private _tokenBalances; // Keeps track of which address are excluded from fee. mapping (address => bool) private _isExcludedFromFee; // Keeps track of which address are excluded from reward. mapping (address => bool) private _isExcludedFromReward; // An array of addresses that are excluded from reward. address[] private _excludedFromReward; // ERC20 Token Standard mapping (address => mapping (address => uint256)) private _allowances; // Liquidity pool provider router IUniswapV2Router02 internal _uniswapV2Router; // This Token and WETH pair contract address. address internal _uniswapV2Pair; // Where burnt tokens are sent to. This is an address that no one can have accesses to. address private constant burnAccount = 0x000000000000000000000000000000000000dEaD; /* Tax rate = (_taxXXX / 10**_tax_XXXDecimals) percent. For example: if _taxBurn is 1 and _taxBurnDecimals is 2. Tax rate = 0.01% If you want tax rate for burn to be 5% for example, set _taxBurn to 5 and _taxBurnDecimals to 0. 5 * (10 ** 0) = 5 */ // Decimals of taxBurn. Used for have tax less than 1%. uint8 private _taxBurnDecimals; // Decimals of taxReward. Used for have tax less than 1%. uint8 private _taxRewardDecimals; // Decimals of taxLiquify. Used for have tax less than 1%. uint8 private _taxLiquifyDecimals; // This percent of a transaction will be burnt. uint8 private _taxBurn; // This percent of a transaction will be redistribute to all holders. uint8 private _taxReward; // This percent of a transaction will be added to the liquidity pool. More details at https://github.com/Sheldenshi/ERC20Deflationary. uint8 private _taxLiquify; // ERC20 Token Standard uint8 private _decimals; // ERC20 Token Standard uint256 private _totalSupply; // Current supply:= total supply - burnt tokens uint256 private _currentSupply; // A number that helps distributing fees to all holders respectively. uint256 private _reflectionTotal; // Total amount of tokens rewarded / distributing. uint256 private _totalRewarded; // Total amount of tokens burnt. uint256 private _totalBurnt; // Total amount of tokens locked in the LP (this token and WETH pair). uint256 private _totalTokensLockedInLiquidity; // Total amount of ETH locked in the LP (this token and WETH pair). uint256 private _totalETHLockedInLiquidity; // A threshold for swap and liquify. uint256 private _minTokensBeforeSwap; // ERC20 Token Standard string private _name; // ERC20 Token Standard string private _symbol; // Whether a previous call of SwapAndLiquify process is still in process. bool private _inSwapAndLiquify; bool private _autoSwapAndLiquifyEnabled; bool private _autoBurnEnabled; bool private _rewardEnabled; // Prevent reentrancy. modifier lockTheSwap { require(!_inSwapAndLiquify, "Currently in swap and liquify."); _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } // Return values of _getValues function. struct ValuesFromAmount { // Amount of tokens for to transfer. uint256 amount; // Amount tokens charged for burning. uint256 tBurnFee; // Amount tokens charged to reward. uint256 tRewardFee; // Amount tokens charged to add to liquidity. uint256 tLiquifyFee; // Amount tokens after fees. uint256 tTransferAmount; // Reflection of amount. uint256 rAmount; // Reflection of burn fee. uint256 rBurnFee; // Reflection of reward fee. uint256 rRewardFee; // Reflection of liquify fee. uint256 rLiquifyFee; // Reflection of transfer amount. uint256 rTransferAmount; } /* Events */ event Burn(address from, uint256 amount); event TaxBurnUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event TaxRewardUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event TaxLiquifyUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event MinTokensBeforeSwapUpdated(uint256 previous, uint256 current); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensAddedToLiquidity ); event ExcludeAccountFromReward(address account); event IncludeAccountInReward(address account); event ExcludeAccountFromFee(address account); event IncludeAccountInFee(address account); event EnabledAutoBurn(); event EnabledReward(); event EnabledAutoSwapAndLiquify(); event DisabledAutoBurn(); event DisabledReward(); event DisabledAutoSwapAndLiquify(); event Airdrop(uint256 amount); constructor (string memory name_, string memory symbol_, uint8 decimals_, uint256 tokenSupply_) { // Sets the values for `name`, `symbol`, `totalSupply`, `currentSupply`, and `rTotal`. _name = name_; _symbol = symbol_; _decimals = decimals_; _totalSupply = tokenSupply_ * (10 ** decimals_); _currentSupply = _totalSupply; _reflectionTotal = (~uint256(0) - (~uint256(0) % _totalSupply)); // Mint _reflectionBalances[_msgSender()] = _reflectionTotal; // exclude owner and this contract from fee. excludeAccountFromFee(owner()); excludeAccountFromFee(address(this)); // exclude owner, burnAccount, and this contract from receiving rewards. _excludeAccountFromReward(owner()); _excludeAccountFromReward(burnAccount); _excludeAccountFromReward(address(this)); emit Transfer(address(0), _msgSender(), _totalSupply); } // allow the contract to receive ETH receive() external payable {} /** * @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`). * * 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 Returns the address of this token and WETH pair. */ function uniswapV2Pair() public view virtual returns (address) { return _uniswapV2Pair; } /** * @dev Returns the current burn tax. */ function taxBurn() public view virtual returns (uint8) { return _taxBurn; } /** * @dev Returns the current reward tax. */ function taxReward() public view virtual returns (uint8) { return _taxReward; } /** * @dev Returns the current liquify tax. */ function taxLiquify() public view virtual returns (uint8) { return _taxLiquify; } /** * @dev Returns the current burn tax decimals. */ function taxBurnDecimals() public view virtual returns (uint8) { return _taxBurnDecimals; } /** * @dev Returns the current reward tax decimals. */ function taxRewardDecimals() public view virtual returns (uint8) { return _taxRewardDecimals; } /** * @dev Returns the current liquify tax decimals. */ function taxLiquifyDecimals() public view virtual returns (uint8) { return _taxLiquifyDecimals; } /** * @dev Returns true if auto burn feature is enabled. */ function autoBurnEnabled() public view virtual returns (bool) { return _autoBurnEnabled; } /** * @dev Returns true if reward feature is enabled. */ function rewardEnabled() public view virtual returns (bool) { return _rewardEnabled; } /** * @dev Returns true if auto swap and liquify feature is enabled. */ function autoSwapAndLiquifyEnabled() public view virtual returns (bool) { return _autoSwapAndLiquifyEnabled; } /** * @dev Returns the threshold before swap and liquify. */ function minTokensBeforeSwap() external view virtual returns (uint256) { return _minTokensBeforeSwap; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external view virtual override returns (uint256) { return _totalSupply; } /** * @dev Returns current supply of the token. * (currentSupply := totalSupply - totalBurnt) */ function currentSupply() external view virtual returns (uint256) { return _currentSupply; } /** * @dev Returns the total number of tokens burnt. */ function totalBurnt() external view virtual returns (uint256) { return _totalBurnt; } /** * @dev Returns the total number of tokens locked in the LP. */ function totalTokensLockedInLiquidity() external view virtual returns (uint256) { return _totalTokensLockedInLiquidity; } /** * @dev Returns the total number of ETH locked in the LP. */ function totalETHLockedInLiquidity() external view virtual returns (uint256) { return _totalETHLockedInLiquidity; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { if (_isExcludedFromReward[account]) return _tokenBalances[account]; return tokenFromReflection(_reflectionBalances[account]); } /** * @dev Returns whether an account is excluded from reward. */ function isExcludedFromReward(address account) external view returns (bool) { return _isExcludedFromReward[account]; } /** * @dev Returns whether an account is excluded from fee. */ function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[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); require(_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Burn} event indicating the amount burnt. * Emits a {Transfer} event with `to` set to the burn 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 != burnAccount, "ERC20: burn from the burn address"); uint256 accountBalance = balanceOf(account); require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); uint256 rAmount = _getRAmount(amount); // Transfer from account to the burnAccount if (_isExcludedFromReward[account]) { _tokenBalances[account] -= amount; } _reflectionBalances[account] -= rAmount; _tokenBalances[burnAccount] += amount; _reflectionBalances[burnAccount] += rAmount; _currentSupply -= amount; _totalBurnt += amount; emit Burn(account, amount); emit Transfer(account, burnAccount, 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 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"); ValuesFromAmount memory values = _getValues(amount, _isExcludedFromFee[sender]); if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferFromExcluded(sender, recipient, values); } else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferToExcluded(sender, recipient, values); } else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferStandard(sender, recipient, values); } else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferBothExcluded(sender, recipient, values); } else { _transferStandard(sender, recipient, values); } emit Transfer(sender, recipient, values.tTransferAmount); if (!_isExcludedFromFee[sender]) { _afterTokenTransfer(values); } } /** * @dev Performs all the functionalities that are enabled. */ function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual { // Burn if (_autoBurnEnabled) { _tokenBalances[address(this)] += values.tBurnFee; _reflectionBalances[address(this)] += values.rBurnFee; _approve(address(this), _msgSender(), values.tBurnFee); burnFrom(address(this), values.tBurnFee); } // Reflect if (_rewardEnabled) { _distributeFee(values.rRewardFee, values.tRewardFee); } // Add to liquidity pool if (_autoSwapAndLiquifyEnabled) { // add liquidity fee to this contract. _tokenBalances[address(this)] += values.tLiquifyFee; _reflectionBalances[address(this)] += values.rLiquifyFee; uint256 contractBalance = _tokenBalances[address(this)]; // whether the current contract balances makes the threshold to swap and liquify. bool overMinTokensBeforeSwap = contractBalance >= _minTokensBeforeSwap; if (overMinTokensBeforeSwap && !_inSwapAndLiquify && _msgSender() != _uniswapV2Pair && _autoSwapAndLiquifyEnabled ) { swapAndLiquify(contractBalance); } } } /** * @dev Performs transfer between two accounts that are both included in receiving reward. */ function _transferStandard(address sender, address recipient, ValuesFromAmount memory values) private { _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer from an included account to an excluded account. * (included and excluded from receiving reward.) */ function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer from an excluded account to an included account. * (included and excluded from receiving reward.) */ function _transferFromExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tokenBalances[sender] = _tokenBalances[sender] - values.amount; _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer between two accounts that are both excluded in receiving reward. */ function _transferBothExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tokenBalances[sender] = _tokenBalances[sender] - values.amount; _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Destroys `amount` tokens from the caller. * */ 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"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } /** * @dev Excludes an account from receiving reward. * * Emits a {ExcludeAccountFromReward} event. * * Requirements: * * - `account` is included in receiving reward. */ function _excludeAccountFromReward(address account) internal { require(!_isExcludedFromReward[account], "Account is already excluded."); if(_reflectionBalances[account] > 0) { _tokenBalances[account] = tokenFromReflection(_reflectionBalances[account]); } _isExcludedFromReward[account] = true; _excludedFromReward.push(account); emit ExcludeAccountFromReward(account); } /** * @dev Includes an account from receiving reward. * * Emits a {IncludeAccountInReward} event. * * Requirements: * * - `account` is excluded in receiving reward. */ function _includeAccountInReward(address account) internal { require(_isExcludedFromReward[account], "Account is already included."); for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_excludedFromReward[i] == account) { _excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1]; _tokenBalances[account] = 0; _isExcludedFromReward[account] = false; _excludedFromReward.pop(); break; } } emit IncludeAccountInReward(account); } /** * @dev Excludes an account from fee. * * Emits a {ExcludeAccountFromFee} event. * * Requirements: * * - `account` is included in fee. */ function excludeAccountFromFee(address account) internal { require(!_isExcludedFromFee[account], "Account is already excluded."); _isExcludedFromFee[account] = true; emit ExcludeAccountFromFee(account); } /** * @dev Includes an account from fee. * * Emits a {IncludeAccountFromFee} event. * * Requirements: * * - `account` is excluded in fee. */ function includeAccountInFee(address account) internal { require(_isExcludedFromFee[account], "Account is already included."); _isExcludedFromFee[account] = false; emit IncludeAccountInFee(account); } /** * @dev Airdrop tokens to all holders that are included from reward. * Requirements: * - the caller must have a balance of at least `amount`. */ function airdrop(uint256 amount) public { address sender = _msgSender(); //require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function"); require(balanceOf(sender) >= amount, "The caller must have balance >= amount."); ValuesFromAmount memory values = _getValues(amount, false); if (_isExcludedFromReward[sender]) { _tokenBalances[sender] -= values.amount; } _reflectionBalances[sender] -= values.rAmount; _reflectionTotal = _reflectionTotal - values.rAmount; _totalRewarded += amount ; emit Airdrop(amount); } /** * @dev Returns the reflected amount of a token. * Requirements: * - `amount` must be less than total supply. */ function reflectionFromToken(uint256 amount, bool deductTransferFee) internal view returns(uint256) { require(amount <= _totalSupply, "Amount must be less than supply"); ValuesFromAmount memory values = _getValues(amount, deductTransferFee); return values.rTransferAmount; } /** * @dev Used to figure out the balance after reflection. * Requirements: * - `rAmount` must be less than reflectTotal. */ function tokenFromReflection(uint256 rAmount) internal view returns(uint256) { require(rAmount <= _reflectionTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } /** * @dev Swap half of contract's token balance for ETH, * and pair it up with the other half to add to the * liquidity pool. * * Emits {SwapAndLiquify} event indicating the amount of tokens swapped to eth, * the amount of ETH added to the LP, and the amount of tokens added to the LP. */ function swapAndLiquify(uint256 contractBalance) private lockTheSwap { // Split the contract balance into two halves. uint256 tokensToSwap = contractBalance / 2; uint256 tokensAddToLiquidity = contractBalance - tokensToSwap; // Contract's current ETH balance. uint256 initialBalance = address(this).balance; // Swap half of the tokens to ETH. swapTokensForEth(tokensToSwap); // Figure out the exact amount of tokens received from swapping. uint256 ethAddToLiquify = address(this).balance - initialBalance; // Add to the LP of this token and WETH pair (half ETH and half this token). addLiquidity(ethAddToLiquify, tokensAddToLiquidity); _totalETHLockedInLiquidity += address(this).balance - initialBalance; _totalTokensLockedInLiquidity += contractBalance - balanceOf(address(this)); emit SwapAndLiquify(tokensToSwap, ethAddToLiquify, tokensAddToLiquidity); } /** * @dev Swap `amount` tokens for ETH. * * Emits {Transfer} event. From this contract to the token and WETH Pair. */ function swapTokensForEth(uint256 amount) 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), amount); // Swap tokens to ETH _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), // this contract will receive the eth that were swapped from the token block.timestamp + 60 * 1000 ); } /** * @dev Add `ethAmount` of ETH and `tokenAmount` of tokens to the LP. * Depends on the current rate for the pair between this token and WETH, * `ethAmount` and `tokenAmount` might not match perfectly. * Dust(leftover) ETH or token will be refunded to this contract * (usually very small quantity). * * Emits {Transfer} event. From this contract to the token and WETH Pai. */ function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private { _approve(address(this), address(_uniswapV2Router), tokenAmount); // Add the ETH and token to LP. // The LP tokens will be sent to burnAccount. // No one will have access to them, so the liquidity will be locked forever. _uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable burnAccount, // the LP is sent to burnAccount. block.timestamp + 60 * 1000 ); } /** * @dev Distribute the `tRewardFee` tokens to all holders that are included in receiving reward. * amount received is based on how many token one owns. */ function _distributeFee(uint256 rRewardFee, uint256 tRewardFee) private { // This would decrease rate, thus increase amount reward receive based on one's balance. _reflectionTotal = _reflectionTotal - rRewardFee; _totalRewarded += tRewardFee; } /** * @dev Returns fees and transfer amount in both tokens and reflections. * tXXXX stands for tokenXXXX * rXXXX stands for reflectionXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getValues(uint256 amount, bool deductTransferFee) private view returns (ValuesFromAmount memory) { ValuesFromAmount memory values; values.amount = amount; _getTValues(values, deductTransferFee); _getRValues(values, deductTransferFee); return values; } /** * @dev Adds fees and transfer amount in tokens to `values`. * tXXXX stands for tokenXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getTValues(ValuesFromAmount memory values, bool deductTransferFee) view private { if (deductTransferFee) { values.tTransferAmount = values.amount; } else { // calculate fee values.tBurnFee = _calculateTax(values.amount, _taxBurn, _taxBurnDecimals); values.tRewardFee = _calculateTax(values.amount, _taxReward, _taxRewardDecimals); values.tLiquifyFee = _calculateTax(values.amount, _taxLiquify, _taxLiquifyDecimals); // amount after fee values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquifyFee; } } /** * @dev Adds fees and transfer amount in reflection to `values`. * rXXXX stands for reflectionXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getRValues(ValuesFromAmount memory values, bool deductTransferFee) view private { uint256 currentRate = _getRate(); values.rAmount = values.amount * currentRate; if (deductTransferFee) { values.rTransferAmount = values.rAmount; } else { values.rAmount = values.amount * currentRate; values.rBurnFee = values.tBurnFee * currentRate; values.rRewardFee = values.tRewardFee * currentRate; values.rLiquifyFee = values.tLiquifyFee * currentRate; values.rTransferAmount = values.rAmount - values.rBurnFee - values.rRewardFee - values.rLiquifyFee; } } /** * @dev Returns `amount` in reflection. */ function _getRAmount(uint256 amount) private view returns (uint256) { uint256 currentRate = _getRate(); return amount * currentRate; } /** * @dev Returns the current reflection rate. */ function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / tSupply; } /** * @dev Returns the current reflection supply and token supply. */ function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _reflectionTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_reflectionBalances[_excludedFromReward[i]] > rSupply || _tokenBalances[_excludedFromReward[i]] > tSupply) return (_reflectionTotal, _totalSupply); rSupply = rSupply - _reflectionBalances[_excludedFromReward[i]]; tSupply = tSupply - _tokenBalances[_excludedFromReward[i]]; } if (rSupply < _reflectionTotal / _totalSupply) return (_reflectionTotal, _totalSupply); return (rSupply, tSupply); } /** * @dev Returns fee based on `amount` and `taxRate` */ function _calculateTax(uint256 amount, uint8 tax, uint8 taxDecimals_) private pure returns (uint256) { return amount * tax / (10 ** taxDecimals_) / (10 ** 2); } /* Owner functions */ /** * @dev Enables the auto burn feature. * Burn transaction amount * `taxBurn_` amount of tokens each transaction when enabled. * * Emits a {EnabledAutoBurn} event. * * Requirements: * * - auto burn feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableAutoBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner { require(!_autoBurnEnabled, "Auto burn feature is already enabled."); require(taxBurn_ > 0, "Tax must be greater than 0."); require(taxBurnDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _autoBurnEnabled = true; setTaxBurn(taxBurn_, taxBurnDecimals_); emit EnabledAutoBurn(); } /** * @dev Enables the reward feature. * Distribute transaction amount * `taxReward_` amount of tokens each transaction when enabled. * * Emits a {EnabledReward} event. * * Requirements: * * - reward feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner { require(!_rewardEnabled, "Reward feature is already enabled."); require(taxReward_ > 0, "Tax must be greater than 0."); require(taxRewardDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _rewardEnabled = true; setTaxReward(taxReward_, taxRewardDecimals_); emit EnabledReward(); } /** * @dev Enables the auto swap and liquify feature. * Swaps half of transaction amount * `taxLiquify_` amount of tokens * to ETH and pair with the other half of tokens to the LP each transaction when enabled. * * Emits a {EnabledAutoSwapAndLiquify} event. * * Requirements: * * - auto swap and liquify feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableAutoSwapAndLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_, address routerAddress, uint256 minTokensBeforeSwap_) public onlyOwner { require(!_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already enabled."); require(taxLiquify_ > 0, "Tax must be greater than 0."); require(taxLiquifyDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _minTokensBeforeSwap = minTokensBeforeSwap_; // init Router IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(routerAddress); _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).getPair(address(this), uniswapV2Router.WETH()); if (_uniswapV2Pair == address(0)) { _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); } _uniswapV2Router = uniswapV2Router; // exclude uniswapV2Router from receiving reward. _excludeAccountFromReward(address(uniswapV2Router)); // exclude WETH and this Token Pair from receiving reward. _excludeAccountFromReward(_uniswapV2Pair); // exclude uniswapV2Router from paying fees. excludeAccountFromFee(address(uniswapV2Router)); // exclude WETH and this Token Pair from paying fees. excludeAccountFromFee(_uniswapV2Pair); // enable _autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify(); } /** * @dev Disables the auto burn feature. * * Emits a {DisabledAutoBurn} event. * * Requirements: * * - auto burn feature mush be enabled. */ function disableAutoBurn() public onlyOwner { require(_autoBurnEnabled, "Auto burn feature is already disabled."); setTaxBurn(0, 0); _autoBurnEnabled = false; emit DisabledAutoBurn(); } /** * @dev Disables the reward feature. * * Emits a {DisabledReward} event. * * Requirements: * * - reward feature mush be enabled. */ function disableReward() public onlyOwner { require(_rewardEnabled, "Reward feature is already disabled."); setTaxReward(0, 0); _rewardEnabled = false; emit DisabledReward(); } /** * @dev Disables the auto swap and liquify feature. * * Emits a {DisabledAutoSwapAndLiquify} event. * * Requirements: * * - auto swap and liquify feature mush be enabled. */ function disableAutoSwapAndLiquify() public onlyOwner { require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already disabled."); setTaxLiquify(0, 0); _autoSwapAndLiquifyEnabled = false; emit DisabledAutoSwapAndLiquify(); } /** * @dev Updates `_minTokensBeforeSwap` * * Emits a {MinTokensBeforeSwap} event. * * Requirements: * * - `minTokensBeforeSwap_` must be less than _currentSupply. */ function setMinTokensBeforeSwap(uint256 minTokensBeforeSwap_) public onlyOwner { require(minTokensBeforeSwap_ < _currentSupply, "minTokensBeforeSwap must be higher than current supply."); uint256 previous = _minTokensBeforeSwap; _minTokensBeforeSwap = minTokensBeforeSwap_; emit MinTokensBeforeSwapUpdated(previous, _minTokensBeforeSwap); } /** * @dev Updates taxBurn * * Emits a {TaxBurnUpdate} event. * * Requirements: * * - auto burn feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner { require(_autoBurnEnabled, "Auto burn feature must be enabled. Try the EnableAutoBurn function."); require(taxBurn_ + _taxReward + _taxLiquify < 100, "Tax fee too high."); uint8 previousTax = _taxBurn; uint8 previousDecimals = _taxBurnDecimals; _taxBurn = taxBurn_; _taxBurnDecimals = taxBurnDecimals_; emit TaxBurnUpdate(previousTax, previousDecimals, taxBurn_, taxBurnDecimals_); } /** * @dev Updates taxReward * * Emits a {TaxRewardUpdate} event. * * Requirements: * * - reward feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner { require(_rewardEnabled, "Reward feature must be enabled. Try the EnableReward function."); require(_taxBurn + taxReward_ + _taxLiquify < 100, "Tax fee too high."); uint8 previousTax = _taxReward; uint8 previousDecimals = _taxRewardDecimals; _taxReward = taxReward_; _taxBurnDecimals = taxRewardDecimals_; emit TaxRewardUpdate(previousTax, previousDecimals, taxReward_, taxRewardDecimals_); } /** * @dev Updates taxLiquify * * Emits a {TaxLiquifyUpdate} event. * * Requirements: * * - auto swap and liquify feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_) public onlyOwner { require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature must be enabled. Try the EnableAutoSwapAndLiquify function."); require(_taxBurn + _taxReward + taxLiquify_ < 100, "Tax fee too high."); uint8 previousTax = _taxLiquify; uint8 previousDecimals = _taxLiquifyDecimals; _taxLiquify = taxLiquify_; _taxLiquifyDecimals = taxLiquifyDecimals_; emit TaxLiquifyUpdate(previousTax, previousDecimals, taxLiquify_, taxLiquifyDecimals_); } }
Returns the threshold before swap and liquify./
function minTokensBeforeSwap() external view virtual returns (uint256) { return _minTokensBeforeSwap; }
916,774
// SPDX-License-Identifier: MIT pragma solidity ^0.6.2; library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library 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; } } library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint256) values; mapping(address => uint256) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint256) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) public view returns (int256) { if (!map.inserted[key]) { return -1; } return int256(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint256 index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint256) { return map.keys.length; } function set( Map storage map, address key, uint256 val ) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint256 index = map.indexOf[key]; uint256 lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } interface IFTPAntiBot { // Here we create the interface to interact with AntiBot function scanAddress( address _address, address _safeAddress, address _origin ) external returns (bool); function registerBlock(address _recipient, address _sender) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } interface 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 DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns (uint256); /// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0. function distributeDividends() external payable; /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed(address indexed from, uint256 weiAmount); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount, address received ); } interface DividendPayingTokenOptionalInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) external view returns (uint256); } 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 ); } 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); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } 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() public { 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; } } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _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 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 {} } contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 internal constant magnitude = 2**128; uint256 internal magnifiedDividendPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {} /// @dev Distributes dividends whenever ether is paid to this contract. receive() external payable { distributeDividends(); } /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividends() public payable override { require(totalSupply() > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (msg.value).mul(magnitude) / totalSupply() ); emit DividendsDistributed(msg.sender, msg.value); totalDividendsDistributed = totalDividendsDistributed.add( msg.value ); } } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function withdrawDividend() public virtual override { _withdrawDividendOfUser(msg.sender, msg.sender); } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function _withdrawDividendOfUser(address payable user, address payable to) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add( _withdrawableDividend ); emit DividendWithdrawn(user, _withdrawableDividend, to); (bool success, ) = to.call{value: _withdrawableDividend}(""); if (!success) { withdrawnDividends[user] = withdrawnDividends[user].sub( _withdrawableDividend ); return 0; } return _withdrawableDividend; } return 0; } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view override returns (uint256) { return withdrawableDividendOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) public view override returns (uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) public view override returns (uint256) { return withdrawnDividends[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) public view override returns (uint256) { return magnifiedDividendPerShare .mul(balanceOf(_owner)) .toInt256Safe() .add(magnifiedDividendCorrections[_owner]) .toUint256Safe() / magnitude; } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[ account ].sub((magnifiedDividendPerShare.mul(value)).toInt256Safe()); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[ account ].add((magnifiedDividendPerShare.mul(value)).toInt256Safe()); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if (newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if (newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } function getAccount(address _account) public view returns (uint256 _withdrawableDividends, uint256 _withdrawnDividends) { _withdrawableDividends = withdrawableDividendOf(_account); _withdrawnDividends = withdrawnDividends[_account]; } } contract JPOPDOGEDividendTracker is DividendPayingToken, Ownable { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; mapping(address => bool) public excludedFromDividends; uint256 public minimumTokenBalanceForDividends; event ExcludeFromDividends(address indexed account); constructor() public DividendPayingToken( "JPOPDOGE_Dividend_Tracker", "JPOPDOGE_Dividend_Tracker" ) { minimumTokenBalanceForDividends = 10000 * (10**18); //must hold 10000+ tokens } function _approve( address, address, uint256 ) internal override { require(false, "JPOPDOGE_Dividend_Tracker: No approvals allowed"); } function _transfer( address, address, uint256 ) internal override { require(false, "JPOPDOGE_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public override { require( false, "JPOPDOGE_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main JPOPDOGE contract." ); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludeFromDividends(account); } function getNumberOfTokenHolders() external view returns (uint256) { return tokenHoldersMap.keys.length; } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if (excludedFromDividends[account]) { return; } if (newBalance >= minimumTokenBalanceForDividends) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } } function processAccount(address payable account, address payable toAccount) public onlyOwner returns (uint256) { uint256 amount = _withdrawDividendOfUser(account, toAccount); return amount; } } contract JPOPDOGE is ERC20, Ownable { using SafeMath for uint256; IFTPAntiBot private antiBot; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private swapping; bool private reinvesting; bool public antibotEnabled = false; bool public maxPurchaseEnabled = true; JPOPDOGEDividendTracker public dividendTracker; address payable public devAddress = 0x6E106C8f3618D5abC69660B4d86A912c699Ad35b; uint256 public ethFee = 8; uint256 public devFee = 6; uint256 public totalFee = 14; uint256 public tradingStartTime = 1628091030; uint256 minimumTokenBalanceForDividends = 10000 * (10**18); //maximum purchase amount for initial launch uint256 maxPurchaseAmount = 5000000 * (10**18); // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; // addresses that can make transfers before presale is over mapping(address => bool) public canTransferBeforeTradingIsEnabled; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; // the last time an address transferred // used to detect if an account can be reinvest inactive funds to the vault mapping(address => uint256) public lastTransfer; event UpdateDividendTracker( address indexed newAddress, address indexed oldAddress ); event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event SendDividends(uint256 amount); event DividendClaimed( uint256 ethAmount, uint256 tokenAmount, address account ); constructor() public ERC20("JPOPDOGE", "JPOPDOGE") { IFTPAntiBot _antiBot = IFTPAntiBot( 0x590C2B20f7920A2D21eD32A21B616906b4209A43 ); antiBot = _antiBot; dividendTracker = new JPOPDOGEDividendTracker(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Create a uniswap pair for this new token address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); // exclude from receiving dividends dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); // exclude from paying fees or having max transaction amount excludeFromFees(address(this), true); excludeFromFees(owner(), true); // enable owner and fixed-sale wallet to send tokens before presales are over canTransferBeforeTradingIsEnabled[owner()] = true; _mint(owner(), 1000000000 * (10**18)); } receive() external payable {} function setTradingStartTime(uint256 newStartTime) public onlyOwner { require( tradingStartTime > block.timestamp, "Trading has already started" ); require( newStartTime > block.timestamp, "Start time must be in the future" ); tradingStartTime = newStartTime; } function updateDividendTracker(address newAddress) public onlyOwner { require( newAddress != address(dividendTracker), "JPOPDOGE: The dividend tracker already has that address" ); JPOPDOGEDividendTracker newDividendTracker = JPOPDOGEDividendTracker( payable(newAddress) ); require( newDividendTracker.owner() == address(this), "JPOPDOGE: The new dividend tracker must be owned by the JPOPDOGE token contract" ); newDividendTracker.excludeFromDividends(address(newDividendTracker)); newDividendTracker.excludeFromDividends(address(this)); newDividendTracker.excludeFromDividends(owner()); newDividendTracker.excludeFromDividends(address(uniswapV2Router)); emit UpdateDividendTracker(newAddress, address(dividendTracker)); dividendTracker = newDividendTracker; } function updateUniswapV2Router(address newAddress) public onlyOwner { require( newAddress != address(uniswapV2Router), "JPOPDOGE: The router already has that address" ); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IUniswapV2Router02(newAddress); } function excludeFromFees(address account, bool excluded) public onlyOwner { require( _isExcludedFromFees[account] != excluded, "JPOPDOGE: Account is already the value of 'excluded'" ); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function excludeMultipleAccountsFromFees( address[] memory accounts, bool excluded ) public onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "JPOPDOGE: The UniSwap pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require( automatedMarketMakerPairs[pair] != value, "JPOPDOGE: Automated market maker pair is already set to that value" ); automatedMarketMakerPairs[pair] = value; if (value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function allowPreTrading(address account, bool allowed) public onlyOwner { // used for owner and pre sale addresses require( canTransferBeforeTradingIsEnabled[account] != allowed, "JPOPDOGE: Pre trading is already the value of 'excluded'" ); canTransferBeforeTradingIsEnabled[account] = allowed; } function setMaxPurchaseEnabled(bool enabled) public onlyOwner { require( maxPurchaseEnabled != enabled, "JPOPDOGE: Max purchase enabled is already the value of 'enabled'" ); maxPurchaseEnabled = enabled; } function setMaxPurchaseAmount(uint256 newAmount) public onlyOwner { maxPurchaseAmount = newAmount; } function updateDevAddress(address payable newAddress) public onlyOwner { devAddress = newAddress; } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns (uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function reinvestInactive(address payable account) public onlyOwner { uint256 tokenBalance = dividendTracker.balanceOf(account); require( tokenBalance <= minimumTokenBalanceForDividends, "JPOPDOGE: Account balance must be less then minimum token balance for dividends" ); uint256 _lastTransfer = lastTransfer[account]; require( block.timestamp.sub(_lastTransfer) > 12 weeks, "JPOPDOGE: Account must have been inactive for at least 12 weeks" ); dividendTracker.processAccount(account, address(this)); uint256 dividends = address(this).balance; (bool success, ) = address(dividendTracker).call{value: dividends}(""); if (success) { emit SendDividends(dividends); try dividendTracker.setBalance(account, 0) {} catch {} } } function claim(bool reinvest, uint256 minTokens) external { _claim(msg.sender, reinvest, minTokens); } function _claim( address payable account, bool reinvest, uint256 minTokens ) private { uint256 withdrawableAmount = dividendTracker.withdrawableDividendOf( account ); require( withdrawableAmount > 0, "JPOPDOGE: Claimer has no withdrawable dividend" ); if (!reinvest) { uint256 ethAmount = dividendTracker.processAccount( account, account ); if (ethAmount > 0) { emit DividendClaimed(ethAmount, 0, account); } return; } uint256 ethAmount = dividendTracker.processAccount( account, address(this) ); if (ethAmount > 0) { reinvesting = true; uint256 tokenAmount = swapEthForTokens( ethAmount, minTokens, account ); reinvesting = false; emit DividendClaimed(ethAmount, tokenAmount, account); } } function getNumberOfDividendTokenHolders() external view returns (uint256) { return dividendTracker.getNumberOfTokenHolders(); } function getAccount(address _account) public view returns ( uint256 withdrawableDividends, uint256 withdrawnDividends, uint256 balance ) { (withdrawableDividends, withdrawnDividends) = dividendTracker .getAccount(_account); return (withdrawableDividends, withdrawnDividends, balanceOf(_account)); } 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"); // address must be permitted to transfer before tradingStartTime if (tradingStartTime > block.timestamp) { require( canTransferBeforeTradingIsEnabled[from], "JPOPDOGE: This account cannot send tokens until trading is enabled" ); } if (amount == 0) { super._transfer(from, to, 0); return; } if (antibotEnabled) { if (automatedMarketMakerPairs[from]) { require( !antiBot.scanAddress(to, from, tx.origin), "Beep Beep Boop, You're a piece of poop" ); } if (automatedMarketMakerPairs[to]) { require( !antiBot.scanAddress(from, to, tx.origin), "Beep Beep Boop, You're a piece of poop" ); } } // make sure amount does not exceed max on a purchase if (maxPurchaseEnabled && automatedMarketMakerPairs[from]) { require( amount <= maxPurchaseAmount, "JPOPDOGE: Exceeds max purchase amount" ); } if ( !swapping && !reinvesting && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapAndDistribute(); swapping = false; } bool takeFee = !swapping && !reinvesting; // if any account belongs to _isExcludedFromFee account then remove the fee // don't take a fee unless it's a buy / sell if ( (_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to]) ) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(totalFee).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {} if (antibotEnabled) { try antiBot.registerBlock(from, to) {} catch {} } lastTransfer[from] = block.timestamp; lastTransfer[to] = block.timestamp; } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function swapEthForTokens( uint256 ethAmount, uint256 minTokens, address account ) internal returns (uint256) { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); uint256 balanceBefore = balanceOf(account); uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: ethAmount }(minTokens, path, account, block.timestamp); uint256 tokenAmount = balanceOf(account).sub(balanceBefore); return tokenAmount; } function swapAndDistribute() private { uint256 tokenBalance = balanceOf(address(this)); swapTokensForEth(tokenBalance); uint256 ethBalance = address(this).balance; uint256 devPortion = ethBalance.mul(devFee).div(totalFee); devAddress.transfer(devPortion); uint256 dividends = address(this).balance; (bool success, ) = address(dividendTracker).call{value: dividends}(""); if (success) { emit SendDividends(dividends); } } function assignAntiBot(address _address) external onlyOwner { IFTPAntiBot _antiBot = IFTPAntiBot(_address); antiBot = _antiBot; } function toggleAntiBot() external onlyOwner { if (antibotEnabled) { antibotEnabled = false; } else { antibotEnabled = true; } } function getDay() internal view returns (uint256) { return block.timestamp.div(1 days); } }
Withdraws the ether distributed to the sender. It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user, address payable to) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add( _withdrawableDividend ); emit DividendWithdrawn(user, _withdrawableDividend, to); if (!success) { withdrawnDividends[user] = withdrawnDividends[user].sub( _withdrawableDividend ); return 0; } return _withdrawableDividend; } return 0; }
414,373
./full_match/7700/0xe9F857be65E73c0bc86BCbb35cA8aFAB4d70e178/sources/contracts/StrategyY2R.sol
Withdraw what we can from Scream
function withdrawPartialFromScream(uint256 _amountUnderlying) external onlyManager { require(balanceOfPool() >= _amountUnderlying, "more than our Scream balance"); uint256 wantBal = IERC20(want).balanceOf(pool); require(wantBal >= _amountUnderlying, "not enough in Scream"); ICantoLP(pool).redeemUnderlying(_amountUnderlying); }
4,654,515
/** *Submitted for verification at Etherscan.io on 2021-05-07 */ // Sources flattened with hardhat v2.2.1 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract 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; } } // File @openzeppelin/contracts/GSN/[email protected] pragma solidity >=0.6.0 <0.8.0; // File @openzeppelin/contracts/introspection/[email protected] pragma solidity >=0.6.0 <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/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, basic interface * @dev See https://eips.ethereum.org/EIPS/eip-20 * Note: The ERC-165 identifier for this interface is 0x36372b07. */ interface IERC20 { /** * @dev Emitted when tokens are transferred, including zero value transfers. * @param _from The account where the transferred tokens are withdrawn from. * @param _to The account where the transferred tokens are deposited to. * @param _value The amount of tokens being transferred. */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev Emitted when a successful call to {IERC20-approve(address,uint256)} is made. * @param _owner The account granting an allowance to `_spender`. * @param _spender The account being granted an allowance from `_owner`. * @param _value The allowance amount being granted. */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @notice Returns the total token supply. * @return The total token supply. */ function totalSupply() external view returns (uint256); /** * @notice Returns the account balance of another account with address `owner`. * @param owner The account whose balance will be returned. * @return The account balance of another account with address `owner`. */ function balanceOf(address owner) external view returns (uint256); /** * @notice Transfers `value` amount of tokens to address `to`. * @dev Reverts if the message caller's account balance does not have enough tokens to spend. * @dev Emits an {IERC20-Transfer} event. * @dev Transfers of 0 values are treated as normal transfers and fire the {IERC20-Transfer} event. * @param to The account where the transferred tokens will be deposited to. * @param value The amount of tokens to transfer. * @return True if the transfer succeeds, false otherwise. */ function transfer(address to, uint256 value) external returns (bool); /** * @notice Transfers `value` amount of tokens from address `from` to address `to` via the approval mechanism. * @dev Reverts if the caller has not been approved by `from` for at least `value`. * @dev Reverts if `from` does not have at least `value` of balance. * @dev Emits an {IERC20-Transfer} event. * @dev Transfers of 0 values are treated as normal transfers and fire the {IERC20-Transfer} event. * @param from The account where the transferred tokens will be withdrawn from. * @param to The account where the transferred tokens will be deposited to. * @param value The amount of tokens to transfer. * @return True if the transfer succeeds, false otherwise. */ function transferFrom( address from, address to, uint256 value ) external returns (bool); /** * Sets `value` as the allowance from the caller to `spender`. * 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 * @dev Reverts if `spender` is the zero address. * @dev Emits the {IERC20-Approval} event. * @param spender The account being granted the allowance by the message caller. * @param value The allowance amount to grant. * @return True if the approval succeeds, false otherwise. */ function approve(address spender, uint256 value) external returns (bool); /** * Returns the amount which `spender` is allowed to spend on behalf of `owner`. * @param owner The account that has granted an allowance to `spender`. * @param spender The account that was granted an allowance by `owner`. * @return The amount which `spender` is allowed to spend on behalf of `owner`. */ function allowance(address owner, address spender) external view returns (uint256); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, optional extension: Detailed * See https://eips.ethereum.org/EIPS/eip-20 * Note: the ERC-165 identifier for this interface is 0xa219a025. */ interface IERC20Detailed { /** * Returns the name of the token. E.g. "My Token". * Note: the ERC-165 identifier for this interface is 0x06fdde03. * @return The name of the token. */ function name() external view returns (string memory); /** * Returns the symbol of the token. E.g. "HIX". * Note: the ERC-165 identifier for this interface is 0x95d89b41. * @return The symbol of the token. */ function symbol() external view returns (string memory); /** * Returns the number of decimals used to display the balances. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract. * Note: the ERC-165 identifier for this interface is 0x313ce567. * @return The number of decimals used to display the balances. */ function decimals() external view returns (uint8); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, optional extension: Allowance * See https://eips.ethereum.org/EIPS/eip-20 * Note: the ERC-165 identifier for this interface is 0xd5b86388. */ interface IERC20Allowance { /** * Increases the allowance granted by the sender to `spender` by `value`. * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * @dev Reverts if `spender` is the zero address. * @dev Reverts if `spender`'s allowance overflows. * @dev Emits an {IERC20-Approval} event with an updated allowance for `spender`. * @param spender The account whose allowance is being increased by the message caller. * @param value The allowance amount increase. * @return True if the allowance increase succeeds, false otherwise. */ function increaseAllowance(address spender, uint256 value) external returns (bool); /** * Decreases the allowance granted by the sender to `spender` by `value`. * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * @dev Reverts if `spender` is the zero address. * @dev Reverts if `spender` has an allowance with the message caller for less than `value`. * @dev Emits an {IERC20-Approval} event with an updated allowance for `spender`. * @param spender The account whose allowance is being decreased by the message caller. * @param value The allowance amount decrease. * @return True if the allowance decrease succeeds, false otherwise. */ function decreaseAllowance(address spender, uint256 value) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, optional extension: Safe Transfers * Note: the ERC-165 identifier for this interface is 0x53f41a97. */ interface IERC20SafeTransfers { /** * Transfers tokens from the caller to `to`. If this address is a contract, then calls `onERC20Received(address,address,uint256,bytes)` on it. * @dev Reverts if `to` is the zero address. * @dev Reverts if `value` is greater than the sender's balance. * @dev Reverts if `to` is a contract which does not implement `onERC20Received(address,address,uint256,bytes)`. * @dev Reverts if `to` is a contract and the call to `onERC20Received(address,address,uint256,bytes)` returns a wrong value. * @dev Emits an {IERC20-Transfer} event. * @param to The address for the tokens to be transferred to. * @param amount The amount of tokens to be transferred. * @param data Optional additional data with no specified format, to be passed to the receiver contract. * @return true. */ function safeTransfer( address to, uint256 amount, bytes calldata data ) external returns (bool); /** * Transfers tokens from `from` to another address, using the allowance mechanism. * If this address is a contract, then calls `onERC20Received(address,address,uint256,bytes)` on it. * @dev Reverts if `to` is the zero address. * @dev Reverts if `value` is greater than `from`'s balance. * @dev Reverts if the sender does not have at least `value` allowance by `from`. * @dev Reverts if `to` is a contract which does not implement `onERC20Received(address,address,uint256,bytes)`. * @dev Reverts if `to` is a contract and the call to `onERC20Received(address,address,uint256,bytes)` returns a wrong value. * @dev Emits an {IERC20-Transfer} event. * @param from The address which owns the tokens to be transferred. * @param to The address for the tokens to be transferred to. * @param amount The amount of tokens to be transferred. * @param data Optional additional data with no specified format, to be passed to the receiver contract. * @return true. */ function safeTransferFrom( address from, address to, uint256 amount, bytes calldata data ) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, optional extension: Multi Transfers * Note: the ERC-165 identifier for this interface is 0xd5b86388. */ interface IERC20MultiTransfers { /** * Moves multiple `amounts` tokens from the caller's account to each of `recipients`. * @dev Reverts if `recipients` and `amounts` have different lengths. * @dev Reverts if one of `recipients` is the zero address. * @dev Reverts if the caller has an insufficient balance. * @dev Emits an {IERC20-Transfer} event for each individual transfer. * @param recipients the list of recipients to transfer the tokens to. * @param amounts the amounts of tokens to transfer to each of `recipients`. * @return a boolean value indicating whether the operation succeeded. */ function multiTransfer(address[] calldata recipients, uint256[] calldata amounts) external returns (bool); /** * Moves multiple `amounts` tokens from an account to each of `recipients`, using the approval mechanism. * @dev Reverts if `recipients` and `amounts` have different lengths. * @dev Reverts if one of `recipients` is the zero address. * @dev Reverts if `from` has an insufficient balance. * @dev Reverts if the sender does not have at least the sum of all `amounts` as allowance by `from`. * @dev Emits an {IERC20-Transfer} event for each individual transfer. * @dev Emits an {IERC20-Approval} event. * @param from The address which owns the tokens to be transferred. * @param recipients the list of recipients to transfer the tokens to. * @param amounts the amounts of tokens to transfer to each of `recipients`. * @return a boolean value indicating whether the operation succeeded. */ function multiTransferFrom( address from, address[] calldata recipients, uint256[] calldata amounts ) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, ERC1046 optional extension: Metadata * See https://eips.ethereum.org/EIPS/eip-1046 * Note: the ERC-165 identifier for this interface is 0x3c130d90. */ interface IERC20Metadata { /** * Returns a distinct Uniform Resource Identifier (URI) for the token metadata. * @return a distinct Uniform Resource Identifier (URI) for the token metadata. */ function tokenURI() external view returns (string memory); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, ERC2612 optional extension: permit – 712-signed approvals * @dev Interface for allowing ERC20 approvals to be made via ECDSA `secp256k1` signatures. * See https://eips.ethereum.org/EIPS/eip-2612 * Note: the ERC-165 identifier for this interface is 0x9d8ff7da. */ interface IERC20Permit { /** * Sets `value` as the allowance of `spender` over the tokens of `owner`, given `owner` account's signed permit. * @dev WARNING: The standard ERC-20 race condition for approvals applies to `permit()` as well: https://swcregistry.io/docs/SWC-114 * @dev Reverts if `owner` is the zero address. * @dev Reverts if the current blocktime is > `deadline`. * @dev Reverts if `r`, `s`, and `v` is not a valid `secp256k1` signature from `owner`. * @dev Emits an {IERC20-Approval} event. * @param owner The token owner granting the allowance to `spender`. * @param spender The token spender being granted the allowance by `owner`. * @param value The token amount of the allowance. * @param deadline The deadline from which the permit signature is no longer valid. * @param v Permit signature v parameter * @param r Permit signature r parameter. * @param s Permis signature s parameter. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * Returns the current permit nonce of `owner`. * @param owner the address to check the nonce of. * @return the current permit nonce of `owner`. */ function nonces(address owner) external view returns (uint256); /** * Returns the EIP-712 encoded hash struct of the domain-specific information for permits. * * @dev A common ERC-20 permit implementation choice for the `DOMAIN_SEPARATOR` is: * * keccak256( * abi.encode( * keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), * keccak256(bytes(name)), * keccak256(bytes(version)), * chainId, * address(this))) * * where * - `name` (string) is the ERC-20 token name. * - `version` (string) refers to the ERC-20 token contract version. * - `chainId` (uint256) is the chain ID to which the ERC-20 token contract is deployed to. * - `verifyingContract` (address) is the ERC-20 token contract address. * * @return the EIP-712 encoded hash struct of the domain-specific information for permits. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, Receiver * See https://eips.ethereum.org/EIPS/eip-20 * Note: the ERC-165 identifier for this interface is 0x4fc35859. */ interface IERC20Receiver { /** * Handles the receipt of ERC20 tokens. * @param sender The initiator of the transfer. * @param from The address which transferred the tokens. * @param value The amount of tokens transferred. * @param data Optional additional data with no specified format. * @return bytes4 `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))` */ function onERC20Received( address sender, address from, uint256 value, bytes calldata data ) external returns (bytes4); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @dev Implementation of the {IERC20} interface. */ contract ERC20 is IERC165, Context, IERC20, IERC20Detailed, IERC20Metadata, IERC20Allowance, IERC20MultiTransfers, IERC20SafeTransfers, IERC20Permit { using Address for address; // bytes4(keccak256("onERC20Received(address,address,uint256,bytes)")) bytes4 internal constant _ERC20_RECEIVED = 0x4fc35859; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 internal constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; // solhint-disable-next-line var-name-mixedcase bytes32 public immutable override DOMAIN_SEPARATOR; mapping(address => uint256) public override nonces; string internal _name; string internal _symbol; uint8 internal immutable _decimals; string internal _tokenURI; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 internal _totalSupply; constructor( string memory name, string memory symbol, uint8 decimals, string memory version, string memory tokenURI ) internal { _name = name; _symbol = symbol; _decimals = decimals; _tokenURI = tokenURI; uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /////////////////////////////////////////// ERC165 /////////////////////////////////////// /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId || interfaceId == type(IERC20).interfaceId || interfaceId == type(IERC20Detailed).interfaceId || interfaceId == 0x06fdde03 || // bytes4(keccak256("name()")) interfaceId == 0x95d89b41 || // bytes4(keccak256("symbol()")) interfaceId == 0x313ce567 || // bytes4(keccak256("decimals()")) interfaceId == type(IERC20Metadata).interfaceId || interfaceId == type(IERC20Allowance).interfaceId || interfaceId == type(IERC20MultiTransfers).interfaceId || interfaceId == type(IERC20SafeTransfers).interfaceId || interfaceId == type(IERC20Permit).interfaceId; } /////////////////////////////////////////// ERC20Detailed /////////////////////////////////////// /// @dev See {IERC20Detailed-name}. function name() public view override returns (string memory) { return _name; } /// @dev See {IERC20Detailed-symbol}. function symbol() public view override returns (string memory) { return _symbol; } /// @dev See {IERC20Detailed-decimals}. function decimals() public view override returns (uint8) { return _decimals; } /////////////////////////////////////////// ERC20Metadata /////////////////////////////////////// /// @dev See {IERC20Metadata-tokenURI}. function tokenURI() public view override returns (string memory) { return _tokenURI; } /////////////////////////////////////////// ERC20 /////////////////////////////////////// /// @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-allowance}. function allowance(address owner, address spender) public view virtual override returns (uint256) { if (owner == spender) { return type(uint256).max; } return _allowances[owner][spender]; } /// @dev See {IERC20-approve}. function approve(address spender, uint256 value) public virtual override returns (bool) { _approve(_msgSender(), spender, value); return true; } /////////////////////////////////////////// ERC20 Allowance /////////////////////////////////////// /// @dev See {IERC20Allowance-increaseAllowance}. function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { require(spender != address(0), "ERC20: zero address"); address owner = _msgSender(); uint256 allowance_ = _allowances[owner][spender]; uint256 newAllowance = allowance_ + addedValue; require(newAllowance >= allowance_, "ERC20: allowance overflow"); _allowances[owner][spender] = newAllowance; emit Approval(owner, spender, newAllowance); return true; } /// @dev See {IERC20Allowance-decreaseAllowance}. function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { require(spender != address(0), "ERC20: zero address"); _decreaseAllowance(_msgSender(), spender, subtractedValue); return true; } /// @dev See {IERC20-transfer}. function transfer(address to, uint256 value) public virtual override returns (bool) { _transfer(_msgSender(), to, value); return true; } /// @dev See {IERC20-transferFrom}. function transferFrom( address from, address to, uint256 value ) public virtual override returns (bool) { _transferFrom(_msgSender(), from, to, value); return true; } /////////////////////////////////////////// ERC20MultiTransfer /////////////////////////////////////// /// @dev See {IERC20MultiTransfer-multiTransfer(address[],uint256[])}. function multiTransfer(address[] calldata recipients, uint256[] calldata amounts) external virtual override returns (bool) { uint256 length = recipients.length; require(length == amounts.length, "ERC20: inconsistent arrays"); address sender = _msgSender(); for (uint256 i = 0; i != length; ++i) { _transfer(sender, recipients[i], amounts[i]); } return true; } /// @dev See {IERC20MultiTransfer-multiTransferFrom(address,address[],uint256[])}. function multiTransferFrom( address from, address[] calldata recipients, uint256[] calldata values ) external virtual override returns (bool) { uint256 length = recipients.length; require(length == values.length, "ERC20: inconsistent arrays"); uint256 total; for (uint256 i = 0; i != length; ++i) { uint256 value = values[i]; _transfer(from, recipients[i], value); total += value; // cannot overflow, else it would mean thann from's balance underflowed first } _decreaseAllowance(from, _msgSender(), total); return true; } /////////////////////////////////////////// ERC20SafeTransfers /////////////////////////////////////// /// @dev See {IERC20Safe-safeTransfer(address,uint256,bytes)}. function safeTransfer( address to, uint256 amount, bytes calldata data ) external virtual override returns (bool) { address sender = _msgSender(); _transfer(sender, to, amount); if (to.isContract()) { require(IERC20Receiver(to).onERC20Received(sender, sender, amount, data) == _ERC20_RECEIVED, "ERC20: transfer refused"); } return true; } /// @dev See {IERC20Safe-safeTransferFrom(address,address,uint256,bytes)}. function safeTransferFrom( address from, address to, uint256 amount, bytes calldata data ) external virtual override returns (bool) { address sender = _msgSender(); _transferFrom(sender, from, to, amount); if (to.isContract()) { require(IERC20Receiver(to).onERC20Received(sender, from, amount, data) == _ERC20_RECEIVED, "ERC20: transfer refused"); } return true; } /////////////////////////////////////////// ERC20Permit /////////////////////////////////////// /// @dev See {IERC2612-permit(address,address,uint256,uint256,uint8,bytes32,bytes32)}. function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual override { require(owner != address(0), "ERC20: zero address owner"); require(block.timestamp <= deadline, "ERC20: expired permit"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); bytes32 hash = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(hash, v, r, s); require(signer != address(0) && signer == owner, "ERC20: invalid permit"); _approve(owner, spender, value); } /////////////////////////////////////////// Internal Functions /////////////////////////////////////// function _approve( address owner, address spender, uint256 value ) internal { require(spender != address(0), "ERC20: zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _decreaseAllowance( address owner, address spender, uint256 subtractedValue ) internal { if (owner == spender) return; uint256 allowance_ = _allowances[owner][spender]; if (allowance_ != type(uint256).max && subtractedValue != 0) { // save gas when allowance is maximal by not reducing it (see https://github.com/ethereum/EIPs/issues/717) uint256 newAllowance = allowance_ - subtractedValue; require(newAllowance <= allowance_, "ERC20: insufficient allowance"); _allowances[owner][spender] = newAllowance; allowance_ = newAllowance; } emit Approval(owner, spender, allowance_); } function _transfer( address from, address to, uint256 value ) internal virtual { require(to != address(0), "ERC20: zero address"); uint256 balance = _balances[from]; require(balance >= value, "ERC20: insufficient balance"); _balances[from] = balance - value; _balances[to] += value; emit Transfer(from, to, value); } function _transferFrom( address sender, address from, address to, uint256 value ) internal { _decreaseAllowance(from, sender, value); _transfer(from, to, value); } function _mint(address to, uint256 value) internal virtual { require(to != address(0), "ERC20: zero address"); uint256 supply = _totalSupply; uint256 newSupply = supply + value; require(newSupply >= supply, "ERC20: supply overflow"); _totalSupply = newSupply; _balances[to] += value; // balance cannot overflow if supply does not emit Transfer(address(0), to, value); } function _batchMint(address[] memory recipients, uint256[] memory values) internal virtual { uint256 length = recipients.length; require(length == values.length, "ERC20: inconsistent arrays"); uint256 supply = _totalSupply; for (uint256 i = 0; i != length; ++i) { address to = recipients[i]; require(to != address(0), "ERC20: zero address"); uint256 value = values[i]; uint256 newSupply = supply + value; require(newSupply >= supply, "ERC20: supply overflow"); supply = newSupply; _balances[to] += value; // balance cannot overflow if supply does not emit Transfer(address(0), to, value); } _totalSupply = supply; } function _burn(address from, uint256 value) internal virtual { uint256 balance = _balances[from]; require(balance >= value, "ERC20: insufficient balance"); _balances[from] = balance - value; _totalSupply -= value; // will not underflow if balance does not emit Transfer(from, address(0), value); } function _burnFrom(address from, uint256 value) internal virtual { _decreaseAllowance(from, _msgSender(), value); _burn(from, value); } } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, optional extension: Burnable * Note: the ERC-165 identifier for this interface is 0x3b5a0bf8. */ interface IERC20Burnable { /** * Burns `value` tokens from the message sender, decreasing the total supply. * @dev Reverts if the sender owns less than `value` tokens. * @dev Emits a {IERC20-Transfer} event with `_to` set to the zero address. * @param value the amount of tokens to burn. * @return a boolean value indicating whether the operation succeeded. */ function burn(uint256 value) external returns (bool); /** * Burns `value` tokens from `from`, using the allowance mechanism and decreasing the total supply. * @dev Reverts if `from` owns less than `value` tokens. * @dev Reverts if the message sender is not approved by `from` for at least `value` tokens. * @dev Emits a {IERC20-Transfer} event with `_to` set to the zero address. * @dev Emits a {IERC20-Approval} event (non-standard). * @param from the account to burn the tokens from. * @param value the amount of tokens to burn. * @return a boolean value indicating whether the operation succeeded. */ function burnFrom(address from, uint256 value) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Fungible Token Contract, burnable version. */ contract ERC20Burnable is ERC20, IERC20Burnable { constructor( string memory name, string memory symbol, uint8 decimals, string memory version, string memory tokenURI ) public ERC20(name, symbol, decimals, version, tokenURI) {} /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC20Burnable).interfaceId || super.supportsInterface(interfaceId); } /// @dev See {IERC20Burnable-burn(uint256)}. function burn(uint256 amount) public virtual override returns (bool) { _burn(_msgSender(), amount); return true; } /// @dev See {IERC20Burnable-burnFrom(address,uint256)}. function burnFrom(address from, uint256 value) public virtual override returns (bool) { _burnFrom(from, value); return true; } } // File contracts/solc-0.6/token/ERC20/TOWERChest.sol pragma solidity 0.6.8; /** * @title TOWERChest * A burnable ERC-20 token contract for Crazy Defense Heroes (CDH). TOWER Chests are tokens that can be burned to obtain CDH NFTs. * @dev TWR.BRNZ for Bronze chests. * @dev TWR.SLVR for Silver chests. * @dev TWR.GOLD for Gold chests. */ contract TOWERChest is ERC20Burnable, Ownable { /** * Constructor. * @param name Name of the token. * @param symbol Symbol of the token. * @param decimals Number of decimals the token uses. * @param version Signing domain version used for IERC2612 permit signatures. * @param tokenURI The URI for the token metadata. * @param holder Account to mint the initial total supply to. * @param totalSupply Total supply amount to mint to the message caller. */ constructor( string memory name, string memory symbol, uint8 decimals, string memory version, string memory tokenURI, address holder, uint256 totalSupply ) public ERC20Burnable(name, symbol, decimals, version, tokenURI) { _mint(holder, totalSupply); } /** * Updates the token metadata URI. * @dev Reverts if the sender is not the contract owner. * @param tokenURI_ the new token metdata URI. */ function updateTokenURI(string calldata tokenURI_) external { require(_msgSender() == owner(), "TOWERChest: not the owner"); _tokenURI = tokenURI_; } }
ERC20 Token Standard, optional extension: Burnable Note: the ERC-165 identifier for this interface is 0x3b5a0bf8./
interface IERC20Burnable { function burn(uint256 value) external returns (bool); function burnFrom(address from, uint256 value) external returns (bool); }
7,831,915
// File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/AccessControl.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: @openzeppelin/contracts/utils/Pausable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // File: @openzeppelin/contracts/math/Math.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/utils/Arrays.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // File: @openzeppelin/contracts/utils/Counters.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // 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); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } // File: contracts/BUX.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev BUX token, including: * * - ability for holders to burn (destroy) their tokens * - ability admin to take snapshot at any moment * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - a freezer role that allows to freeze all token of an address to be transfered * * 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, pauser and freezer * roles, as well as the default admin role, which will let it grant both minter, pauser * and freezer roles to other accounts. */ contract BUX is Context, AccessControl, ERC20Burnable, ERC20Pausable, ERC20Snapshot { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant FREEZER_ROLE = keccak256("FREEZER_ROLE"); string constant TOKEN_NAME = 'Privi Bux'; string constant TOKEN_SYMBOL = 'BUX'; uint256 public currentCap; mapping (address => bool) public freezed; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, `PAUSER_ROLE` and `FREEZER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor() public ERC20(TOKEN_NAME, TOKEN_SYMBOL) { // setting current Cap currentCap = 100000000000000000000000000; // setting initial roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(FREEZER_ROLE, _msgSender()); } /** * @dev Function to set a new Cap for the token. * @param newCap new cap to be set. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setCap(uint256 newCap) public { require(totalSupply() <= newCap, "BUX: hard Cap is lower than current total supply"); require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "BUX: must be Admin to set hard cap"); currentCap = newCap; } /** * @dev Function to freeze a specific address's circulation for emergency. * @param addresToFreeze The address to freeze * * Requirements: * * - the caller must have the `FREEZER_ROLE`. */ function freeze(address addresToFreeze) public { require(hasRole(FREEZER_ROLE, _msgSender()), "BUX: must have freezer role to freeze"); freezed[addresToFreeze] = true; } /** * @dev Function to recover a specific address's circulation from emergency. * @param freezedAddress The address to recover * * Requirements: * * - the caller must have the `FREEZER_ROLE`. */ function unfreeze(address freezedAddress) public { require(hasRole(FREEZER_ROLE, _msgSender()), "BUX: must have freezer role to unfreeze"); freezed[freezedAddress] = false; } /** * @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()), "BUX: 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()), "BUX: 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()), "BUX: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable, ERC20Snapshot) { super._beforeTokenTransfer(from, to, amount); require(!freezed[from] && !freezed[to], "BUX: origin or target address is freezed"); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= currentCap, "BUX: cap exceeded"); } } }
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()), "BUX: must have pauser role to pause"); _pause(); }
1,141,986
./full_match/5/0x83ee8124430BB5e62aDb09CDe8D3360A4bF45d2D/sources/contracts/lc.sol
once the bar is opened to the public, it can't be opened again
function setBarStatus(bool _isOpen, bool _isPublic) external onlyOwner { require(gameStartBlock == 0, "The bar cannot be opened again"); barIsOpen = _isOpen; if (_isPublic) { gameStartBlock = block.number; } if (_isOpen) { _resetTimer(); } }
11,619,652
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); } }
Vote on a given proposal (onlyMember) _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; }
23,709
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./IcoToken.sol"; /// @title /// @author /// @dev contract IcoContract is Ownable { using Address for address payable; IcoToken private _token; uint256 private _end; uint256 private _DURATION = 14 days; event Purchase(address indexed buyer, uint256 amount); event Withdrew(address indexed owner, uint256 amount); /// @dev Set the ERC20 address and start the ICO for 14 days. /// @param tokenAddress Set the address of the ERC20. constructor(address tokenAddress) { _token = IcoToken(tokenAddress); require(_token.balanceOf(_token.owner()) == 1000000 * 10**18, "ICO: The owner must have token for exchange"); _end = block.timestamp + _DURATION; } /// @dev Use to receive ether directly from a transaction receive() external payable { _buyTokens(msg.sender, msg.value); } /// @dev Use withdraw function when ICO date finished function withdraw() public onlyOwner { require(block.timestamp >= _end, "ICO: you need to wait 14 days from the deployment of this contract"); uint256 gain = address(this).balance; payable(msg.sender).sendValue(address(this).balance); emit Withdrew(msg.sender, gain); } /// @dev Use to buy platform Ether function buyTokens() public payable { _buyTokens(msg.sender, msg.value); } /// @dev Exchange rate /// @param amount = Ether /// @return value function conversion(uint256 amount) public pure returns (uint256) { return amount * 10**9; } /// @dev Total Ether this ICO function total() public view returns (uint256) { return address(this).balance; } /// @dev ICO is finished /// @return Time left before the end ICO function timeLeft() public view returns (uint256) { require(block.timestamp < _end, "ICO: there is no time left"); return _end - block.timestamp; } /// @dev allows investors to buy tokens /// @param sender : The investors /// @param amount = Ether function _buyTokens(address sender, uint256 amount) private { require(block.timestamp < _end, "ICO: 14 days have passed, you can not buy token"); uint256 allowance = _token.allowance(_token.owner(), address(this)); require(allowance > 0, "ICO: You have not approved because all token are already sold"); uint256 token = conversion(amount); if (token > allowance) { uint256 rest = token - allowance; token -= rest; payable(sender).sendValue(rest / 10**9); } _token.transferFrom(_token.owner(), sender, token); emit Purchase(sender, amount); } }
allows investors to buy tokens sender : The investors amount = Ether
function _buyTokens(address sender, uint256 amount) private { require(block.timestamp < _end, "ICO: 14 days have passed, you can not buy token"); uint256 allowance = _token.allowance(_token.owner(), address(this)); require(allowance > 0, "ICO: You have not approved because all token are already sold"); uint256 token = conversion(amount); if (token > allowance) { uint256 rest = token - allowance; token -= rest; payable(sender).sendValue(rest / 10**9); } _token.transferFrom(_token.owner(), sender, token); emit Purchase(sender, amount); }
7,276,741
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.10; import "../types/ExodusAccessControlled.sol"; import "../interfaces/IERC20.sol"; abstract contract FrontEndRewarder is ExodusAccessControlled { /* ========= STATE VARIABLES ========== */ uint256 public daoReward; // % reward for dao (3 decimals: 100 = 1%) uint256 public refReward; // % reward for referrer (3 decimals: 100 = 1%) mapping(address => uint256) public rewards; // front end operator rewards mapping(address => bool) public whitelisted; // whitelisted status for operators IERC20 internal immutable exo; // reward token constructor(IExodusAuthority _authority, IERC20 _exo) ExodusAccessControlled(_authority) { exo = _exo; } /* ========= EXTERNAL FUNCTIONS ========== */ // pay reward to front end operator function getReward() external { uint256 reward = rewards[msg.sender]; rewards[msg.sender] = 0; exo.transfer(msg.sender, reward); } /* ========= INTERNAL ========== */ /** * @notice add new market payout to user data */ function _giveRewards(uint256 _payout, address _referral) internal returns (uint256) { // first we calculate rewards paid to the DAO and to the front end operator (referrer) uint256 toDAO = (_payout * daoReward) / 1e4; uint256 toRef = (_payout * refReward) / 1e4; // and store them in our rewards mapping if (whitelisted[_referral]) { rewards[_referral] += toRef; rewards[authority.guardian()] += toDAO; } else { // the DAO receives both rewards if referrer is not whitelisted rewards[authority.guardian()] += toDAO + toRef; } return toDAO + toRef; } /** * @notice set rewards for front end operators and DAO */ function setRewards(uint256 _toFrontEnd, uint256 _toDAO) external onlyGovernor { refReward = _toFrontEnd; daoReward = _toDAO; } /** * @notice add or remove addresses from the reward whitelist */ function whitelist(address _operator) external onlyPolicy { whitelisted[_operator] = !whitelisted[_operator]; } }
add new market payout to user data/ first we calculate rewards paid to the DAO and to the front end operator (referrer) and store them in our rewards mapping the DAO receives both rewards if referrer is not whitelisted
function _giveRewards(uint256 _payout, address _referral) internal returns (uint256) { uint256 toDAO = (_payout * daoReward) / 1e4; uint256 toRef = (_payout * refReward) / 1e4; if (whitelisted[_referral]) { rewards[_referral] += toRef; rewards[authority.guardian()] += toDAO; rewards[authority.guardian()] += toDAO + toRef; } return toDAO + toRef; }
6,404,658
// Dependency file: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Dependency file: @openzeppelin/contracts/utils/EnumerableSet.sol // pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // Root file: contracts/MasterGame.sol pragma solidity ^0.6.12; // import "@openzeppelin/contracts/access/Ownable.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /** * @dev Ticket contract interface */ interface ITicketsToken is IERC20 { function burnFromUsdt(address account, uint256 usdtAmount) external; function vendingAndBurn(address account, uint256 amount) external; function price() external returns (uint256); function totalVending() external returns (uint256); } /** * @dev Master contract */ contract MasterGame is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; IERC20 usdt; uint256 constant usdter = 1e6; // Creation time uint256 public createdAt; // Total revenue uint256 public totalRevenue; // Ticket contract ITicketsToken ticket; // Static income cycle: 1 day uint256 constant STATIC_CYCLE = 1 days; // Daily prize pool cycle: 1 day uint256 constant DAY_POOL_CYCLE = 1 days; // Weekly prize pool cycle: 7 days uint256 constant WEEK_POOL_CYCLE = 7 days; // Upgrade node discount: 100 days uint256 constant NODE_DISCOUNT_TIME = 100 days; // Static rate of return, parts per thousand uint256 staticRate = 5; // Dynamic rate of return, parts per thousand uint256[12] dynamicRates = [ 100, 80, 60, 50, 50, 60, 70, 50, 50, 50, 60, 80 ]; // Technology founding team uint256 public founder; // Market value management fee uint256 public operation; // Insurance pool uint256 public insurance; // Perpetual capital pool uint256 public sustainable; // Dex Market making uint256 public dex; // Account ID uint256 public id; // Number of people activating Pa Point uint8 public nodeBurnNumber; // Account data mapping(address => Account) public accounts; mapping(address => AccountCount) public stats; // Node burn data mapping(address => AccountNodeBurn) public burns; // Team data mapping(address => AccountPerformance) public performances; mapping(address => address[]) public teams; // Node data // 1 Light node; 2 Intermediate node; 3 Super node; 4 Genesis node mapping(uint8 => address[]) public nodes; // Weekly prize pool uint64 public weekPoolId; mapping(uint64 => Pool) public weekPool; // Daily prize pool uint64 public dayPoolId; mapping(uint64 => Pool) public dayPool; // Address with a deposit of 15,000 or more EnumerableSet.AddressSet private richman; // Account struct Account { uint256 id; address referrer; // Direct push bool reinvest; // Whether to reinvest uint8 nodeLevel; // Node level uint256 joinTime; // Join time: This value needs to be updated when joining again uint256 lastTakeTime; // Last time the static income was received uint256 deposit; // Deposited quantity: 0 means "out" uint256 nodeIncome; // Node revenue balance uint256 dayPoolIncome; // Daily bonus pool income balance uint256 weekPoolIncome; // Weekly bonus pool income balance uint256 dynamicIncome; // Dynamic income balance uint256 income; // Total revenue uint256 maxIncome; // Exit condition uint256 reward; // Additional other rewards } // Account statistics struct AccountCount { uint256 income; // Total revenue uint256 investment; // Total investment } // Performance struct AccountPerformance { uint256 performance; // Direct performance uint256 wholeLine; // Performance of all layers below } // Node burn struct AccountNodeBurn { bool active; // Whether to activate Node burn uint256 income; // Node burn income } // Prize pool struct Pool { uint256 amount; // Prize pool amount uint256 date; // Creation time: Use this field to determine the draw time mapping(uint8 => address) ranks; // Ranking: up to 256 mapping(address => uint256) values; // Quantity/Performance } /** * @dev Determine whether the address is an already added address */ modifier onlyJoined(address addr) { require(accounts[addr].id > 0, "ANR"); _; } constructor(IERC20 _usdt) public { usdt = _usdt; createdAt = now; // Genius Account storage user = accounts[msg.sender]; user.id = ++id; user.referrer = address(0); user.joinTime = now; } /** * @dev Join or reinvest the game */ function join(address referrer, uint256 _amount) public onlyJoined(referrer) { require(referrer != msg.sender, "NS"); require(_amount >= usdter.mul(100), "MIN"); // Receive USDT usdt.safeTransferFrom(msg.sender, address(this), _amount); // Burn 12% _handleJoinBurn(msg.sender, _amount); Account storage user = accounts[msg.sender]; // Create new account if (user.id == 0) { user.id = ++id; user.referrer = referrer; user.joinTime = now; // Direct team teams[referrer].push(msg.sender); } // Reinvest to join if (user.deposit != 0) { require(!user.reinvest, "Reinvest"); // Can reinvest after paying back uint256 income = calculateStaticIncome(msg.sender) .add(user.dynamicIncome) .add(user.nodeIncome) .add(burns[msg.sender].income) .add(user.income); require(income >= user.deposit, "Not Coast"); // Half or all reinvestment require( _amount == user.deposit || _amount == user.deposit.div(2), "FOH" ); if (_amount == user.deposit) { // All reinvestment user.maxIncome = user.maxIncome.add( _calculateFullOutAmount(_amount) ); } else { // Half return user.maxIncome = user.maxIncome.add( _calculateOutAmount(_amount) ); } user.reinvest = true; user.deposit = user.deposit.add(_amount); } else { // Join out user.deposit = _amount; user.lastTakeTime = now; user.maxIncome = _calculateOutAmount(_amount); // Cumulative income cleared user.nodeIncome = 0; user.dayPoolIncome = 0; user.weekPoolIncome = 0; user.dynamicIncome = 0; burns[msg.sender].income = 0; } // Processing performance performances[msg.sender].wholeLine = performances[msg.sender] .wholeLine .add(_amount); _handlePerformance(user.referrer, _amount); // Processing node rewards _handleNodeReward(_amount); // Handling Node burn Reward _handleNodeBurnReward(msg.sender, _amount); // Processing node level _handleNodeLevel(user.referrer); // Handling prizes and draws _handlePool(user.referrer, _amount); // Technology founding team: 4% founder = founder.add(_amount.mul(4).div(100)); // Expansion operating expenses: 4% operation = operation.add(_amount.mul(4).div(100)); // Dex market making capital 2% dex = dex.add(_amount.mul(2).div(100)); // Insurance pool: 1.5% insurance = insurance.add(_amount.mul(15).div(1000)); // Perpetual pool: 3.5% sustainable = sustainable.add(_amount.mul(35).div(1000)); // Record the address of deposit 15000 if (user.deposit >= usdter.mul(15000)) { EnumerableSet.add(richman, msg.sender); } // Statistics total investment stats[msg.sender].investment = stats[msg.sender].investment.add( _amount ); // Total revenue totalRevenue = totalRevenue.add(_amount); } /** * @dev Burn tickets when you join */ function _handleJoinBurn(address addr, uint256 _amount) internal { uint256 burnUsdt = _amount.mul(12).div(100); uint256 burnAmount = burnUsdt.mul(ticket.price()).div(usdter); uint256 bal = ticket.balanceOf(addr); if (bal >= burnAmount) { ticket.burnFromUsdt(addr, burnUsdt); } else { // USDT can be used to deduct tickets after the resonance of 4.5 million require( ticket.totalVending() >= uint256(1e18).mul(4500000), "4.5M" ); // Use USDT to deduct tickets usdt.safeTransferFrom(addr, address(this), burnUsdt); ticket.vendingAndBurn(addr, burnAmount); } } /** * @dev Receive revenue and calculate outgoing data */ function take() public onlyJoined(msg.sender) { Account storage user = accounts[msg.sender]; require(user.deposit > 0, "OUT"); uint256 staticIncome = calculateStaticIncome(msg.sender); if (staticIncome > 0) { user.lastTakeTime = now - ((now - user.lastTakeTime) % STATIC_CYCLE); } uint256 paid = staticIncome .add(user.dynamicIncome) .add(user.nodeIncome) .add(burns[msg.sender].income); // Cleared user.nodeIncome = 0; user.dynamicIncome = 0; burns[msg.sender].income = 0; // Cumulative income user.income = user.income.add(paid); // Meet the exit conditions, or no re-investment and reach 1.3 times uint256 times13 = user.deposit.mul(13).div(10); bool special = !user.reinvest && user.income >= times13; // Out of the game if (user.income >= user.maxIncome || special) { // Deduct excess income if (special) { paid = times13.sub(user.income.sub(paid)); } else { paid = paid.sub(user.income.sub(user.maxIncome)); } // Data clear user.deposit = 0; user.income = 0; user.maxIncome = 0; user.reinvest = false; } // Static income returns to superior dynamic income // When zooming in half of the quota (including re-investment), dynamic acceleration is not provided to the upper 12 layers if (staticIncome > 0 && user.income < user.maxIncome.div(2)) { _handleDynamicIncome(msg.sender, staticIncome); } // Total income statistics stats[msg.sender].income = stats[msg.sender].income.add(paid); // USDT transfer _safeUsdtTransfer(msg.sender, paid); // Trigger _openWeekPool(); _openDayPool(); } /** * @dev Receive insurance pool rewards */ function takeReward() public { uint256 paid = accounts[msg.sender].reward; accounts[msg.sender].reward = 0; usdt.safeTransfer(msg.sender, paid); // Total income statistics stats[msg.sender].income = stats[msg.sender].income.add(paid); } /** * @dev Receive prize pool income */ function takePoolIncome() public { Account storage user = accounts[msg.sender]; uint256 paid = user.dayPoolIncome.add(user.weekPoolIncome); user.dayPoolIncome = 0; user.weekPoolIncome = 0; // Total income statistics stats[msg.sender].income = stats[msg.sender].income.add(paid); _safeUsdtTransfer(msg.sender, paid); } /** * @dev To activate Node burn, you need to destroy some tickets worth a specific USDT */ function activateNodeBurn() public onlyJoined(msg.sender) { require(!burns[msg.sender].active, "ACT"); require(nodeBurnNumber < 500, "LIMIT"); uint256 burn = activateNodeBurnAmount(); ticket.burnFromUsdt(msg.sender, burn); nodeBurnNumber++; burns[msg.sender].active = true; } /** * @dev Get the amount of USDT that activates the burned ticket for Node burn */ function activateNodeBurnAmount() public view returns (uint256) { uint8 num = nodeBurnNumber + 1; if (num >= 400) { return usdter.mul(7000); } else if (num >= 300) { return usdter.mul(6000); } else if (num >= 200) { return usdter.mul(5000); } else if (num >= 100) { return usdter.mul(4000); } else { return usdter.mul(3000); } } /** * @dev Handling Node burn Reward */ function _handleNodeBurnReward(address addr, uint256 _amount) internal { address referrer = accounts[addr].referrer; bool pioneer = false; while (referrer != address(0)) { AccountNodeBurn storage ap = burns[referrer]; if (ap.active) { if (accounts[referrer].nodeLevel > 0) { uint256 paid; if (pioneer) { paid = _amount.mul(4).div(100); // 4% } else { paid = _amount.mul(7).div(100); // 7% } ap.income = ap.income.add(paid); break; } else if (!pioneer) { ap.income = ap.income.add(_amount.mul(3).div(100)); // 3% pioneer = true; } } referrer = accounts[referrer].referrer; } } /** * @dev Dealing with dynamic revenue */ function _handleDynamicIncome(address addr, uint256 _amount) internal { address account = accounts[addr].referrer; // Up to 12 layers for (uint8 i = 1; i <= 12; i++) { if (account == address(0)) { break; } Account storage user = accounts[account]; if ( user.deposit > 0 && _canDynamicIncomeAble( performances[account].performance, user.deposit, i ) ) { uint256 _income = _amount.mul(dynamicRates[i - 1]).div(1000); user.dynamicIncome = user.dynamicIncome.add(_income); } account = user.referrer; } } /** * @dev Judge whether you can get dynamic income */ function _canDynamicIncomeAble( uint256 performance, uint256 deposit, uint8 floor ) internal pure returns (bool) { // Deposit more than 1500 if (deposit >= usdter.mul(1500)) { if (performance >= usdter.mul(10000)) { return floor <= 12; } if (performance >= usdter.mul(6000)) { return floor <= 8; } if (performance >= usdter.mul(3000)) { return floor <= 5; } if (performance >= usdter.mul(1500)) { return floor <= 3; } } else if (deposit >= usdter.mul(300)) { if (performance >= usdter.mul(1500)) { return floor <= 3; } } return floor <= 1; } /** * @dev Process prize pool data and draw */ function _handlePool(address referrer, uint256 _amount) internal { _openWeekPool(); _openDayPool(); uint256 prize = _amount.mul(3).div(100); // 3% uint256 dayPrize = prize.mul(60).div(100); // 60% uint256 weekPrize = prize.sub(dayPrize); // 40% _handleWeekPool(referrer, _amount, weekPrize); _handleDayPool(referrer, _amount, dayPrize); } /** * @dev Manually trigger the draw */ function triggerOpenPool() public { _openWeekPool(); _openDayPool(); } /** * @dev Processing weekly prize pool */ function _handleWeekPool( address referrer, uint256 _amount, uint256 _prize ) internal { Pool storage week = weekPool[weekPoolId]; week.amount = week.amount.add(_prize); week.values[referrer] = week.values[referrer].add(_amount); _PoolSort(week, referrer, 3); } /** * @dev Handling the daily prize pool */ function _handleDayPool( address referrer, uint256 _amount, uint256 _prize ) internal { Pool storage day = dayPool[dayPoolId]; day.amount = day.amount.add(_prize); day.values[referrer] = day.values[referrer].add(_amount); _PoolSort(day, referrer, 7); } /** * @dev Prize pool sorting */ function _PoolSort( Pool storage pool, address addr, uint8 number ) internal { for (uint8 i = 0; i < number; i++) { address key = pool.ranks[i]; if (key == addr) { break; } if (pool.values[addr] > pool.values[key]) { for (uint8 j = number; j > i; j--) { pool.ranks[j] = pool.ranks[j - 1]; } pool.ranks[i] = addr; for (uint8 k = i + 1; k < number; k++) { if (pool.ranks[k] == addr) { for (uint8 l = k; l < number; l++) { pool.ranks[l] = pool.ranks[l + 1]; } break; } } break; } } } /** * @dev Weekly prize pool draw */ function _openWeekPool() internal { Pool storage week = weekPool[weekPoolId]; // Determine whether the weekly prize pool can draw prizes if (now >= week.date + WEEK_POOL_CYCLE) { weekPoolId++; weekPool[weekPoolId].date = now; // 15% for the draw uint256 prize = week.amount.mul(15).div(100); // 85% naturally rolled into the next round weekPool[weekPoolId].amount = week.amount.sub(prize); if (prize > 0) { // No prizes left uint256 surplus = prize; // Proportion 70%、20%、10% uint256[3] memory rates = [ uint256(70), uint256(20), uint256(10) ]; // Top 3 for (uint8 i = 0; i < 3; i++) { address addr = week.ranks[i]; uint256 reward = prize.mul(rates[i]).div(100); // Reward for rankings, and rollover to the next round without rankings if (addr != address(0)) { accounts[addr].weekPoolIncome = accounts[addr] .weekPoolIncome .add(reward); surplus = surplus.sub(reward); } } // Add the rest to the next round weekPool[weekPoolId].amount = weekPool[weekPoolId].amount.add( surplus ); } } } /** * @dev Daily prize pool draw */ function _openDayPool() internal { Pool storage day = dayPool[dayPoolId]; // Determine whether the daily prize pool can be drawn if (now >= day.date + DAY_POOL_CYCLE) { dayPoolId++; dayPool[dayPoolId].date = now; // 15% for the draw uint256 prize = day.amount.mul(15).div(100); // 85% naturally rolled into the next round dayPool[dayPoolId].amount = day.amount.sub(prize); if (prize > 0) { // No prizes left uint256 surplus = prize; // The first and second place ratios are 70%, 20%; 10% is evenly distributed to the remaining 5 uint256[2] memory rates = [uint256(70), uint256(20)]; // Top 2 for (uint8 i = 0; i < 2; i++) { address addr = day.ranks[i]; uint256 reward = prize.mul(rates[i]).div(100); // Reward for rankings, and rollover to the next round without rankings if (addr != address(0)) { accounts[addr].dayPoolIncome = accounts[addr] .dayPoolIncome .add(reward); surplus = surplus.sub(reward); } } // 10% is evenly divided among the remaining 5 uint256 avg = prize.div(50); for (uint8 i = 2; i <= 6; i++) { address addr = day.ranks[i]; if (addr != address(0)) { accounts[addr].dayPoolIncome = accounts[addr] .dayPoolIncome .add(avg); surplus = surplus.sub(avg); } } // Add the rest to the next round dayPool[dayPoolId].amount = dayPool[dayPoolId].amount.add( surplus ); } } } /** * @dev Processing account performance */ function _handlePerformance(address referrer, uint256 _amount) internal { // Direct performance performances[referrer].performance = performances[referrer] .performance .add(_amount); // Full line performance address addr = referrer; while (addr != address(0)) { performances[addr].wholeLine = performances[addr].wholeLine.add( _amount ); addr = accounts[addr].referrer; } } /** * @dev Processing node level */ function _handleNodeLevel(address referrer) internal { address addr = referrer; // Condition uint256[4] memory c1s = [ usdter.mul(100000), usdter.mul(300000), usdter.mul(600000), usdter.mul(1200000) ]; uint256[4] memory c2s = [ usdter.mul(250000), usdter.mul(600000), usdter.mul(1200000), usdter.mul(2250000) ]; uint256[4] memory s1s = [ usdter.mul(20000), usdter.mul(60000), usdter.mul(90000), usdter.mul(160000) ]; uint256[4] memory s2s = [ usdter.mul(30000), usdter.mul(90000), usdter.mul(135000), usdter.mul(240000) ]; while (addr != address(0)) { uint8 level = accounts[addr].nodeLevel; if (level < 4) { uint256 c1 = c1s[level]; uint256 c2 = c2s[level]; if (now - accounts[addr].joinTime <= NODE_DISCOUNT_TIME) { c1 = c1.sub(s1s[level]); c2 = c2.sub(s2s[level]); } if (_handleNodeLevelUpgrade(addr, c1, c2)) { accounts[addr].nodeLevel = level + 1; nodes[level + 1].push(addr); } } addr = accounts[addr].referrer; } } /** * @dev Determine whether the upgrade conditions are met according to the conditions */ function _handleNodeLevelUpgrade( address addr, uint256 c1, uint256 c2 ) internal view returns (bool) { uint8 count = 0; uint256 min = uint256(-1); for (uint256 i = 0; i < teams[addr].length; i++) { uint256 w = performances[teams[addr][i]].wholeLine; // Case 1 if (w >= c1) { count++; if (count >= 3) { return true; } } // Case 2 if (w >= c2 && w < min) { min = w; } } if (min < uint256(-1) && performances[addr].wholeLine.sub(min) >= c2) { return true; } return false; } /** * @dev Processing node rewards */ function _handleNodeReward(uint256 _amount) internal { uint256 reward = _amount.div(25); for (uint8 i = 1; i <= 4; i++) { address[] storage _nodes = nodes[i]; uint256 len = _nodes.length; if (len > 0) { uint256 _reward = reward.div(len); for (uint256 j = 0; j < len; j++) { Account storage user = accounts[_nodes[j]]; user.nodeIncome = user.nodeIncome.add(_reward); } } } } /** * @dev Calculate static income */ function calculateStaticIncome(address addr) public view returns (uint256) { Account storage user = accounts[addr]; if (user.deposit > 0) { uint256 last = user.lastTakeTime; uint256 day = (now - last) / STATIC_CYCLE; if (day == 0) { return 0; } if (day > 30) { day = 30; } return user.deposit.mul(staticRate).div(1000).mul(day); } return 0; } /** * @dev Calculate out multiple */ function _calculateOutAmount(uint256 _amount) internal pure returns (uint256) { if (_amount >= usdter.mul(15000)) { return _amount.mul(35).div(10); } else if (_amount >= usdter.mul(4000)) { return _amount.mul(30).div(10); } else if (_amount >= usdter.mul(1500)) { return _amount.mul(25).div(10); } else { return _amount.mul(20).div(10); } } /** * @dev Calculate the out multiple of all reinvestments */ function _calculateFullOutAmount(uint256 _amount) internal pure returns (uint256) { if (_amount >= usdter.mul(15000)) { return _amount.mul(45).div(10); } else if (_amount >= usdter.mul(4000)) { return _amount.mul(40).div(10); } else if (_amount >= usdter.mul(1500)) { return _amount.mul(35).div(10); } else { return _amount.mul(25).div(10); } } /** * @dev Get the number of nodes at a certain level */ function nodeLength(uint8 level) public view returns (uint256) { return nodes[level].length; } /** * @dev Number of teams */ function teamsLength(address addr) public view returns (uint256) { return teams[addr].length; } /** * @dev Daily prize pool ranking */ function dayPoolRank(uint64 _id, uint8 _rank) public view returns (address) { return dayPool[_id].ranks[_rank]; } /** * @dev Daily prize pool performance */ function dayPoolValue(uint64 _id, address _addr) public view returns (uint256) { return dayPool[_id].values[_addr]; } /** * @dev Weekly prize pool ranking */ function weekPoolRank(uint64 _id, uint8 _rank) public view returns (address) { return weekPool[_id].ranks[_rank]; } /** * @dev Weekly prize pool performance */ function weekPoolValue(uint64 _id, address _addr) public view returns (uint256) { return weekPool[_id].values[_addr]; } /** * @dev Team statistics, return the smallest, medium and most performance */ function teamsStats(address addr) public view returns (uint256, uint256) { uint256 count = teams[addr].length; if (count > 0) { uint256 max = performances[teams[addr][count - 1]].wholeLine; uint256 min = performances[teams[addr][count - 1]].wholeLine; for (uint256 i = 0; i < count; i++) { if (performances[teams[addr][i]].wholeLine > max) { max = performances[teams[addr][i]].wholeLine; } if (performances[teams[addr][i]].wholeLine < min) { min = performances[teams[addr][i]].wholeLine; } } return (max, min); } return (0, 0); } /** * @dev Count how many people meet the conditions */ function teamsCount(address addr, uint256 _amount) public view returns (uint256) { uint256 count; for (uint256 i = 0; i < teams[addr].length; i++) { if (_amount <= performances[teams[addr][i]].wholeLine) { count++; } } return count; } /** * @dev Get the number of large account addresses */ function richmanLength() public view returns (uint256) { return EnumerableSet.length(richman); } /** * @dev Safe USDT transfer, excluding the balance of insurance pool and perpetual pool */ function _safeUsdtTransfer(address addr, uint256 _amount) internal { uint256 bal = usdt.balanceOf(address(this)); bal = bal.sub(insurance).sub(sustainable); if (bal < _amount) { usdt.safeTransfer(addr, bal); } else { usdt.safeTransfer(addr, _amount); } } /** * @dev Activate the insurance pool, only the administrator can call */ function activeInsurance() public onlyOwner { uint256 nodePaid = insurance.mul(70).div(100); uint256 bigPaid = insurance.sub(nodePaid); insurance = 0; // Issued to richman uint256 _richmanLen = EnumerableSet.length(richman); if (_richmanLen > 0) { uint256 paid = bigPaid.div(_richmanLen); for (uint256 i = 0; i < _richmanLen; i++) { Account storage user = accounts[EnumerableSet.at(richman, i)]; user.reward = user.reward.add(paid); } } // Issued to node uint256[4] memory _rates = [ uint256(10), uint256(20), uint256(30), uint256(40) ]; for (uint8 i = 1; i <= 4; i++) { uint256 _nodeLen = nodes[i].length; if (_nodeLen > 0) { uint256 paid = nodePaid.mul(_rates[i - 1]).div(100).div( _nodeLen ); for (uint256 j = 0; j < _nodeLen; j++) { Account storage user = accounts[nodes[i][j]]; user.reward = user.reward.add(paid); } } } } /** * @dev Transfer to the perpetual pool, only the administrator can call */ function activeSustainable(address next) public onlyOwner { require(sustainable > 0); uint256 paid = sustainable; uint256 bal = usdt.balanceOf(address(this)); if (bal < paid) { usdt.safeTransfer(next, bal); } else { usdt.safeTransfer(next, paid); } } /** * @dev Set static rate of return, only the administrator can call */ function setStaticRate(uint256 _rate) public onlyOwner { require(_rate <= 1000); staticRate = _rate; } /** * @dev Set dynamic rate of return, only the administrator can call */ function setDynamicRates(uint8 level, uint256 _rate) public onlyOwner { require(level < 12); require(_rate <= 1000); dynamicRates[level] = _rate; } /** * @dev Set up the ticket contract, only the administrator can call */ function setTicket(ITicketsToken _ticket) public onlyOwner { ticket = _ticket; } /** * @dev Receive the technical founding team, only the administrator can call */ function takeFounder() public onlyOwner { uint256 paid = founder; founder = 0; usdt.safeTransfer(msg.sender, paid); } /** * @dev Receive expansion operation fee, only the administrator can call */ function takeOperation() public onlyOwner { uint256 paid = operation.add(dex); operation = 0; dex = 0; usdt.safeTransfer(msg.sender, paid); } }
Manually trigger the draw/
function triggerOpenPool() public { _openWeekPool(); _openDayPool(); }
433,577
./full_match/5/0x213816e69A21320D086a40Af97A5151445e8bFDE/sources/contracts/DeedTenantProvisioning.sol
Returns the delegated address for Provisioning Management of an NFT/
function getDelegatee(uint256 _nftId) external view returns(address) { return delegatees[_nftId]; }
7,060,018
./full_match/1/0xe802c53EeAc712deb8bD9B202416B852eEf0E7AB/sources/contracts/Orchestrator.sol
Main entry point to initiate a rebase operation. The Orchestrator calls rebase on the policy and notifies downstream applications. Contracts are guarded from calling, to avoid flash loan attacks on liquidity providers. If a transaction in the transaction list fails, Orchestrator will stop execution and revert to prevent a gas underprice attack./
function rebase() external { policy.rebase(); for (uint256 i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { (bool result, ) = t.destination.call(t.data); if (!result) { revert("Transaction Failed"); } } } }
3,873,001
// SPDX-License-Identifier: AGPL-3.0-or-later /// DssProxyActionsCropper.sol // Copyright (C) 2018-2020 Maker Ecosystem Growth Holdings, INC. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.12; interface GemLike { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom(address, address, uint256) external; function deposit() external payable; function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); } interface CropperLike { function getOrCreateProxy(address) external returns (address); function join(address, address, uint256) external; function exit(address, address, uint256) external; function flee(address, address, uint256) external; function frob(bytes32, address, address, address, int256, int256) external; function quit(bytes32, address, address) external; } interface VatLike { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function hope(address) external; function nope(address) external; function flux(bytes32, address, address, uint256) external; } interface GemJoinLike { function dec() external returns (uint256); function gem() external returns (GemLike); function ilk() external returns (bytes32); function bonus() external returns (GemLike); } interface DaiJoinLike { function dai() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } interface EndLike { function fix(bytes32) external view returns (uint256); function cash(bytes32, uint256) external; function free(bytes32) external; function pack(uint256) external; function skim(bytes32, address) external; } interface JugLike { function drip(bytes32) external returns (uint256); } interface HopeLike { function hope(address) external; function nope(address) external; } interface CdpRegistryLike { function owns(uint256) external view returns (address); function ilks(uint256) external view returns (bytes32); function open(bytes32, address) external returns (uint256); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contract Common { uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; address immutable public vat; address immutable public cropper; address immutable public cdpRegistry; constructor(address vat_, address cropper_, address cdpRegistry_) public { vat = vat_; cropper = cropper_; cdpRegistry = cdpRegistry_; } // Internal functions function _mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address daiJoin, address u, uint256 wad) public { GemLike dai = DaiJoinLike(daiJoin).dai(); // Gets DAI from the user's wallet dai.transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount dai.approve(daiJoin, wad); // Joins DAI into the vat DaiJoinLike(daiJoin).join(u, wad); } } contract DssProxyActionsCropper is Common { constructor(address vat_, address cropper_, address cdpRegistry_) public Common(vat_, cropper_, cdpRegistry_) {} // Internal functions function _sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function _divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x != 0 ? ((x - 1) / y) + 1 : 0; } function _toInt256(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function _convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we // need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = _mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address jug, address u, bytes32 ilk, uint256 wad ) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(u); // If there was already enough DAI in the vat balance, just exits it without adding more debt uint256 rad = _mul(wad, RAY); if (dai < rad) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = _toInt256(_divup(rad - dai, rate)); // safe since dai < rad } } function _getWipeDart( uint256 dai, address u, bytes32 ilk ) internal returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, CropperLike(cropper).getOrCreateProxy(u)); // Uses the whole dai balance in the vat to reduce the debt dart = _toInt256(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), // otherwise uses its value dart = uint256(dart) <= art ? - dart : - _toInt256(art); } function _getWipeAllWad( address u, address urp, bytes32 ilk ) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urp); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(u); // If there was already enough DAI in the vat balance, no need to join more uint256 debt = _mul(art, rate); if (debt > dai) { wad = _divup(debt - dai, RAY); // safe since debt > dai } } function _frob( bytes32 ilk, address u, int256 dink, int256 dart ) internal { CropperLike(cropper).frob(ilk, u, u, u, dink, dart); } function _ethJoin_join(address ethJoin, address u) internal { GemLike gem = GemJoinLike(ethJoin).gem(); // Wraps ETH in WETH gem.deposit{value: msg.value}(); // Approves adapter to take the WETH amount gem.approve(cropper, msg.value); // Joins WETH collateral into the vat CropperLike(cropper).join(ethJoin, u, msg.value); } function _gemJoin_join(address gemJoin, address u, uint256 amt) internal { GemLike gem = GemJoinLike(gemJoin).gem(); // Gets token from the user's wallet gem.transferFrom(msg.sender, address(this), amt); // Approves adapter to take the token amount gem.approve(cropper, amt); // Joins token collateral into the vat CropperLike(cropper).join(gemJoin, u, amt); } // Public functions function transfer(address gem, address dst, uint256 amt) external { GemLike(gem).transfer(dst, amt); } function hope( address obj, address usr ) external { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) external { HopeLike(obj).nope(usr); } function open( bytes32 ilk, address usr ) external returns (uint256 cdp) { cdp = CdpRegistryLike(cdpRegistry).open(ilk, usr); } function lockETH( address ethJoin, uint256 cdp ) external payable { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat _ethJoin_join(ethJoin, owner); // Locks WETH amount into the CDP _frob(CdpRegistryLike(cdpRegistry).ilks(cdp), owner, _toInt256(msg.value), 0); } function lockGem( address gemJoin, uint256 cdp, uint256 amt ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); // Takes token amount from user's wallet and joins into the vat _gemJoin_join(gemJoin, owner, amt); // Locks token amount into the CDP _frob(CdpRegistryLike(cdpRegistry).ilks(cdp), owner, _toInt256(_convertTo18(gemJoin, amt)), 0); } function freeETH( address ethJoin, uint256 cdp, uint256 wad ) external { // Unlocks WETH amount from the CDP _frob( CdpRegistryLike(cdpRegistry).ilks(cdp), CdpRegistryLike(cdpRegistry).owns(cdp), -_toInt256(wad), 0 ); // Exits WETH amount to proxy address as a token CropperLike(cropper).exit(ethJoin, address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function freeGem( address gemJoin, uint256 cdp, uint256 amt ) external { // Unlocks token amount from the CDP _frob( CdpRegistryLike(cdpRegistry).ilks(cdp), CdpRegistryLike(cdpRegistry).owns(cdp), -_toInt256(_convertTo18(gemJoin, amt)), 0 ); // Exits token amount to proxy address as a token CropperLike(cropper).exit(gemJoin, address(this), amt); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).gem().transfer(msg.sender, amt); } function exitETH( address ethJoin, uint256 cdp, uint256 wad ) external { require(CdpRegistryLike(cdpRegistry).owns(cdp) == address(this), "wrong-cdp"); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(ethJoin).ilk(), "wrong-ilk"); // Exits WETH amount to proxy address as a token CropperLike(cropper).exit(ethJoin, address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address gemJoin, uint256 cdp, uint256 amt ) external { require(CdpRegistryLike(cdpRegistry).owns(cdp) == address(this), "wrong-cdp"); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(gemJoin).ilk(), "wrong-ilk"); // Exits token amount to proxy address as a token CropperLike(cropper).exit(gemJoin, address(this), amt); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).gem().transfer(msg.sender, amt); } function fleeETH( address ethJoin, uint256 cdp, uint256 wad ) external { require(CdpRegistryLike(cdpRegistry).owns(cdp) == address(this), "wrong-cdp"); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(ethJoin).ilk(), "wrong-ilk"); // Exits WETH to proxy address as a token CropperLike(cropper).flee(ethJoin, address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function fleeGem( address gemJoin, uint256 cdp, uint256 amt ) external { require(CdpRegistryLike(cdpRegistry).owns(cdp) == address(this), "wrong-cdp"); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(gemJoin).ilk(), "wrong-ilk"); // Exits token amount to the user's wallet as a token CropperLike(cropper).flee(gemJoin, msg.sender, amt); } function draw( address jug, address daiJoin, uint256 cdp, uint256 wad ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Generates debt in the CDP _frob(ilk, owner, 0, _getDrawDart(jug, owner, ilk, wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function wipe( address daiJoin, uint256 cdp, uint256 wad ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, wad); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP _frob( ilk, owner, 0, _getWipeDart( VatLike(vat).dai(owner), owner, ilk ) ); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); } function wipeAll( address daiJoin, uint256 cdp ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); address urp = CropperLike(cropper).getOrCreateProxy(owner); (, uint256 art) = VatLike(vat).urns(ilk, urp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, _getWipeAllWad(owner, urp, ilk)); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP _frob(ilk, owner, 0, -_toInt256(art)); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); } function lockETHAndDraw( address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat _ethJoin_join(ethJoin, owner); // Locks WETH amount into the CDP and generates debt _frob( ilk, owner, _toInt256(msg.value), _getDrawDart( jug, owner, ilk, wadD ) ); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD ) public payable returns (uint256 cdp) { cdp = CdpRegistryLike(cdpRegistry).open(ilk, address(this)); lockETHAndDraw(jug, ethJoin, daiJoin, cdp, wadD); } function lockGemAndDraw( address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 amtC, uint256 wadD ) public { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Takes token amount from user's wallet and joins into the vat _gemJoin_join(gemJoin, owner, amtC); // Locks token amount into the CDP and generates debt _frob( ilk, owner, _toInt256(_convertTo18(gemJoin, amtC)), _getDrawDart( jug, owner, ilk, wadD ) ); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 amtC, uint256 wadD ) public returns (uint256 cdp) { cdp = CdpRegistryLike(cdpRegistry).open(ilk, address(this)); lockGemAndDraw(jug, gemJoin, daiJoin, cdp, amtC, wadD); } function wipeAndFreeETH( address ethJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, wadD); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP and unlocks WETH amount from it _frob( ilk, owner, -_toInt256(wadC), _getWipeDart( VatLike(vat).dai(owner), owner, ilk ) ); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); // Exits WETH amount to proxy address as a token CropperLike(cropper).exit(ethJoin, address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function wipeAllAndFreeETH( address ethJoin, address daiJoin, uint256 cdp, uint256 wadC ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); address urp = CropperLike(cropper).getOrCreateProxy(owner); (, uint256 art) = VatLike(vat).urns(ilk, urp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, _getWipeAllWad(owner, urp, ilk)); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP and unlocks WETH amount from it _frob(ilk, owner, -_toInt256(wadC), -_toInt256(art)); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); // Exits WETH amount to proxy address as a token CropperLike(cropper).exit(ethJoin, address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function wipeAndFreeGem( address gemJoin, address daiJoin, uint256 cdp, uint256 amtC, uint256 wadD ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, wadD); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP and unlocks token amount from it _frob( ilk, owner, -_toInt256(_convertTo18(gemJoin, amtC)), _getWipeDart( VatLike(vat).dai(owner), owner, ilk ) ); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); // Exits token amount to proxy address as a token CropperLike(cropper).exit(gemJoin, address(this), amtC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).gem().transfer(msg.sender, amtC); } function wipeAllAndFreeGem( address gemJoin, address daiJoin, uint256 cdp, uint256 amtC ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); address urp = CropperLike(cropper).getOrCreateProxy(owner); (, uint256 art) = VatLike(vat).urns(ilk, urp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, _getWipeAllWad(owner, urp, ilk)); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP and unlocks token amount from it _frob(ilk, owner, -_toInt256(_convertTo18(gemJoin, amtC)), -_toInt256(art)); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); // Exits token amount to proxy address as a token CropperLike(cropper).exit(gemJoin, address(this), amtC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).gem().transfer(msg.sender, amtC); } function crop( address gemJoin, uint256 cdp ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(gemJoin).ilk(), "wrong-ilk"); CropperLike(cropper).join(gemJoin, owner, 0); GemLike bonus = GemJoinLike(gemJoin).bonus(); bonus.transfer(msg.sender, bonus.balanceOf(address(this))); } } contract DssProxyActionsEndCropper is Common { constructor(address vat_, address cropper_, address cdpRegistry_) public Common(vat_, cropper_, cdpRegistry_) {} // Internal functions function _free( address end, address u, bytes32 ilk ) internal returns (uint256 ink) { address urp = CropperLike(cropper).getOrCreateProxy(u); uint256 art; (ink, art) = VatLike(vat).urns(ilk, urp); // If CDP still has debt, it needs to be paid if (art > 0) { EndLike(end).skim(ilk, urp); (ink,) = VatLike(vat).urns(ilk, urp); } // Approves the cropper to transfer the position to proxy's address in the vat VatLike(vat).hope(cropper); // Transfers position from CDP to the proxy address CropperLike(cropper).quit(ilk, u, address(this)); // Denies cropper to access to proxy's position in the vat after execution VatLike(vat).nope(cropper); // Frees the position and recovers the collateral in the vat registry EndLike(end).free(ilk); // Fluxs to the proxy's cropper proxy, so it can be pulled out with the managed gem join VatLike(vat).flux( ilk, address(this), urp, ink ); } // Public functions function freeETH( address ethJoin, address end, uint256 cdp ) external { // Frees the position through the end contract uint256 wad = _free(end, CdpRegistryLike(cdpRegistry).owns(cdp), CdpRegistryLike(cdpRegistry).ilks(cdp)); // Exits WETH amount to proxy address as a token CropperLike(cropper).exit(ethJoin, address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function freeGem( address gemJoin, address end, uint256 cdp ) external { // Frees the position through the end contract uint256 wad = _free(end, CdpRegistryLike(cdpRegistry).owns(cdp), CdpRegistryLike(cdpRegistry).ilks(cdp)); // Exits token amount to the user's wallet as a token uint256 amt = wad / 10 ** (18 - GemJoinLike(gemJoin).dec()); // Exits token amount to proxy address as a token CropperLike(cropper).exit(gemJoin, address(this), amt); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).gem().transfer(msg.sender, amt); } function pack( address daiJoin, address end, uint256 wad ) external { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Approves the end to take out DAI from the proxy's balance in the vat if (VatLike(vat).can(address(this), address(end)) == 0) { VatLike(vat).hope(end); } EndLike(end).pack(wad); } function cashETH( address ethJoin, address end, uint256 wad ) external { bytes32 ilk = GemJoinLike(ethJoin).ilk(); EndLike(end).cash(ilk, wad); uint256 wadC = _mul(wad, EndLike(end).fix(ilk)) / RAY; // Flux to the proxy's UrnProxy in cropper, so it can be pulled out with the managed gem join VatLike(vat).flux( ilk, address(this), CropperLike(cropper).getOrCreateProxy(address(this)), wadC ); // Exits WETH amount to proxy address as a token CropperLike(cropper).flee(ethJoin, address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function cashGem( address gemJoin, address end, uint256 wad ) external { bytes32 ilk = GemJoinLike(gemJoin).ilk(); EndLike(end).cash(ilk, wad); uint256 wadC = _mul(wad, EndLike(end).fix(ilk)) / RAY; // Flux to the proxy's UrnProxy in cropper, so it can be pulled out with the managed gem join VatLike(vat).flux( ilk, address(this), CropperLike(cropper).getOrCreateProxy(address(this)), wadC ); // Exits token amount to the user's wallet as a token uint256 amt = wadC / 10 ** (18 - GemJoinLike(gemJoin).dec()); CropperLike(cropper).flee(gemJoin, msg.sender, amt); } }
Exits token amount to proxy address as a token Exits token amount to the user's wallet as a token
function exitGem( address gemJoin, uint256 cdp, uint256 amt ) external { require(CdpRegistryLike(cdpRegistry).owns(cdp) == address(this), "wrong-cdp"); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(gemJoin).ilk(), "wrong-ilk"); CropperLike(cropper).exit(gemJoin, address(this), amt); GemJoinLike(gemJoin).gem().transfer(msg.sender, amt); }
52,435
pragma solidity ^0.4.23; /******************************************************************************* * * Copyright (c) 2018 Taboo University MDAO. * Released under the MIT License. * * Taboo Db - An eternal database, providing a sustainable storage solution * for use throughout the upgrade lifecycle of managing contracts. * * Version 18.5.7 * * Web : https://taboou.com/ * Email : [email protected] * Github : https://github.com/taboou/tabooads.bit/ */ /******************************************************************************* * 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); } } /******************************************************************************* * Taboo Db Contract */ contract TabooDb is Owned { /* Initialize all storage types. */ mapping(bytes32 => address) private addressStorage; mapping(bytes32 => bool) private boolStorage; mapping(bytes32 => bytes) private bytesStorage; mapping(bytes32 => int256) private intStorage; mapping(bytes32 => string) private stringStorage; mapping(bytes32 => uint256) private uIntStorage; /** * @dev Only allow access from the latest version of a contract * in the Taboo U Networks (TUN) after deployment. */ modifier onlyAuthByTUN() { /*********************************************************************** * The owner is only allowed to set the authorized contracts upon * deployment, to register the initial contracts, afterwards their * direct access is permanently disabled. */ if (msg.sender == owner) { /* Verify owner's write access has not already been disabled. */ require(boolStorage[keccak256('owner.auth.disabled')] != true); } else { /* Verify write access is only permitted to authorized accounts. */ require(boolStorage[keccak256(msg.sender, '.has.auth')] == true); } _; // function code is inserted here } /*************************************************************************** * Initialize all getter 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 getBool(bytes32 _key) external view returns (bool) { return boolStorage[_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 getInt(bytes32 _key) external view returns (int) { return intStorage[_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 getUint(bytes32 _key) external view returns (uint) { return uIntStorage[_key]; } /*************************************************************************** * Initialize all setter methods. */ /// @param _key The key for the record function setAddress(bytes32 _key, address _value) onlyAuthByTUN external { addressStorage[_key] = _value; } /// @param _key The key for the record function setBool(bytes32 _key, bool _value) onlyAuthByTUN external { boolStorage[_key] = _value; } /// @param _key The key for the record function setBytes(bytes32 _key, bytes _value) onlyAuthByTUN external { bytesStorage[_key] = _value; } /// @param _key The key for the record function setInt(bytes32 _key, int _value) onlyAuthByTUN external { intStorage[_key] = _value; } /// @param _key The key for the record function setString(bytes32 _key, string _value) onlyAuthByTUN external { stringStorage[_key] = _value; } /// @param _key The key for the record function setUint(bytes32 _key, uint _value) onlyAuthByTUN external { uIntStorage[_key] = _value; } /*************************************************************************** * Initialize all delete methods. */ /// @param _key The key for the record function deleteAddress(bytes32 _key) onlyAuthByTUN external { delete addressStorage[_key]; } /// @param _key The key for the record function deleteBool(bytes32 _key) onlyAuthByTUN external { delete boolStorage[_key]; } /// @param _key The key for the record function deleteBytes(bytes32 _key) onlyAuthByTUN external { delete bytesStorage[_key]; } /// @param _key The key for the record function deleteInt(bytes32 _key) onlyAuthByTUN external { delete intStorage[_key]; } /// @param _key The key for the record function deleteString(bytes32 _key) onlyAuthByTUN external { delete stringStorage[_key]; } /// @param _key The key for the record function deleteUint(bytes32 _key) onlyAuthByTUN external { delete uIntStorage[_key]; } }
_key The key for the record
function setBytes(bytes32 _key, bytes _value) onlyAuthByTUN external { bytesStorage[_key] = _value; }
619,622
pragma solidity ^0.5.0; // TODO // only manager ethereum account have access of this contract import './Zeppelin/ownership/Ownable.sol'; contract UsersManager is Ownable{ struct User{ address account; // user account address address contractUser; // "User" contract address bytes32 password; // User password hash value } event NewUser(address userAccount, address contractAccount, string username); mapping (string => User) private userToAccount; // a storage for user and their account, key=username mapping (string => address) private SINToAccount; // key = SIN, value = account address mapping (string => bool) private SINToCredit; // key = SIN, value = credit free function updateCredit(string memory _SIN, bool _credit) public onlyOwner{ SINToCredit[_SIN] = _credit; } function getCredit(string memory _SIN) public view returns(bool credit){ return SINToCredit[_SIN]; } function createSIN(string memory _SIN, address _user) public onlyOwner{//suppose happen once when user input SIN on first time SINToAccount[_SIN] = _user; } function getUserBySIN(string memory _SIN)public view returns(address userContract){ return SINToAccount[_SIN]; } function changeSIN(string memory _prevSIN, string memory _newSIN) public{ // very rare situtation when user inputed a wrong SIN SINToAccount[_newSIN] = SINToAccount[_prevSIN]; SINToAccount[_prevSIN]=address(0); SINToCredit[_newSIN] = SINToCredit[_prevSIN]; } uint private count; // number of register User function checkValidateUsers(string memory _username) public view returns (address result){// see if input username already exist if(userToAccount[_username].account == address(0)){ return userToAccount[_username].account; }else return userToAccount[_username].account; } function register(address _userAccount, address _userContract, string memory _username, string memory _password) public{ // Adding address and username to mapping, userCount++ userToAccount[_username] = User(_userAccount, _userContract, keccak256(abi.encodePacked(_password))); count++; //To log user register event emit NewUser(_userAccount, _userContract, _username); } function login(string memory _username, string memory _password) public view returns (address userAccount, address userContract){ // if username & password is correct, return user address if(keccak256(abi.encodePacked(_password)) == userToAccount[_username].password) return (userToAccount[_username].account, userToAccount[_username].contractUser); else return (address(0),address(0)); } }
see if input username already exist
function checkValidateUsers(string memory _username) public view returns (address result){
12,816,052
// File: openzeppelin-eth/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: zos-lib/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/ownership/Ownable.sol pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Initializable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.4.24; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string name, string symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } uint256[50] private ______gap; } // File: uFragments/contracts/lib/SafeMathInt.sol /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.4.24; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } // File: uFragments/contracts/IUniswapV2Pair.sol interface IUniswapV2Pair { function sync() external; function skim(address to) external; function token0() external view returns (address); function token1() external view returns (address); } // File: uFragments/contracts/UFragments.sol pragma solidity 0.4.24; /** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining value proportionally across all wallets. */ contract UFragments is ERC20Detailed, Ownable { using SafeMath for uint256; using SafeMathInt for int256; uint256 private constant TOKEN_PRECISION = 1e6; uint256 private constant DECIMALS = 6; uint256 private constant MIN_SUPPLY = 240 * TOKEN_PRECISION; uint256 private constant INITIAL_SUPPLY = 12000 * TOKEN_PRECISION; uint256 private constant MAX_SUPPLY = 24000 * TOKEN_PRECISION; struct User { uint256 balance; mapping(address => uint256) allowance; uint256 appliedTokenCirculation; uint256 executeTransferTimeOut; } struct Info { uint256 totalSupply; mapping(address => User) users; uint256 coinWorkingTime; address uniswapV2PairAddress; bool initialSetup; address[] contractUsers; uint256 periodVolumenToken; uint256 round; uint256 divider; uint256 drainSystem; uint256 rewardBonus; } Info public info; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event AdjustSupply(uint256 value); event AdjustUniswapSupply(uint256 value); function initialize(address owner_) public initializer { ERC20Detailed.initialize("VolTime", "VolTime", uint8(DECIMALS)); Ownable.initialize(owner_); info.coinWorkingTime = now; info.uniswapV2PairAddress = address(0); info.totalSupply = INITIAL_SUPPLY; info.users[msg.sender].balance = INITIAL_SUPPLY; info.users[msg.sender].appliedTokenCirculation = INITIAL_SUPPLY; info.initialSetup = false; info.round = 24 hours; info.divider = 1 hours; info.drainSystem = 60 seconds; info.rewardBonus = 10; emit Transfer(address(0x0), owner_, INITIAL_SUPPLY); } /** * @return The total number of fragments. */ function totalSupply() public view returns (uint256) { return info.totalSupply; } /** * @dev Function to check the amount of value that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of value still available for the spender. */ function allowance(address owner_, address spender) public view returns (uint256) { return info.users[owner_].allowance[spender]; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view returns (uint256) { bool isNewUser = info.users[who].balance == 0; if(isNewUser) { return 0; } uint256 adjustedAddressBalance = ((info.users[who].balance * info.totalSupply) / info.users[who].appliedTokenCirculation); return (adjustedAddressBalance); } /** * @dev Approve the passed address to spend the specified amount of value on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of value to be spent. */ function approve(address spender, uint256 value) external returns (bool) { info.users[msg.sender].allowance[spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer value to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Transfer value from one address to another. * @param from The address you want to send value from. * @param to The address you want to transfer to. * @param value The amount of value to be transferred. */ function transferFrom(address from, address to, uint256 value) external returns (bool) { require(info.users[from].allowance[msg.sender] >= value); info.users[from].allowance[msg.sender] -= value; _transfer(from, to, value); return true; } function _transfer(address from, address to, uint256 value) internal returns (uint256) { require(balanceOf(from) >= value); uint256 _transferred = 0; bool isNewUser = info.users[to].balance == 0; if(isNewUser) { info.users[to].appliedTokenCirculation = info.totalSupply; info.users[to].executeTransferTimeOut = now; info.contractUsers.push(to); } if(to == info.uniswapV2PairAddress){ require(info.users[from].executeTransferTimeOut + info.drainSystem < now); info.users[from].executeTransferTimeOut = now; } if(from == info.uniswapV2PairAddress){ info.users[to].executeTransferTimeOut = now; } //Sync wallets if(info.uniswapV2PairAddress != from && info.users[from].appliedTokenCirculation != info.totalSupply){ _adjRebase(from); } if(info.uniswapV2PairAddress != to && info.users[to].appliedTokenCirculation != info.totalSupply){ _adjRebase(to); } bool whenAbleToTransfer = info.users[from].appliedTokenCirculation == info.users[to].appliedTokenCirculation; // Able to transfer on the same level only if(whenAbleToTransfer){ info.users[from].balance -= value; _transferred = value; info.users[to].balance += _transferred; emit Transfer(from, to, _transferred); } if(info.uniswapV2PairAddress == from || info.uniswapV2PairAddress == to){ info.periodVolumenToken += value; } if(info.uniswapV2PairAddress != address(0) && !isNewUser){ if(info.coinWorkingTime + info.round < now) { uint256 countOfCoins = (((now - info.coinWorkingTime) / info.divider) * TOKEN_PRECISION) * info.rewardBonus; info.coinWorkingTime = now; if(info.periodVolumenToken >= info.totalSupply){ if(info.totalSupply + countOfCoins >= MAX_SUPPLY){ info.totalSupply = MAX_SUPPLY; }else{ info.totalSupply += countOfCoins; } }else{ if(info.totalSupply <= countOfCoins + MIN_SUPPLY){ info.totalSupply = MIN_SUPPLY; }else{ info.totalSupply -= countOfCoins; } } info.periodVolumenToken = 0; emit AdjustSupply(info.totalSupply); } } if(info.uniswapV2PairAddress != address(0)){ // Rebalance uniswap wallet even user to user if(info.users[info.uniswapV2PairAddress].appliedTokenCirculation != info.totalSupply){ _adjRebase(info.uniswapV2PairAddress); } // Sync uniswap even user to user if(info.uniswapV2PairAddress != from && info.uniswapV2PairAddress != to){ IUniswapV2Pair(info.uniswapV2PairAddress).sync(); } } return _transferred; } function initRebase (address _uniswapV2PairAddress) onlyOwner public { require(!info.initialSetup); info.initialSetup = true; info.coinWorkingTime = now; info.uniswapV2PairAddress = _uniswapV2PairAddress; } function rebaseTimeInfo() public view returns (bool _isTimeToRebase, uint256 _timeNow, uint256 _workingTime, uint256 _roundTime) { bool isTimeToRebase = info.coinWorkingTime + info.round < now; return(isTimeToRebase, now, info.coinWorkingTime, info.round); } function volTime() public view returns (uint256 volumenOnToken, uint256 _coinsToAddOrRemove, uint256 _totalSupply, uint256 _futureTotalSupply) { uint256 countOfCoins = (((now - info.coinWorkingTime) / info.divider) * TOKEN_PRECISION) * info.rewardBonus; uint256 futureTotalSupply = info.totalSupply; if(info.periodVolumenToken >= info.totalSupply){ if(info.totalSupply + countOfCoins >= MAX_SUPPLY){ futureTotalSupply = MAX_SUPPLY; }else{ futureTotalSupply += countOfCoins; } }else{ if(info.totalSupply <= countOfCoins + MIN_SUPPLY){ futureTotalSupply = MIN_SUPPLY; }else{ futureTotalSupply -= countOfCoins; } } if(futureTotalSupply == info.totalSupply){ _coinsToAddOrRemove = 0; } return(info.periodVolumenToken, countOfCoins, info.totalSupply, futureTotalSupply); } function _adjRebase(address person) private { uint256 addressBalanceFrom = info.users[person].balance; uint256 adjustedAddressBalanceFrom = (addressBalanceFrom * info.totalSupply) / info.users[person].appliedTokenCirculation; info.users[person].balance = adjustedAddressBalanceFrom; info.users[person].appliedTokenCirculation = info.totalSupply; emit Transfer(person, person, adjustedAddressBalanceFrom); } function resetSeason() onlyOwner public { for (uint id = 0; id < info.contractUsers.length; id++) { address userAddress = info.contractUsers[id]; if(userAddress == info.uniswapV2PairAddress || userAddress == owner()){ emit Transfer(userAddress, userAddress, 0); }else{ uint256 value = info.users[userAddress].balance; info.users[userAddress].balance -= value; info.users[owner()].balance += value; emit Transfer(userAddress, owner(), value); } } delete info.contractUsers; } }
return The total number of fragments./
function totalSupply() public view returns (uint256) { return info.totalSupply; }
1,509,409
./full_match/80001/0x99BC393191c472202f27FB2bf3454ed0A6837ffb/sources/fflat.sol
toCronString converts a cron spec to a human-readable cron string. This is gas-intensive and therefore should only be called off-chain. spec the cron spec return the corresponding cron string/
function toCronString(Spec memory spec) internal pure returns (string memory) { return string( bytes.concat( fieldToBstring(spec.minute), " ", fieldToBstring(spec.hour), " ", fieldToBstring(spec.day), " ", fieldToBstring(spec.month), " ", fieldToBstring(spec.dayOfWeek) ) ); }
859,404
./full_match/1/0x7045f6CA2e9C63D01856fb9F8eF9FA2d95296B54/sources/browser/UniswapV2Recipe_flat.sol
Max eth amount enforced by msg.value return excess ETH Send any excess ETH back
function toPie(address _pie, uint256 _poolAmount) external payable saveGas(gasSponsor) { uint256 totalEth = calcToPie(_pie, _poolAmount); require(msg.value >= totalEth, "Amount ETH too low"); _toPie(_pie, _poolAmount); if(address(this).balance != 0) { msg.sender.transfer(address(this).balance); } IERC20(pie).transfer(msg.sender, pie.balanceOf(address(this))); }
3,206,532
/** *Submitted for verification at Etherscan.io on 2019-07-11 */ // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice 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 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: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/external/DappHub/interfaces/IMedian.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IMedian * @author Set Protocol * * Interface for operating with a price feed Medianizer contract */ interface IMedian { /** * Returns the current price set on the medianizer. Throws if the price is set to 0 (initialization) * * @return Current price of asset represented in hex as bytes32 */ function read() external view returns (bytes32); /** * Returns the current price set on the medianizer and whether the value has been initialized * * @return Current price of asset represented in hex as bytes32, and whether value is non-zero */ function peek() external view returns (bytes32, bool); } // File: contracts/meta-oracles/lib/LinkedListLibrary.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; /** * @title LinkedListLibrary * @author Set Protocol * * Library for creating and altering uni-directional circularly linked lists, optimized for sequential updating */ contract LinkedListLibrary { using SafeMath for uint256; /* ============ Structs ============ */ struct LinkedList{ uint256 dataSizeLimit; uint256 lastUpdatedIndex; uint256[] dataArray; } /* * Initialize LinkedList by setting limit on amount of nodes and inital value of node 0 * * @param _self LinkedList to operate on * @param _dataSizeLimit Max amount of nodes allowed in LinkedList * @param _initialValue Initial value of node 0 in LinkedList */ function initialize( LinkedList storage _self, uint256 _dataSizeLimit, uint256 _initialValue ) internal { require( _self.dataArray.length == 0, "LinkedListLibrary: Initialized LinkedList must be empty" ); // Initialize Linked list by defining upper limit of data points in the list and setting // initial value _self.dataSizeLimit = _dataSizeLimit; _self.dataArray.push(_initialValue); _self.lastUpdatedIndex = 0; } /* * Add new value to list by either creating new node if node limit not reached or updating * existing node value * * @param _self LinkedList to operate on * @param _addedValue Value to add to list */ function editList( LinkedList storage _self, uint256 _addedValue ) internal { // Add node if data hasn&#39;t reached size limit, otherwise update next node _self.dataArray.length < _self.dataSizeLimit ? addNode(_self, _addedValue) : updateNode(_self, _addedValue); } /* * Add new value to list by either creating new node. Node limit must not be reached. * * @param _self LinkedList to operate on * @param _addedValue Value to add to list */ function addNode( LinkedList storage _self, uint256 _addedValue ) internal { uint256 newNodeIndex = _self.lastUpdatedIndex.add(1); require( newNodeIndex == _self.dataArray.length, "LinkedListLibrary: Node must be added at next expected index in list" ); require( newNodeIndex < _self.dataSizeLimit, "LinkedListLibrary: Attempting to add node that exceeds data size limit" ); // Add node value _self.dataArray.push(_addedValue); // Update lastUpdatedIndex value _self.lastUpdatedIndex = newNodeIndex; } /* * Add new value to list by updating existing node. Updates only happen if node limit has been * reached. * * @param _self LinkedList to operate on * @param _addedValue Value to add to list */ function updateNode( LinkedList storage _self, uint256 _addedValue ) internal { // Determine the next node in list to be updated uint256 updateNodeIndex = _self.lastUpdatedIndex.add(1) % _self.dataSizeLimit; // Require that updated node has been previously added require( updateNodeIndex < _self.dataArray.length, "LinkedListLibrary: Attempting to update non-existent node" ); // Update node value and last updated index _self.dataArray[updateNodeIndex] = _addedValue; _self.lastUpdatedIndex = updateNodeIndex; } /* * Read list from the lastUpdatedIndex back the passed amount of data points. * * @param _self LinkedList to operate on * @param _dataPoints Number of data points to return */ function readList( LinkedList storage _self, uint256 _dataPoints ) internal view returns (uint256[] memory) { // Make sure query isn&#39;t for more data than collected require( _dataPoints <= _self.dataArray.length, "LinkedListLibrary: Querying more data than available" ); // Instantiate output array in memory uint256[] memory outputArray = new uint256[](_dataPoints); // Find head of list uint256 linkedListIndex = _self.lastUpdatedIndex; for (uint256 i = 0; i < _dataPoints; i++) { // Get value at index in linkedList outputArray[i] = _self.dataArray[linkedListIndex]; // Find next linked index linkedListIndex = linkedListIndex == 0 ? _self.dataSizeLimit.sub(1) : linkedListIndex.sub(1); } return outputArray; } } // File: contracts/meta-oracles/HistoricalPriceFeed.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title HistoricalPriceFeed * @author Set Protocol * * Contract used to store Historical price data from an off-chain oracle */ contract HistoricalPriceFeed is Ownable, LinkedListLibrary { using SafeMath for uint256; /* ============ Constants ============ */ uint256 constant DAYS_IN_DATASET = 200; /* ============ State Variables ============ */ uint256 public updateFrequency; uint256 public lastUpdatedAt; string public dataDescription; IMedian public medianizerInstance; LinkedList public historicalPriceData; /* ============ Constructor ============ */ /* * Historical Price Feed constructor. * Stores Historical prices according to passed in oracle address. Updates must be * triggered off chain to be stored in this smart contract. * * @param _updateFrequency How often new data can be logged, passe=d in seconds * @param _medianizerAddress The oracle address to read historical data from * @param _dataDescription Description of data in Data Bank * @param _seededValues Array of previous days&#39; Historical price values to seed * initial values in list. Should NOT contain the current * days price. */ constructor( uint256 _updateFrequency, address _medianizerAddress, string memory _dataDescription, uint256[] memory _seededValues ) public { // Set medianizer address, data description, and instantiate medianizer updateFrequency = _updateFrequency; dataDescription = _dataDescription; medianizerInstance = IMedian(_medianizerAddress); // Create initial values array from _seededValues and current price uint256[] memory initialValues = createInitialValues(_seededValues); // Define upper data size limit for linked list and input initial value initialize( historicalPriceData, DAYS_IN_DATASET, initialValues[0] ); // Cycle through input values array (skipping first value used to initialize LinkedList) // and add to historicalPriceData for (uint256 i = 1; i < initialValues.length; i++) { editList( historicalPriceData, initialValues[i] ); } // Set last updated timestamp lastUpdatedAt = block.timestamp; } /* ============ External ============ */ /* * Updates linked list with newest data point by querying medianizer. Is eligible to be * called every 24 hours. */ function poke() external { // Make sure 24 hours have passed since last update require( block.timestamp >= lastUpdatedAt.add(updateFrequency), "HistoricalPriceFeed: Not enough time passed between updates" ); // Update the timestamp to current block timestamp; Prevents re-entrancy lastUpdatedAt = block.timestamp; // Get current price uint256 newValue = uint256(medianizerInstance.read()); // Update linkedList with new price editList( historicalPriceData, newValue ); } /* * Query linked list for specified days of data. Will revert if number of days * passed exceeds amount of days collected. Will revert if not enough days of * data logged. * * @param _dataDays Number of days of data being queried * @returns Array of historical price data of length _dataDays */ function read( uint256 _dataDays ) external view returns (uint256[] memory) { return readList( historicalPriceData, _dataDays ); } /* * Change medianizer in case current one fails or is deprecated. Only contract * owner is allowed to change. * * @param _newMedianizerAddress Address of new medianizer to pull data from */ function changeMedianizer( address _newMedianizerAddress ) external onlyOwner { medianizerInstance = IMedian(_newMedianizerAddress); } /* ============ Private ============ */ /* * Create initialValues array from _seededValues and the current medianizer price. * Added to historicalPriceData in constructor. * * @param _seededValues Array of previous days&#39; historical price values to seed * @returns Array of initial values to add to historicalPriceData */ function createInitialValues( uint256[] memory _seededValues ) private returns (uint256[] memory) { // Get current value from medianizer uint256 currentValue = uint256(medianizerInstance.read()); // Instantiate outputArray uint256 seededValuesLength = _seededValues.length; uint256[] memory outputArray = new uint256[](seededValuesLength.add(1)); // Take values from _seededValues array and add to outputArray for (uint256 i = 0; i < _seededValues.length; i++) { outputArray[i] = _seededValues[i]; } // Add currentValue to outputArray outputArray[seededValuesLength] = currentValue; return outputArray; } }
Updates linked list with newest data point by querying medianizer. Is eligible to be called every 24 hours./ Make sure 24 hours have passed since last update Update the timestamp to current block timestamp; Prevents re-entrancy Get current price Update linkedList with new price
function poke() external { require( block.timestamp >= lastUpdatedAt.add(updateFrequency), "HistoricalPriceFeed: Not enough time passed between updates" ); lastUpdatedAt = block.timestamp; uint256 newValue = uint256(medianizerInstance.read()); editList( historicalPriceData, newValue ); }
6,689,904
./full_match/1/0x42b255be54d2a38b13ca7e242898134469c3EF08/sources/contracts/Market.sol
Given a token ID and a bidder, this method transfers the value of the bid to the shareholders. It also transfers the ownership of the media to the bid recipient. Finally, it removes the accepted bid and the current ask./ Transfer bid share to owner of media Transfer bid share to creator of media Transfer bid share to previous owner of media (if applicable) Transfer media to bid recipient Calculate the bid share for the new owner, equal to 100 - creatorShare - sellOnShare Set the previous owner share to the accepted bid's sell-on fee Remove the accepted bid
function _finalizeNFTTransfer(uint256 tokenId, address bidder) private { Bid memory bid = _tokenBidders[tokenId][bidder]; BidShares storage bidShares = _bidShares[tokenId]; IERC20 token = IERC20(bid.currency); token.safeTransfer( IERC721(mediaContract).ownerOf(tokenId), splitShare(bidShares.owner, bid.amount) ); token.safeTransfer( Media(mediaContract).tokenCreators(tokenId), splitShare(bidShares.creator, bid.amount) ); token.safeTransfer( Media(mediaContract).previousTokenOwners(tokenId), splitShare(bidShares.prevOwner, bid.amount) ); Media(mediaContract).auctionTransfer(tokenId, bid.recipient); bidShares.owner = Decimal.D256( uint256(100) .mul(Decimal.BASE) .sub(_bidShares[tokenId].creator.value) .sub(bid.sellOnShare.value) ); bidShares.prevOwner = bid.sellOnShare; delete _tokenBidders[tokenId][bidder]; emit BidShareUpdated(tokenId, bidShares); emit BidFinalized(tokenId, bid); }
3,046,383
pragma solidity ^0.4.24; import "../../TransferManager/ITransferManager.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title Transfer Manager module to automate blacklist and restrict transfers */ contract BlacklistTransferManager is ITransferManager { using SafeMath for uint256; bytes32 public constant ADMIN = "ADMIN"; struct BlacklistsDetails { uint256 startTime; uint256 endTime; uint256 repeatPeriodTime; } //hold the different blacklist details corresponds to its name mapping(bytes32 => BlacklistsDetails) public blacklists; //hold the different name of blacklist corresponds to a investor mapping(address => bytes32[]) investorToBlacklist; //get list of the addresses for a particular blacklist mapping(bytes32 => address[]) blacklistToInvestor; //mapping use to store the indexes for different blacklist types for a investor mapping(address => mapping(bytes32 => uint256)) investorToIndex; //mapping use to store the indexes for different investor for a blacklist type mapping(bytes32 => mapping(address => uint256)) blacklistToIndex; bytes32[] allBlacklists; // Emit when new blacklist type is added event AddBlacklistType( uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime ); // Emit when there is a change in the blacklist type event ModifyBlacklistType( uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime ); // Emit when the added blacklist type is deleted event DeleteBlacklistType( bytes32 _blacklistName ); // Emit when new investor is added to the blacklist type event AddInvestorToBlacklist( address indexed _investor, bytes32 _blacklistName ); // Emit when investor is deleted from the blacklist type event DeleteInvestorFromBlacklist( address indexed _investor, bytes32 _blacklistName ); /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public Module(_securityToken, _polyAddress) { } /** * @notice This function returns the signature of configure function */ function getInitFunction() public pure returns (bytes4) { return bytes4(0); } /** * @notice Used to verify the transfer transaction * @param _from Address of the sender * @dev Restrict the blacklist address to transfer tokens * if the current time is between the timeframe define for the * blacklist type associated with the _from address */ function verifyTransfer(address _from, address /* _to */, uint256 /* _amount */, bytes /* _data */, bool /* _isTransfer */) public returns(Result) { if (!paused) { if (investorToBlacklist[_from].length != 0) { for (uint256 i = 0; i < investorToBlacklist[_from].length; i++) { uint256 endTimeTemp = blacklists[investorToBlacklist[_from][i]].endTime; uint256 startTimeTemp = blacklists[investorToBlacklist[_from][i]].startTime; uint256 repeatPeriodTimeTemp = blacklists[investorToBlacklist[_from][i]].repeatPeriodTime * 1 days; /*solium-disable-next-line security/no-block-members*/ if (now > startTimeTemp) { // Find the repeating parameter that will be used to calculate the new startTime and endTime // based on the new current time value /*solium-disable-next-line security/no-block-members*/ uint256 repeater = (now.sub(startTimeTemp)).div(repeatPeriodTimeTemp); /*solium-disable-next-line security/no-block-members*/ if (startTimeTemp.add(repeatPeriodTimeTemp.mul(repeater)) <= now && endTimeTemp.add(repeatPeriodTimeTemp.mul(repeater)) >= now) { return Result.INVALID; } } } } } return Result.NA; } /** * @notice Used to add the blacklist type * @param _startTime Start date of the blacklist type * @param _endTime End date of the blacklist type * @param _blacklistName Name of the blacklist type * @param _repeatPeriodTime Repeat period of the blacklist type */ function addBlacklistType(uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime) public withPerm(ADMIN) { _addBlacklistType(_startTime, _endTime, _blacklistName, _repeatPeriodTime); } /** * @notice Used to add the multiple blacklist type * @param _startTimes Start date of the blacklist type * @param _endTimes End date of the blacklist type * @param _blacklistNames Name of the blacklist type * @param _repeatPeriodTimes Repeat period of the blacklist type */ function addBlacklistTypeMulti(uint256[] _startTimes, uint256[] _endTimes, bytes32[] _blacklistNames, uint256[] _repeatPeriodTimes) external withPerm(ADMIN) { require (_startTimes.length == _endTimes.length && _endTimes.length == _blacklistNames.length && _blacklistNames.length == _repeatPeriodTimes.length, "Input array's length mismatch"); for (uint256 i = 0; i < _startTimes.length; i++){ _addBlacklistType(_startTimes[i], _endTimes[i], _blacklistNames[i], _repeatPeriodTimes[i]); } } /** * @notice Internal function */ function _validParams(uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime) internal view { require(_blacklistName != bytes32(0), "Invalid blacklist name"); require(_startTime >= now && _startTime < _endTime, "Invalid start or end date"); require(_repeatPeriodTime.mul(1 days) >= _endTime.sub(_startTime) || _repeatPeriodTime == 0); } /** * @notice Used to modify the details of a given blacklist type * @param _startTime Start date of the blacklist type * @param _endTime End date of the blacklist type * @param _blacklistName Name of the blacklist type * @param _repeatPeriodTime Repeat period of the blacklist type */ function modifyBlacklistType(uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime) public withPerm(ADMIN) { require(blacklists[_blacklistName].endTime != 0, "Blacklist type doesn't exist"); _validParams(_startTime, _endTime, _blacklistName, _repeatPeriodTime); blacklists[_blacklistName] = BlacklistsDetails(_startTime, _endTime, _repeatPeriodTime); emit ModifyBlacklistType(_startTime, _endTime, _blacklistName, _repeatPeriodTime); } /** * @notice Used to modify the details of a given multpile blacklist types * @param _startTimes Start date of the blacklist type * @param _endTimes End date of the blacklist type * @param _blacklistNames Name of the blacklist type * @param _repeatPeriodTimes Repeat period of the blacklist type */ function modifyBlacklistTypeMulti(uint256[] _startTimes, uint256[] _endTimes, bytes32[] _blacklistNames, uint256[] _repeatPeriodTimes) external withPerm(ADMIN) { require (_startTimes.length == _endTimes.length && _endTimes.length == _blacklistNames.length && _blacklistNames.length == _repeatPeriodTimes.length, "Input array's length mismatch"); for (uint256 i = 0; i < _startTimes.length; i++){ modifyBlacklistType(_startTimes[i], _endTimes[i], _blacklistNames[i], _repeatPeriodTimes[i]); } } /** * @notice Used to delete the blacklist type * @param _blacklistName Name of the blacklist type */ function deleteBlacklistType(bytes32 _blacklistName) public withPerm(ADMIN) { require(blacklists[_blacklistName].endTime != 0, "Blacklist type doesn’t exist"); require(blacklistToInvestor[_blacklistName].length == 0, "Investors are associated with the blacklist"); // delete blacklist type delete(blacklists[_blacklistName]); uint256 i = 0; for (i = 0; i < allBlacklists.length; i++) { if (allBlacklists[i] == _blacklistName) { break; } } if (i != allBlacklists.length -1) { allBlacklists[i] = allBlacklists[allBlacklists.length -1]; } allBlacklists.length--; emit DeleteBlacklistType(_blacklistName); } /** * @notice Used to delete the multiple blacklist type * @param _blacklistNames Name of the blacklist type */ function deleteBlacklistTypeMulti(bytes32[] _blacklistNames) external withPerm(ADMIN) { for(uint256 i = 0; i < _blacklistNames.length; i++){ deleteBlacklistType(_blacklistNames[i]); } } /** * @notice Used to assign the blacklist type to the investor * @param _investor Address of the investor * @param _blacklistName Name of the blacklist */ function addInvestorToBlacklist(address _investor, bytes32 _blacklistName) public withPerm(ADMIN) { require(blacklists[_blacklistName].endTime != 0, "Blacklist type doesn't exist"); require(_investor != address(0), "Invalid investor address"); uint256 index = investorToIndex[_investor][_blacklistName]; if (index < investorToBlacklist[_investor].length) require(investorToBlacklist[_investor][index] != _blacklistName, "Blacklist already added to investor"); uint256 investorIndex = investorToBlacklist[_investor].length; // Add blacklist index to the investor investorToIndex[_investor][_blacklistName] = investorIndex; uint256 blacklistIndex = blacklistToInvestor[_blacklistName].length; // Add investor index to the blacklist blacklistToIndex[_blacklistName][_investor] = blacklistIndex; investorToBlacklist[_investor].push(_blacklistName); blacklistToInvestor[_blacklistName].push(_investor); emit AddInvestorToBlacklist(_investor, _blacklistName); } /** * @notice Used to assign the blacklist type to the multiple investor * @param _investors Address of the investor * @param _blacklistName Name of the blacklist */ function addInvestorToBlacklistMulti(address[] _investors, bytes32 _blacklistName) external withPerm(ADMIN){ for(uint256 i = 0; i < _investors.length; i++){ addInvestorToBlacklist(_investors[i], _blacklistName); } } /** * @notice Used to assign the multiple blacklist type to the multiple investor * @param _investors Address of the investor * @param _blacklistNames Name of the blacklist */ function addMultiInvestorToBlacklistMulti(address[] _investors, bytes32[] _blacklistNames) external withPerm(ADMIN){ require (_investors.length == _blacklistNames.length, "Input array's length mismatch"); for(uint256 i = 0; i < _investors.length; i++){ addInvestorToBlacklist(_investors[i], _blacklistNames[i]); } } /** * @notice Used to assign the new blacklist type to the investor * @param _startTime Start date of the blacklist type * @param _endTime End date of the blacklist type * @param _blacklistName Name of the blacklist type * @param _repeatPeriodTime Repeat period of the blacklist type * @param _investor Address of the investor */ function addInvestorToNewBlacklist(uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime, address _investor) external withPerm(ADMIN){ _addBlacklistType(_startTime, _endTime, _blacklistName, _repeatPeriodTime); addInvestorToBlacklist(_investor, _blacklistName); } /** * @notice Used to delete the investor from all the associated blacklist types * @param _investor Address of the investor */ function deleteInvestorFromAllBlacklist(address _investor) public withPerm(ADMIN) { require(_investor != address(0), "Invalid investor address"); require(investorToBlacklist[_investor].length != 0, "Investor is not associated to any blacklist type"); uint256 index = investorToBlacklist[_investor].length - 1; for (uint256 i = index; i >= 0 && i <= index; i--){ deleteInvestorFromBlacklist(_investor, investorToBlacklist[_investor][i]); } } /** * @notice Used to delete the multiple investor from all the associated blacklist types * @param _investor Address of the investor */ function deleteInvestorFromAllBlacklistMulti(address[] _investor) external withPerm(ADMIN) { for(uint256 i = 0; i < _investor.length; i++){ deleteInvestorFromAllBlacklist(_investor[i]); } } /** * @notice Used to delete the investor from the blacklist * @param _investor Address of the investor * @param _blacklistName Name of the blacklist */ function deleteInvestorFromBlacklist(address _investor, bytes32 _blacklistName) public withPerm(ADMIN) { require(_investor != address(0), "Invalid investor address"); require(_blacklistName != bytes32(0),"Invalid blacklist name"); require(investorToBlacklist[_investor][investorToIndex[_investor][_blacklistName]] == _blacklistName, "Investor not associated to the blacklist"); // delete the investor from the blacklist type uint256 _blacklistIndex = blacklistToIndex[_blacklistName][_investor]; uint256 _len = blacklistToInvestor[_blacklistName].length; if ( _blacklistIndex < _len -1) { blacklistToInvestor[_blacklistName][_blacklistIndex] = blacklistToInvestor[_blacklistName][_len - 1]; blacklistToIndex[_blacklistName][blacklistToInvestor[_blacklistName][_blacklistIndex]] = _blacklistIndex; } blacklistToInvestor[_blacklistName].length--; // delete the investor index from the blacklist delete(blacklistToIndex[_blacklistName][_investor]); // delete the blacklist from the investor uint256 _investorIndex = investorToIndex[_investor][_blacklistName]; _len = investorToBlacklist[_investor].length; if ( _investorIndex < _len -1) { investorToBlacklist[_investor][_investorIndex] = investorToBlacklist[_investor][_len - 1]; investorToIndex[_investor][investorToBlacklist[_investor][_investorIndex]] = _investorIndex; } investorToBlacklist[_investor].length--; // delete the blacklist index from the invetsor delete(investorToIndex[_investor][_blacklistName]); emit DeleteInvestorFromBlacklist(_investor, _blacklistName); } /** * @notice Used to delete the multiple investor from the blacklist * @param _investors address of the investor * @param _blacklistNames name of the blacklist */ function deleteMultiInvestorsFromBlacklistMulti(address[] _investors, bytes32[] _blacklistNames) external withPerm(ADMIN) { require (_investors.length == _blacklistNames.length, "Input array's length mismatch"); for(uint256 i = 0; i < _investors.length; i++){ deleteInvestorFromBlacklist(_investors[i], _blacklistNames[i]); } } function _addBlacklistType(uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime) internal { require(blacklists[_blacklistName].endTime == 0, "Blacklist type already exist"); _validParams(_startTime, _endTime, _blacklistName, _repeatPeriodTime); blacklists[_blacklistName] = BlacklistsDetails(_startTime, _endTime, _repeatPeriodTime); allBlacklists.push(_blacklistName); emit AddBlacklistType(_startTime, _endTime, _blacklistName, _repeatPeriodTime); } /** * @notice get the list of the investors of a blacklist type * @param _blacklistName Name of the blacklist type * @return address List of investors associated with the blacklist */ function getListOfAddresses(bytes32 _blacklistName) external view returns(address[]) { require(blacklists[_blacklistName].endTime != 0, "Blacklist type doesn't exist"); return blacklistToInvestor[_blacklistName]; } /** * @notice get the list of the investors of a blacklist type * @param _user Address of the user * @return bytes32 List of blacklist names associated with the given address */ function getBlacklistNamesToUser(address _user) external view returns(bytes32[]) { return investorToBlacklist[_user]; } /** * @notice get the list of blacklist names * @return bytes32 Array of blacklist names */ function getAllBlacklists() external view returns(bytes32[]) { return allBlacklists; } /** * @notice Return the permissions flag that are associated with blacklist transfer manager */ function getPermissions() public view returns(bytes32[]) { bytes32[] memory allPermissions = new bytes32[](1); allPermissions[0] = ADMIN; return allPermissions; } }
Used to delete the multiple investor from the blacklist _investors address of the investor _blacklistNames name of the blacklist/
function deleteMultiInvestorsFromBlacklistMulti(address[] _investors, bytes32[] _blacklistNames) external withPerm(ADMIN) { require (_investors.length == _blacklistNames.length, "Input array's length mismatch"); for(uint256 i = 0; i < _investors.length; i++){ deleteInvestorFromBlacklist(_investors[i], _blacklistNames[i]); } }
12,896,687
./full_match/4/0x979cde57F00Dc252E37D1cEcabA493F55aBD0E21/sources/contracts/DMonks.sol
Public mints
function mint(uint amount) public payable { uint currentTotalSupply = totalSupply(); require(currentTotalSupply >= MAX_PRIZE_MINTS, "DeadFellazToken: Not yet launched"); require(currentTotalSupply+amount <= MAX_SUPPLY, "DeadFellazToken: Not enough mints remaining"); require(amount <= MAX_MINT_AMOUNT, 'DeadFellazToken: mint amount exceeds maximum'); require(msg.value > 0 && msg.value == amount * PRICE, "DeadFellazToken: Not enough value sent"); _mintAmountTo(msg.sender, amount, currentTotalSupply);
12,368,054
// File: contracts/lib/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 * @dev A standard interface for tokens. * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20 { /// @dev Returns the total token supply function totalSupply() public view returns (uint256 supply); /// @dev Returns the account balance of the account with address _owner function balanceOf(address _owner) public view returns (uint256 balance); /// @dev Transfers _value number of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); /// @dev Transfers _value number of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @dev Allows _spender to withdraw from the msg.sender's account up to the _value amount function approve(address _spender, uint256 _value) public returns (bool success); /// @dev Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // File: contracts/FundsForwarder.sol interface IGivethBridge { function donate(uint64 giverId, uint64 receiverId) external payable; function donate(uint64 giverId, uint64 receiverId, address token, uint _amount) external payable; } interface IFundsForwarderFactory { function bridge() external returns (address); function escapeHatchCaller() external returns (address); function escapeHatchDestination() external returns (address); } interface IMolochDao { function approvedToken() external returns (address); function members(address member) external returns (address, uint256, bool, uint256); function ragequit(uint sharesToBurn) external; } interface IWEth { function withdraw(uint wad) external; function balanceOf(address guy) external returns (uint); } contract FundsForwarder { uint64 public receiverId; uint64 public giverId; IFundsForwarderFactory public fundsForwarderFactory; string private constant ERROR_ERC20_APPROVE = "ERROR_ERC20_APPROVE"; string private constant ERROR_BRIDGE_CALL = "ERROR_BRIDGE_CALL"; string private constant ERROR_ZERO_BRIDGE = "ERROR_ZERO_BRIDGE"; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_TOKEN_TRANSFER = "RECOVER_TOKEN_TRANSFER"; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; uint private constant MAX_UINT = uint(-1); event Forwarded(address to, address token, uint balance); event EscapeHatchCalled(address token, uint amount); constructor() public { /// @dev From AragonOS's Autopetrified contract // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). fundsForwarderFactory = IFundsForwarderFactory(address(-1)); } /** * Fallback function to receive ETH donations */ function() public payable {} /** * @dev Initialize can only be called once. * @notice msg.sender MUST be the _fundsForwarderFactory Contract * Its address must be a contract with three public getters: * - bridge(): Returns the bridge address * - escapeHatchCaller(): Returns the escapeHatchCaller address * - escapeHatchDestination(): Returns the escashouldpeHatchDestination address * @param _giverId The adminId of the liquidPledging pledge admin who is donating * @param _receiverId The adminId of the liquidPledging pledge admin receiving the donation */ function initialize(uint64 _giverId, uint64 _receiverId) public { /// @dev onlyInit method from AragonOS's Initializable contract require(fundsForwarderFactory == address(0), ERROR_ALREADY_INITIALIZED); /// @dev Setting fundsForwarderFactory, serves as calling initialized() fundsForwarderFactory = IFundsForwarderFactory(msg.sender); /// @dev Make sure that the fundsForwarderFactory is a contract and has a bridge method require(fundsForwarderFactory.bridge() != address(0), ERROR_ZERO_BRIDGE); receiverId = _receiverId; giverId = _giverId; } /** * Transfer tokens/eth to the bridge. Transfer the entire balance of the contract * @param _token the token to transfer. 0x0 for ETH */ function forward(address _token) public { IGivethBridge bridge = IGivethBridge(fundsForwarderFactory.bridge()); require(bridge != address(0), ERROR_ZERO_BRIDGE); uint balance; bool result; /// @dev Logic for ether if (_token == address(0)) { balance = address(this).balance; /// @dev Call donate() with two arguments, for tokens /// Low level .call must be used due to function overloading /// keccak250("donate(uint64,uint64)") = bde60ac9 /* solium-disable-next-line security/no-call-value */ result = address(bridge).call.value(balance)( 0xbde60ac9, giverId, receiverId ); /// @dev Logic for tokens } else { ERC20 token = ERC20(_token); balance = token.balanceOf(this); /// @dev Since the bridge is a trusted contract, the max allowance /// will be set on the first token transfer. Then it's skipped /// Numbers for DAI First tx | n+1 txs /// approve(_, balance) 66356 51356 /// approve(_, MAX_UINT) 78596 39103 /// +12240 -12253 /// Worth it if forward is called more than once for each token if (token.allowance(address(this), bridge) < balance) { require(token.approve(bridge, MAX_UINT), ERROR_ERC20_APPROVE); } /// @dev Call donate() with four arguments, for tokens /// Low level .call must be used due to function overloading /// keccak256("donate(uint64,uint64,address,uint256)") = 4c4316c7 /* solium-disable-next-line security/no-low-level-calls */ result = address(bridge).call( 0x4c4316c7, giverId, receiverId, token, balance ); } require(result, ERROR_BRIDGE_CALL); emit Forwarded(bridge, _token, balance); } /** * Transfer multiple tokens/eth to the bridge. Simplies UI interactions * @param _tokens the array of tokens to transfer. 0x0 for ETH */ function forwardMultiple(address[] _tokens) public { uint tokensLength = _tokens.length; for (uint i = 0; i < tokensLength; i++) { forward(_tokens[i]); } } /** * Transfer tokens from a Moloch DAO by calling ragequit on all shares * @param _molochDao Address of a Moloch DAO * @param _convertWeth Flag to indicate that this DAO uses WETH */ function forwardMoloch(address _molochDao, bool _convertWeth) public { IMolochDao molochDao = IMolochDao(_molochDao); (,uint shares,,) = molochDao.members(address(this)); molochDao.ragequit(shares); address approvedToken = molochDao.approvedToken(); if (_convertWeth) { IWEth weth = IWEth(approvedToken); weth.withdraw(weth.balanceOf(address(this))); forward(address(0)); } else { forward(molochDao.approvedToken()); } } /** * @notice Send funds to recovery address (escapeHatchDestination). * The `escapeHatch()` should only be called as a last resort if a * security issue is uncovered or something unexpected happened * @param _token Token balance to be sent to recovery vault. * * @dev Only the escapeHatchCaller can trigger this function * @dev The escapeHatchCaller address must not have control over escapeHatchDestination * @dev Function extracted from the Escapable contract (by Jordi Baylina and Adrià Massanet) * Instead of storing the caller, destination and owner addresses, * it fetches them from the parent contract. */ function escapeHatch(address _token) public { /// @dev Serves as the original contract's onlyEscapeHatchCaller require(msg.sender == fundsForwarderFactory.escapeHatchCaller(), ERROR_DISALLOWED); address escapeHatchDestination = fundsForwarderFactory.escapeHatchDestination(); uint256 balance; if (_token == 0x0) { balance = address(this).balance; escapeHatchDestination.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.balanceOf(this); require(token.transfer(escapeHatchDestination, balance), ERROR_TOKEN_TRANSFER); } emit EscapeHatchCalled(_token, balance); } } // File: contracts/lib/IsContract.sol /* * SPDX-License-Identitifer: MIT * Credit to @aragonOS */ contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: contracts/lib/Owned.sol /// @title Owned /// @author Adrià Massanet <[email protected]> /// @notice The Owned contract has an owner address, and provides basic /// authorization control functions, this simplifies & the implementation of /// user permissions; this contract has three work flows for a change in /// ownership, the first requires the new owner to validate that they have the /// ability to accept ownership, the second allows the ownership to be /// directly transfered without requiring acceptance, and the third allows for /// the ownership to be removed to allow for decentralization contract Owned { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed by, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); event OwnershipRemoved(); /// @dev The constructor sets the `msg.sender` as the`owner` of the contract constructor() public { owner = msg.sender; } /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require (msg.sender == owner,"err_ownedNotOwner"); _; } /// @dev In this 1st option for ownership transfer `proposeOwnership()` must /// be called first by the current `owner` then `acceptOwnership()` must be /// called by the `newOwnerCandidate` /// @notice `onlyOwner` Proposes to transfer control of the contract to a /// new owner /// @param _newOwnerCandidate The address being proposed as the new owner function proposeOwnership(address _newOwnerCandidate) public onlyOwner { newOwnerCandidate = _newOwnerCandidate; emit OwnershipRequested(msg.sender, newOwnerCandidate); } /// @notice Can only be called by the `newOwnerCandidate`, accepts the /// transfer of ownership function acceptOwnership() public { require(msg.sender == newOwnerCandidate,"err_ownedNotCandidate"); address oldOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = 0x0; emit OwnershipTransferred(oldOwner, owner); } /// @dev In this 2nd option for ownership transfer `changeOwnership()` can /// be called and it will immediately assign ownership to the `newOwner` /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner function changeOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0x0,"err_ownedInvalidAddress"); address oldOwner = owner; owner = _newOwner; newOwnerCandidate = 0x0; emit OwnershipTransferred(oldOwner, owner); } /// @dev In this 3rd option for ownership transfer `removeOwnership()` can /// be called and it will immediately assign ownership to the 0x0 address; /// it requires a 0xdece be input as a parameter to prevent accidental use /// @notice Decentralizes the contract, this operation cannot be undone /// @param _dac `0xdac` has to be entered for this function to work function removeOwnership(address _dac) public onlyOwner { require(_dac == 0xdac,"err_ownedInvalidDac"); owner = 0x0; newOwnerCandidate = 0x0; emit OwnershipRemoved(); } } // File: contracts/lib/Escapable.sol /* Copyright 2016, Jordi Baylina Contributor: Adrià Massanet <[email protected]> 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/>. */ /// @dev `Escapable` is a base level contract built off of the `Owned` /// contract; it creates an escape hatch function that can be called in an /// emergency that will allow designated addresses to send any ether or tokens /// held in the contract to an `escapeHatchDestination` as long as they were /// not blacklisted contract Escapable is Owned { address public escapeHatchCaller; address public escapeHatchDestination; mapping (address=>bool) private escapeBlacklist; // Token contract addresses /// @notice The Constructor assigns the `escapeHatchDestination` and the /// `escapeHatchCaller` /// @param _escapeHatchCaller The address of a trusted account or contract /// to call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` /// cannot move funds out of `escapeHatchDestination` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract; if a neutral address /// is required, the WHG Multisig is an option: /// 0x8Ff920020c8AD673661c8117f2855C384758C572 constructor(address _escapeHatchCaller, address _escapeHatchDestination) public { escapeHatchCaller = _escapeHatchCaller; escapeHatchDestination = _escapeHatchDestination; } /// @dev The addresses preassigned as `escapeHatchCaller` or `owner` /// are the only addresses that can call a function with this modifier modifier onlyEscapeHatchCallerOrOwner { require ( (msg.sender == escapeHatchCaller)||(msg.sender == owner), "err_escapableInvalidCaller" ); _; } /// @notice Creates the blacklist of tokens that are not able to be taken /// out of the contract; can only be done at the deployment, and the logic /// to add to the blacklist will be in the constructor of a child contract /// @param _token the token contract address that is to be blacklisted function blacklistEscapeToken(address _token) internal { escapeBlacklist[_token] = true; emit EscapeHatchBlackistedToken(_token); } /// @notice Checks to see if `_token` is in the blacklist of tokens /// @param _token the token address being queried /// @return False if `_token` is in the blacklist and can't be taken out of /// the contract via the `escapeHatch()` function isTokenEscapable(address _token) public view returns (bool) { return !escapeBlacklist[_token]; } /// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened /// @param _token to transfer, use 0x0 for ether function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner { require(escapeBlacklist[_token]==false,"err_escapableBlacklistedToken"); uint256 balance; /// @dev Logic for ether if (_token == 0x0) { balance = address(this).balance; escapeHatchDestination.transfer(balance); emit EscapeHatchCalled(_token, balance); return; } /// @dev Logic for tokens ERC20 token = ERC20(_token); balance = token.balanceOf(this); require(token.transfer(escapeHatchDestination, balance),"err_escapableTransfer"); emit EscapeHatchCalled(_token, balance); } /// @notice Changes the address assigned to call `escapeHatch()` /// @param _newEscapeHatchCaller The address of a trusted account or /// contract to call `escapeHatch()` to send the value in this contract to /// the `escapeHatchDestination`; it would be ideal that `escapeHatchCaller` /// cannot move funds out of `escapeHatchDestination` function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner { escapeHatchCaller = _newEscapeHatchCaller; } event EscapeHatchBlackistedToken(address token); event EscapeHatchCalled(address token, uint amount); } // File: contracts/FundsForwarderFactory.sol contract FundsForwarderFactory is Escapable, IsContract { address public bridge; address public childImplementation; string private constant ERROR_NOT_A_CONTRACT = "ERROR_NOT_A_CONTRACT"; string private constant ERROR_HATCH_CALLER = "ERROR_HATCH_CALLER"; string private constant ERROR_HATCH_DESTINATION = "ERROR_HATCH_DESTINATION"; event NewFundForwarder(address indexed _giver, uint64 indexed _receiverId, address fundsForwarder); event BridgeChanged(address newBridge); event ChildImplementationChanged(address newChildImplementation); /** * @notice Create a new factory for deploying Giveth FundForwarders * @dev Requires a deployed bridge * @param _bridge Bridge address * @param _escapeHatchCaller The address of a trusted account or contract to * call `escapeHatch()` to send the ether in this contract to the * `escapeHatchDestination` it would be ideal if `escapeHatchCaller` cannot move * funds out of `escapeHatchDestination` * @param _escapeHatchDestination The address of a safe location (usually a * Multisig) to send the value held in this contract in an emergency */ constructor( address _bridge, address _escapeHatchCaller, address _escapeHatchDestination, address _childImplementation ) Escapable(_escapeHatchCaller, _escapeHatchDestination) public { require(isContract(_bridge), ERROR_NOT_A_CONTRACT); bridge = _bridge; // Set the escapeHatch params to the same as in the bridge Escapable bridgeInstance = Escapable(_bridge); require(_escapeHatchCaller == bridgeInstance.escapeHatchCaller(), ERROR_HATCH_CALLER); require(_escapeHatchDestination == bridgeInstance.escapeHatchDestination(), ERROR_HATCH_DESTINATION); // Set the owner to the same as in the bridge changeOwnership(bridgeInstance.owner()); // Deploy FundsForwarder if (_childImplementation == address(0)) { childImplementation = new FundsForwarder(); } else { childImplementation = _childImplementation; } } /** * @notice Change the bridge address. * @param _bridge New bridge address */ function changeBridge(address _bridge) external onlyEscapeHatchCallerOrOwner { bridge = _bridge; emit BridgeChanged(_bridge); } /** * @notice Change the childImplementation address. * @param _childImplementation New childImplementation address */ function changeChildImplementation(address _childImplementation) external onlyEscapeHatchCallerOrOwner { childImplementation = _childImplementation; emit ChildImplementationChanged(_childImplementation); } /** * @param _giverId The adminId of the liquidPledging pledge admin who is donating * @param _receiverId The adminId of the liquidPledging pledge admin receiving the donation */ function newFundsForwarder(uint64 _giverId, uint64 _receiverId) public { address fundsForwarder = _deployMinimal(childImplementation); FundsForwarder(fundsForwarder).initialize(_giverId, _receiverId); // Store a registry of fundForwarders as events emit NewFundForwarder(_giverId, _receiverId, fundsForwarder); } /** * @notice Deploys a minimal forwarding proxy that is not upgradable * From ZepelinOS https://github.com/zeppelinos/zos/blob/v2.4.0/packages/lib/contracts/upgradeability/ProxyFactory.sol */ function _deployMinimal(address _logic) internal returns (address proxy) { // Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol bytes20 targetBytes = bytes20(_logic); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } } }
Can only be called by the `newOwnerCandidate`, accepts the transfer of ownership
function acceptOwnership() public { require(msg.sender == newOwnerCandidate,"err_ownedNotCandidate"); address oldOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = 0x0; emit OwnershipTransferred(oldOwner, owner); }
2,572,907
./full_match/80001/0x8cBC7B15e7423042DDb37E5dBBCD9Ad8cf83d4c6/sources/contracts/AvatarBuilder.sol
Check if the avatar is owned by the sender Check if the pieces are owned by the sender Burn all the pieces used for the build
function updateAvatar( uint256 tokenId, string calldata tokenURI, bytes32 metadataHash, uint256[] calldata pieceTokensToBurn, string[] calldata piecesToMint, bytes calldata signature ) external nonReentrant returns (uint256[] memory) { if (_avatarNFTContract.ownerOf(tokenId) != msg.sender) revert AvatarBuilder__CallerIsNotTheAvatarOwner(); for (uint256 i = 0; i < pieceTokensToBurn.length; i++) { if (_pieceNFTContract.ownerOf(pieceTokensToBurn[i]) != msg.sender) revert AvatarBuilder__CallerIsNotThePiecesOwner(); } "_", "_", tokenURI, "_", ); if ( !SignatureChecker.isValidSignatureNow( _signer, signature ) ) { revert AvatarBuilder__InvalidSignature(); } for (uint256 i = 0; i < pieceTokensToBurn.length; i++) { _pieceNFTContract.burn(pieceTokensToBurn[i]); } for (uint256 i = 0; i < piecesToMint.length; i++) { tokenIds[i] = _pieceNFTContract.mint(msg.sender, piecesToMint[i]); } _avatarNFTContract.updateTokenURI(tokenId, tokenURI); emit AvatarUpdated(tokenId, tokenURI, pieceTokensToBurn, tokenIds); return tokenIds; }
5,643,738
./full_match/1/0x1f9695C836eC9d12391Ed46cf4fc50dA664F5Dc2/sources/browser/souls.sol
_name = "Name must be hard coded";
function name() external view returns (string memory _name){ return __name; }
4,986,146
./full_match/3/0x98BEdf4BC0a1b05C0AdE19d84f8A03277Ae85B6d/sources/contracts/CallTheAlgo.sol
Parametro riferito alla cartella contenente NEFFIE/l' ipfs sta a rappresentare l' ipfs dell' archivepassa parametri ad algoritmostring coffie_uri;coffie_uri.append("ipfs:", _hashfolder ,"/output.jpg");------------------------------------createToken(name, algo, "neffie", "symbol", currentCoffieUri);
function callAlgo(string memory _hashfolder,string memory _hashNeffie) public payable{ if (provable.getPrice("computation") > address(this).balance) { emit LogNewProvableQuery("Provable query was NOT sent, please add some ETH to cover for the query fee"); emit LogNewProvableQuery("Provable query was sent, standing by for the answer.."); provable_query("computation",["QmaJHZTY5gRpaH7A918WzV9vDfjcwx1B3hSMbNqc23pSNR", _hashfolder]); emit has(_hashfolder); emit algoCalled('algoritmo'); } } currentCoffieUri = _uri; tokenId++; current_user = msg.sender; nft.mint(msg.sender, tokenId, currentCoffieUri);
8,176,193
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; // https://solidity-by-example.org/enum/ contact Enum { // Enum representing order status enum Status { Pending, Shipped, Accepted, Rejected, Cancelled, } Status public status; function get () public view returns (Status) { return status; } function set (Status _status) public { status = _status; } function cancel() public { status = Status.Cancelled; } function reset() public { delete status; } }
https:solidity-by-example.org/enum/ Enum representing order status
contact Enum { enum Status { Pending, Shipped, Accepted, Rejected, Cancelled, } Status public status; function get () public view returns (Status) { return status; } function set (Status _status) public { status = _status; } function cancel() public { status = Status.Cancelled; } function reset() public { delete status; } }
12,944,067
//Address: 0x049a5bf874f241d94232137ef728a9c7dd0d7550 //Contract name: DataTradingToken //Balance: 0 Ether //Verification Date: 1/9/2018 //Transacion Count: 682 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title ERC20Interface * @dev Standart version of ERC20 interface */ contract ERC20Interface { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @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 current 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)); owner = newOwner; } } /** * @title DataTradingToken * @dev Implemantation of the DataTrading token */ contract DataTradingToken is Ownable, ERC20Interface { string public constant symbol = "DTT"; string public constant name = "DataTrading Token"; uint8 public constant decimals = 18; uint256 private _unmintedTokens = 360000000*uint(10)**decimals; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Gets the balance of the specified address * @param _owner The address to query the the balance of * @return An uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev Transfer token to a specified address * @param _to The address to transfer to * @param _value The amount to be transferred */ function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balances[msg.sender] >= _value); assert(balances[_to] + _value >= balances[_to]); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); assert(balances[_to] + _value >= balances[_to]); balances[_from] = balances[_from] - _value; balances[_to] = balances[_to] + _value; allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value; Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf 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 success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens than an owner allowed to a spender * @param _owner The address which owns the funds * @param _spender The address which will spend the funds * @return A uint specifing the amount of tokens still avaible for the spender */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Mint DataTrading tokens. No more than 360,000,000 DTT can be minted * @param _target The address to which new tokens will be minted * @param _mintedAmount The amout of tokens to be minted */ function mintTokens(address _target, uint256 _mintedAmount) public onlyOwner returns (bool success){ require(_mintedAmount <= _unmintedTokens); balances[_target] += _mintedAmount; _unmintedTokens -= _mintedAmount; totalSupply += _mintedAmount; return true; } /** * @dev Mint DataTrading tokens and aproves the passed address to spend the minted amount of tokens * No more than 360,000,000 DTT can be minted * @param _target The address to which new tokens will be minted * @param _mintedAmount The amout of tokens to be minted * @param _spender The address which will spend minted funds */ function mintTokensWithApproval(address _target, uint256 _mintedAmount, address _spender) public onlyOwner returns (bool success){ require(_mintedAmount <= _unmintedTokens); balances[_target] += _mintedAmount; _unmintedTokens -= _mintedAmount; totalSupply += _mintedAmount; allowed[_target][_spender] += _mintedAmount; return true; } /** * @dev Decrease amount of DataTrading tokens that can be minted * @param _burnedAmount The amout of unminted tokens to be burned */ function burnUnmintedTokens(uint256 _burnedAmount) public onlyOwner returns (bool success){ require(_burnedAmount <= _unmintedTokens); _unmintedTokens -= _burnedAmount; return true; } }
Transfer token to a specified address _to The address to transfer to _value The amount to be transferred/
function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balances[msg.sender] >= _value); assert(balances[_to] + _value >= balances[_to]); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; }
1,071,387
./partial_match/4/0x5C5351fBCE9a591Ed29BDB3E177Bb9De24629F3a/sources/LinkerPCS007.sol
Bid to NFT This is an internal function which should be called from user-implemented external function. Its purpose is to show and properly initialize data structures when using this implementation. _tokenId Id for which we want info./
function bid(uint256 _tokenId) external payable validNFToken(_tokenId) { require( msg.sender != highestBidder[_tokenId], "The sender is the highest bidder already." ); require( block.number < startedAt[_tokenId] + duration[_tokenId], "The auction has been expired" ); require( msg.value > minimumPrice[_tokenId], "Bidding price is lower than the minimum price." ); require( msg.value >= biddingPrice[_tokenId] + unit[_tokenId], "Bidding price is lower than the highest price." ); address payable wallet = address(uint160(highestBidder[_tokenId])); wallet.transfer(biddingPrice[_tokenId]); biddingPrice[_tokenId] = msg.value; _setBiddingPrice(_tokenId); _setHighestBidder(_tokenId); }
8,513,857
./full_match/1/0x517a197ad807703D99d919afcd720B5F4a2AA9fC/sources/contracts/BlissFeeHandler.sol
Refresh approval values
function refreshApprovals() external onlyOwner { bliss.approve(address(UNIRouter), uint256(-1)); wbtc.approve(address(UNIRouter), uint256(-1)); }
16,393,996
// SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; pragma abicoder v2; // solhint-disable-line import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./interfaces/ICrowdsale.sol"; /** * @title Crowdsale * @author Enjinstarter * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ERC20 tokens. 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 ReentrancyGuard, ICrowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAX_NUM_PAYMENT_TOKENS = 10; uint256 public constant TOKEN_MAX_DECIMALS = 18; uint256 public constant TOKEN_SELLING_SCALE = 10**TOKEN_MAX_DECIMALS; // Amount of tokens sold uint256 public tokensSold; // The token being sold // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names address private _tokenSelling; // Lot size and maximum number of lots for token being sold LotsInfo private _lotsInfo; // Payment tokens // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names address[] private _paymentTokens; // Payment token decimals // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names mapping(address => uint256) private _paymentDecimals; // Indicates whether ERC20 token is acceptable for payment mapping(address => bool) private _isPaymentTokens; // Address where funds are collected address private _wallet; // How many weis one token costs for each ERC20 payment token mapping(address => uint256) private _rates; // Amount of wei raised for each payment token mapping(address => uint256) private _weiRaised; /** * @dev Rates will denote how many weis one token costs for each ERC20 payment token. * For USDC or USDT payment token which has 6 decimals, minimum rate will * be 1000000000000 which will correspond to a price of USD0.000001 per token. * @param wallet_ Address where collected funds will be forwarded to * @param tokenSelling_ Address of the token being sold * @param lotsInfo Lot size and maximum number of lots for token being sold * @param paymentTokensInfo Addresses, decimals, rates and lot sizes of ERC20 tokens acceptable for payment */ constructor( address wallet_, address tokenSelling_, LotsInfo memory lotsInfo, PaymentTokenInfo[] memory paymentTokensInfo ) { require(wallet_ != address(0), "Crowdsale: zero wallet address"); require( tokenSelling_ != address(0), "Crowdsale: zero token selling address" ); require(lotsInfo.lotSize > 0, "Crowdsale: zero lot size"); require(lotsInfo.maxLots > 0, "Crowdsale: zero max lots"); require(paymentTokensInfo.length > 0, "Crowdsale: zero payment tokens"); require( paymentTokensInfo.length < MAX_NUM_PAYMENT_TOKENS, "Crowdsale: exceed max payment tokens" ); _wallet = wallet_; _tokenSelling = tokenSelling_; _lotsInfo = lotsInfo; for (uint256 i = 0; i < paymentTokensInfo.length; i++) { uint256 paymentDecimal = paymentTokensInfo[i].paymentDecimal; require( paymentDecimal <= TOKEN_MAX_DECIMALS, "Crowdsale: decimals exceed 18" ); address paymentToken = paymentTokensInfo[i].paymentToken; require( paymentToken != address(0), "Crowdsale: zero payment token address" ); uint256 rate_ = paymentTokensInfo[i].rate; require(rate_ > 0, "Crowdsale: zero rate"); _isPaymentTokens[paymentToken] = true; _paymentTokens.push(paymentToken); _paymentDecimals[paymentToken] = paymentDecimal; _rates[paymentToken] = rate_; } } /** * @return tokenSelling_ the token being sold */ function tokenSelling() external view override returns (address tokenSelling_) { tokenSelling_ = _tokenSelling; } /** * @return wallet_ the address where funds are collected */ function wallet() external view override returns (address wallet_) { wallet_ = _wallet; } /** * @return paymentTokens_ the payment tokens */ function paymentTokens() external view override returns (address[] memory paymentTokens_) { paymentTokens_ = _paymentTokens; } /** * @param paymentToken ERC20 payment token address * @return rate_ how many weis one token costs for specified ERC20 payment token */ function rate(address paymentToken) external view override returns (uint256 rate_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); rate_ = _rate(paymentToken); } /** * @return lotSize_ lot size of token being sold */ function lotSize() public view override returns (uint256 lotSize_) { lotSize_ = _lotsInfo.lotSize; } /** * @return maxLots_ maximum number of lots for token being sold */ function maxLots() external view override returns (uint256 maxLots_) { maxLots_ = _lotsInfo.maxLots; } /** * @param paymentToken ERC20 payment token address * @return weiRaised_ the amount of wei raised */ function weiRaisedFor(address paymentToken) external view override returns (uint256 weiRaised_) { weiRaised_ = _weiRaisedFor(paymentToken); } /** * @param paymentToken ERC20 payment token address * @return isPaymentToken_ whether token is accepted for payment */ function isPaymentToken(address paymentToken) public view override returns (bool isPaymentToken_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); isPaymentToken_ = _isPaymentTokens[paymentToken]; } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @return tokenAmount Number of tokens being sold that will be purchased */ function getTokenAmount(uint256 lots) external view override returns (uint256 tokenAmount) { require(lots > 0, "Crowdsale: zero lots"); tokenAmount = _getTokenAmount(lots); } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold * @return weiAmount Amount in wei of ERC20 payment token */ function getWeiAmount(address paymentToken, uint256 lots) external view override returns (uint256 weiAmount) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require(lots > 0, "Crowdsale: zero lots"); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); weiAmount = _getWeiAmount(paymentToken, lots); } /** * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function buyTokens(address paymentToken, uint256 lots) external override { _buyTokensFor(msg.sender, paymentToken, lots); } /** * @param beneficiary Recipient of the token purchase * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) external override { _buyTokensFor(beneficiary, paymentToken, lots); } /** * @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 * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function _buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) internal nonReentrant { require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require(lots > 0, "Crowdsale: zero lots"); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); // calculate token amount to be created uint256 tokenAmount = _getTokenAmount(lots); // calculate wei amount to transfer to wallet uint256 weiAmount = _getWeiAmount(paymentToken, lots); _preValidatePurchase(beneficiary, paymentToken, weiAmount, tokenAmount); // update state _weiRaised[paymentToken] = _weiRaised[paymentToken].add(weiAmount); tokensSold = tokensSold.add(tokenAmount); _updatePurchasingState( beneficiary, paymentToken, weiAmount, tokenAmount ); emit TokensPurchased( msg.sender, beneficiary, paymentToken, lots, weiAmount, tokenAmount ); _processPurchase(beneficiary, tokenAmount); _forwardFunds(paymentToken, weiAmount); _postValidatePurchase( beneficiary, paymentToken, weiAmount, tokenAmount ); } /** * @param paymentToken ERC20 payment token address * @return weiRaised_ the amount of wei raised */ function _weiRaisedFor(address paymentToken) internal view virtual returns (uint256 weiRaised_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); weiRaised_ = _weiRaised[paymentToken]; } /** * @param paymentToken ERC20 payment token address * @return rate_ how many weis one token costs for specified ERC20 payment token */ function _rate(address paymentToken) internal view virtual returns (uint256 rate_) { rate_ = _rates[paymentToken]; } /** * @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 paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _preValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view virtual { // solhint-disable-previous-line no-empty-blocks } /** * @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 paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _postValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view virtual { // 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 */ // https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code // slither-disable-next-line dead-code function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual { IERC20(_tokenSelling).safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _updatePurchasingState( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal virtual { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @return tokenAmount Number of tokens that will be purchased */ function _getTokenAmount(uint256 lots) internal view virtual returns (uint256 tokenAmount) { tokenAmount = lots.mul(_lotsInfo.lotSize).mul(TOKEN_SELLING_SCALE); } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold * @return weiAmount Amount in wei of ERC20 payment token */ function _getWeiAmount(address paymentToken, uint256 lots) internal view virtual returns (uint256 weiAmount) { uint256 rate_ = _rate(paymentToken); uint256 tokenAmount = _getTokenAmount(lots); weiAmount = tokenAmount.mul(rate_).div(TOKEN_SELLING_SCALE); } /** * @dev Determines how ERC20 payment token is stored/forwarded on purchases. */ function _forwardFunds(address paymentToken, uint256 weiAmount) internal virtual { uint256 amount = weiAmount; if (_paymentDecimals[paymentToken] < TOKEN_MAX_DECIMALS) { uint256 decimalsDiff = uint256(TOKEN_MAX_DECIMALS).sub( _paymentDecimals[paymentToken] ); amount = weiAmount.div(10**decimalsDiff); } IERC20(paymentToken).safeTransferFrom(msg.sender, _wallet, amount); } }
paymentToken ERC20 payment token address return weiRaised_ the amount of wei raised/
function weiRaisedFor(address paymentToken) external view override returns (uint256 weiRaised_) { weiRaised_ = _weiRaisedFor(paymentToken); }
6,367,991
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {StringsUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {IFlurryStakingRewards} from "../interfaces/IFlurryStakingRewards.sol"; import {BaseRewards} from "./BaseRewards.sol"; import {ILPStakingRewards} from "../interfaces/ILPStakingRewards.sol"; import {IRhoTokenRewards} from "../interfaces/IRhoTokenRewards.sol"; /** * @title Rewards for FLURRY Token Stakers * @notice This reward scheme enables users to stake (lock) FLURRY tokens to earn more FLURRY tokens * @notice FlurryToken is an ERC20 * BEP20 compliant token with 18 decimals. * @dev all FLURRY rewards in the flurry protocol are held by this contract * @dev This contract is also used by LPStakingRewards & RhoTokenRewards for claiming FLURRY */ contract FlurryStakingRewards is IFlurryStakingRewards, BaseRewards { using SafeERC20Upgradeable for IERC20Upgradeable; /// @dev events event FlurryRewardsRateChanged(uint256 blockNumber, uint256 rewardsRate); event RewardsEndUpdated(uint256 blockNumber, uint256 rewardsEndBlock); event Staked(address indexed user, uint256 blockNumber, uint256 amount); event Withdrawn(address indexed user, uint256 blockNumber, uint256 amount); event TotalStakesChanged(uint256 totalStakes); /// @dev roles of other rewards contracts bytes32 public constant LP_TOKEN_REWARDS_ROLE = keccak256("LP_TOKEN_REWARDS_ROLE"); bytes32 public constant RHO_TOKEN_REWARDS_ROLE = keccak256("RHO_TOKEN_REWARDS_ROLE"); /// @dev no. of FLURRY reward per block uint256 public override rewardsRate; /// @dev last block of time lock uint256 public lockEndBlock; /// @dev block number that staking reward was last accrued at uint256 public lastUpdateBlock; /// @dev staking reward entitlement per FLURRY staked uint256 public rewardsPerTokenStored; /// @dev last block when rewards distubution end uint256 public rewardsEndBlock; IERC20Upgradeable public flurryToken; uint256 public override totalStakes; uint256 public flurryTokenOne; /** * @notice UserInfo * @param stake FLURRY stakes for each staker * @param rewardPerTokenPaid amount of reward already paid to staker per token * @param reward accumulated FLURRY reward */ struct UserInfo { uint256 stake; uint256 rewardPerTokenPaid; uint256 reward; } mapping(address => UserInfo) public userInfo; ILPStakingRewards public override lpStakingRewards; IRhoTokenRewards public override rhoTokenRewards; /** * @notice initialize function is used in place of constructor for upgradeability * @dev Have to call initializers in the parent classes to proper initialize */ function initialize(address flurryTokenAddr) external initializer notZeroAddr(flurryTokenAddr) { BaseRewards.__initialize(); flurryToken = IERC20Upgradeable(flurryTokenAddr); flurryTokenOne = getTokenOne(flurryTokenAddr); } function totalRewardsPool() external view override returns (uint256) { return _totalRewardsPool(); } function _totalRewardsPool() internal view returns (uint256) { return flurryToken.balanceOf(address(this)) - totalStakes; } function stakeOf(address user) external view override notZeroAddr(user) returns (uint256) { return userInfo[user].stake; } function rewardOf(address user) external view override notZeroAddr(user) returns (uint256) { return _earned(user); } function claimableRewardOf(address user) external view override notZeroAddr(user) returns (uint256) { return block.number >= lockEndBlock ? _earned(user) : 0; } function lastBlockApplicable() internal view returns (uint256) { return _lastBlockApplicable(rewardsEndBlock); } function rewardsPerToken() public view override returns (uint256) { if (totalStakes == 0) return rewardsPerTokenStored; return rewardPerTokenInternal( rewardsPerTokenStored, lastBlockApplicable() - lastUpdateBlock, rewardRatePerTokenInternal(rewardsRate, flurryTokenOne, 1, totalStakes, 1) ); } function rewardRatePerTokenStaked() external view override returns (uint256) { if (totalStakes == 0) return type(uint256).max; return rewardRatePerTokenInternal(rewardsRate, flurryTokenOne, 1, totalStakes, 1); } function updateRewardInternal() internal { rewardsPerTokenStored = rewardsPerToken(); lastUpdateBlock = lastBlockApplicable(); } function updateReward(address addr) internal { updateRewardInternal(); if (addr != address(0)) { userInfo[addr].reward = _earned(addr); userInfo[addr].rewardPerTokenPaid = rewardsPerTokenStored; } } function _earned(address addr) internal view returns (uint256) { return super._earned( userInfo[addr].stake, rewardsPerToken() - userInfo[addr].rewardPerTokenPaid, flurryTokenOne, userInfo[addr].reward ); } function setRewardsRate(uint256 newRewardsRate) external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused { updateRewardInternal(); rewardsRate = newRewardsRate; emit FlurryRewardsRateChanged(block.number, rewardsRate); } function startRewards(uint256 rewardsDuration) external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused isValidDuration(rewardsDuration) { require(block.number > rewardsEndBlock, "Previous rewards period must complete before starting a new one"); updateRewardInternal(); lastUpdateBlock = block.number; rewardsEndBlock = block.number + rewardsDuration; emit RewardsEndUpdated(block.number, rewardsEndBlock); } function endRewards() external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused { if (rewardsEndBlock > block.number) { rewardsEndBlock = block.number; emit RewardsEndUpdated(block.number, rewardsEndBlock); } } function isLocked() external view override returns (bool) { return block.number <= lockEndBlock; } function setTimeLock(uint256 lockDuration) external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused { lockEndBlock = block.number + lockDuration; } function earlyUnlock() external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused { lockEndBlock = block.number; } function setTimeLockEndBlock(uint256 _lockEndBlock) external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused { lockEndBlock = _lockEndBlock; } function stake(uint256 amount) external override whenNotPaused nonReentrant { address user = _msgSender(); // check and update require(amount > 0, "Cannot stake 0 tokens"); require(flurryToken.balanceOf(user) >= amount, "Not Enough balance to stake"); updateReward(user); // state change userInfo[user].stake += amount; totalStakes += amount; // interaction flurryToken.safeTransferFrom(user, address(this), amount); emit Staked(user, block.number, amount); emit TotalStakesChanged(totalStakes); } function withdraw(uint256 amount) external override whenNotPaused nonReentrant { _withdrawUser(_msgSender(), amount); } function _withdrawUser(address user, uint256 amount) internal { // check and update require(amount > 0, "Cannot withdraw 0 amount"); require(userInfo[user].stake >= amount, "Exceeds staked amount"); updateReward(user); // state change userInfo[user].stake -= amount; totalStakes -= amount; // interaction flurryToken.safeTransfer(user, amount); emit Withdrawn(user, block.number, amount); emit TotalStakesChanged(totalStakes); } function exit() external override whenNotPaused nonReentrant { _withdrawUser(_msgSender(), userInfo[_msgSender()].stake); } function claimRewardInternal(address user) internal { if (block.number > lockEndBlock) { updateReward(user); if (userInfo[user].reward > 0) { userInfo[user].reward = grantFlurryInternal(user, userInfo[user].reward); } } } function claimReward() external override whenNotPaused nonReentrant { require(this.claimableRewardOf(_msgSender()) > 0, "nothing to claim"); claimRewardInternal(_msgSender()); } function claimAllRewards() external override whenNotPaused nonReentrant { require(this.totalClaimableRewardOf(_msgSender()) > 0, "nothing to claim"); if (address(lpStakingRewards) != address(0)) lpStakingRewards.claimAllReward(_msgSender()); if (address(rhoTokenRewards) != address(0)) rhoTokenRewards.claimAllReward(_msgSender()); claimRewardInternal(_msgSender()); } function grantFlurry(address addr, uint256 amount) external override onlyLPOrRhoTokenRewards returns (uint256) { return grantFlurryInternal(addr, amount); } function grantFlurryInternal(address addr, uint256 amount) internal notZeroAddr(addr) returns (uint256) { if (amount <= _totalRewardsPool()) { flurryToken.safeTransfer(addr, amount); emit RewardPaid(addr, amount); return 0; } emit NotEnoughBalance(addr, amount); return amount; } function isStakeholder(address addr) external view notZeroAddr(addr) returns (bool) { return userInfo[addr].stake > 0; } function sweepERC20Token(address token, address to) external override onlyRole(SWEEPER_ROLE) { require(token != address(flurryToken), "!safe"); _sweepERC20Token(token, to); } function totalRewardOf(address user) external view override notZeroAddr(user) returns (uint256) { uint256 otherRewards; if (address(lpStakingRewards) != address(0)) otherRewards += lpStakingRewards.totalRewardOf(user); if (address(rhoTokenRewards) != address(0)) otherRewards += rhoTokenRewards.totalRewardOf(user); return otherRewards + this.rewardOf(user); } function totalClaimableRewardOf(address user) external view override notZeroAddr(user) returns (uint256) { uint256 otherRewards; if (address(lpStakingRewards) != address(0)) otherRewards += lpStakingRewards.totalClaimableRewardOf(user); if (address(rhoTokenRewards) != address(0)) otherRewards += rhoTokenRewards.totalClaimableRewardOf(user); return otherRewards + this.claimableRewardOf(user); } function setRhoTokenRewardContract(address _rhoTokenRewardAddr) external override onlyRole(DEFAULT_ADMIN_ROLE) notZeroAddr(_rhoTokenRewardAddr) whenNotPaused { rhoTokenRewards = IRhoTokenRewards(_rhoTokenRewardAddr); } function setLPRewardsContract(address lpRewardsAddr) external override onlyRole(DEFAULT_ADMIN_ROLE) notZeroAddr(lpRewardsAddr) whenNotPaused { lpStakingRewards = ILPStakingRewards(lpRewardsAddr); } // modified from OZ onlyRole(), allowing the checking of multiple roles modifier onlyLPOrRhoTokenRewards() { require( hasRole(LP_TOKEN_REWARDS_ROLE, _msgSender()) || hasRole(RHO_TOKEN_REWARDS_ROLE, _msgSender()), string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(_msgSender()), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(LP_TOKEN_REWARDS_ROLE), 32), " or role ", StringsUpgradeable.toHexString(uint256(RHO_TOKEN_REWARDS_ROLE), 32) ) ) ); _; } } // 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; import "../IERC20Upgradeable.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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable 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(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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 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: MIT pragma solidity 0.8.4; import {ILPStakingRewards} from "../interfaces/ILPStakingRewards.sol"; import {IRhoTokenRewards} from "../interfaces/IRhoTokenRewards.sol"; /** * @title Flurry Staking Rewards Interface * @notice Interface for Flurry token staking functions * */ interface IFlurryStakingRewards { /** * @dev equals to balance of FLURRY minus total stakes * @return amount of FLURRY rewards available for the three reward schemes * (Flurry Staking, LP Token Staking and rhoToken Holding) */ function totalRewardsPool() external view returns (uint256); /** * @return aggregated FLURRY stakes from all stakers (in wei) */ function totalStakes() external view returns (uint256); /** * @notice Retrieve the stake balance for a stakeholder. * @param user Stakeholder address * @return user staked amount (in wei) */ function stakeOf(address user) external view returns (uint256); /** * @notice A method to allow a stakeholder to check his rewards. * @param user The stakeholder to check rewards for. * @return Accumulated rewards of addr holder (in wei) */ function rewardOf(address user) external view returns (uint256); /** * @notice A method to allow a stakeholder to check his claimable rewards. * @param user The stakeholder to check rewards for. * @return Accumulated rewards of addr holder (in wei) */ function claimableRewardOf(address user) external view returns (uint256); /** * @notice A method to allow a stakeholder to check all his rewards. * Includes Staking Rewards + RhoToken Rewards + LP Token Rewards * @param user The stakeholder to check rewards for. * @return Accumulated rewards of addr holder (in wei) */ function totalRewardOf(address user) external view returns (uint256); /** * @notice A method to allow a stakeholderto check his claimable rewards. * Includes Staking Rewards + RhoToken Rewards + LP Token Rewards * @param user The stakeholder to check rewards for * @return Accumulated rewards of addr holder (in wei) */ function totalClaimableRewardOf(address user) external view returns (uint256); /** * @return amount of FLURRY distrubuted to all FLURRY stakers per block */ function rewardsRate() external view returns (uint256); /** * @notice Total accumulated reward per token * @return Reward entitlement per FLURRY token staked (in wei) */ function rewardsPerToken() external view returns (uint256); /** * @notice current reward rate per FLURRY token staked * @return rewards rate in FLURRY per block per FLURRY staked scaled by 18 decimals */ function rewardRatePerTokenStaked() external view returns (uint256); /** * @notice A method to add a stake. * @param amount amount of flurry tokens to be staked (in wei) */ function stake(uint256 amount) external; /** * @notice A method to unstake. * @param amount amount to unstake (in wei) */ function withdraw(uint256 amount) external; /** * @notice A method to allow a stakeholder to withdraw his FLURRY staking rewards. */ function claimReward() external; /** * @notice A method to allow a stakeholder to claim all his rewards. */ function claimAllRewards() external; /** * @notice NOT for external use * @dev only callable by LPStakingRewards or RhoTokenRewards for FLURRY distribution * @param addr address of LP Token staker / rhoToken holder * @param amount amount of FLURRY token rewards to grant (in wei) * @return outstanding amount if claim is not successful, 0 if successful */ function grantFlurry(address addr, uint256 amount) external returns (uint256); /** * @notice A method to allow a stakeholder to withdraw full stake. * Rewards are not automatically claimed. Use claimReward() */ function exit() external; /** * @notice Admin function - set rewards rate earned for FLURRY staking per block * @param newRewardsRate amount of FLURRY (in wei) per block */ function setRewardsRate(uint256 newRewardsRate) external; /** * @notice Admin function - A method to start rewards distribution * @param rewardsDuration rewards duration in number of blocks */ function startRewards(uint256 rewardsDuration) external; /** * @notice Admin function - End Rewards distribution earlier, if there is one running */ function endRewards() external; /** * @return true if reward is locked, false otherwise */ function isLocked() external view returns (bool); /** * @notice Admin function - lock all rewards for all users for a given duration * This function should be called BEFORE startRewards() * @param lockDuration lock duration in number of blocks */ function setTimeLock(uint256 lockDuration) external; /** * @notice Admin function - unlock all rewards immediately, if there is a time lock */ function earlyUnlock() external; /** * @notice Admin function - lock FLURRY staking rewards until a specific block * @param _lockEndBlock lock rewards until specific block no. */ function setTimeLockEndBlock(uint256 _lockEndBlock) external; /** * @notice Admin function - withdraw other ERC20 tokens sent to this contract * @param token ERC20 token address to be sweeped * @param to address for sending sweeped tokens to */ function sweepERC20Token(address token, address to) external; /** * @notice Admin function - set RhoTokenReward contract reference */ function setRhoTokenRewardContract(address rhoTokenRewardAddr) external; /** * @notice Admin function - set LP Rewards contract reference */ function setLPRewardsContract(address lpRewardsAddr) external; /** * @return reference to LP Staking Rewards contract */ function lpStakingRewards() external returns (ILPStakingRewards); /** * @return reference to RhoToken Rewards contract */ function rhoTokenRewards() external returns (IRhoTokenRewards); } //SPDX-License-Identifier: MIT pragma solidity 0.8.4; /** * @title BaseRewards Abstract Contract * @notice Abstract Contract to be inherited by LPStakingReward, StakingReward and RhoTokenReward. * Implements the core logic as internal functions. * *** Note: avoid using `super` keyword to avoid confusion because the derived contracts use multiple inheritance *** */ import {MathUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import { IERC20MetadataUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; abstract contract BaseRewards is AccessControlEnumerableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; // events event RewardPaid(address indexed user, uint256 reward); event NotEnoughBalance(address indexed user, uint256 withdrawalAmount); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant SWEEPER_ROLE = keccak256("SWEEPER_ROLE"); function __initialize() internal { AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init(); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function getTokenOne(address token) internal view returns (uint256) { return 10**IERC20MetadataUpgradeable(token).decimals(); } /** * @notice Calculate accrued but unclaimed reward for a user * @param _tokenBalance balance of the rhoToken, OR staking ammount of LP/FLURRY * @param _netRewardPerToken accumulated reward minus the reward already paid to user, on a per token basis * @param _tokenOne decimal of the token * @param accumulatedReward accumulated reward of the user * @return claimable reward of the user */ function _earned( uint256 _tokenBalance, uint256 _netRewardPerToken, uint256 _tokenOne, uint256 accumulatedReward ) internal pure returns (uint256) { return ((_tokenBalance * _netRewardPerToken) / _tokenOne) + accumulatedReward; } /** * @notice Rewards are accrued up to this block (put aside in rewardsPerTokenPaid) * @return min(The current block # or last rewards accrual block #) */ function _lastBlockApplicable(uint256 _rewardsEndBlock) internal view returns (uint256) { return MathUpgradeable.min(block.number, _rewardsEndBlock); } function rewardRatePerTokenInternal( uint256 rewardRate, uint256 tokenOne, uint256 allocPoint, uint256 totalToken, uint256 totalAllocPoint ) internal pure returns (uint256) { return (rewardRate * tokenOne * allocPoint) / (totalToken * totalAllocPoint); } function rewardPerTokenInternal( uint256 accruedRewardsPerToken, uint256 blockDelta, uint256 rewardRatePerToken ) internal pure returns (uint256) { return accruedRewardsPerToken + blockDelta * rewardRatePerToken; } /** * admin functions to withdraw random token transfer to this contract */ function _sweepERC20Token(address token, address to) internal notZeroTokenAddr(token) { IERC20Upgradeable tokenToSweep = IERC20Upgradeable(token); tokenToSweep.safeTransfer(to, tokenToSweep.balanceOf(address(this))); } /** Pausable */ function pause() external onlyRole(PAUSER_ROLE) { _pause(); } function unpause() external onlyRole(PAUSER_ROLE) { _unpause(); } modifier notZeroAddr(address addr) { require(addr != address(0), "address is zero"); _; } modifier notZeroTokenAddr(address addr) { require(addr != address(0), "token address is zero"); _; } modifier isValidDuration(uint256 rewardDuration) { require(rewardDuration > 0, "Reward duration cannot be zero"); _; } } //SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {IFlurryStakingRewards} from "../interfaces/IFlurryStakingRewards.sol"; /** * @title LP Staking Rewards Interface * @notice Interface for FLURRY token rewards when staking LP tokens */ interface ILPStakingRewards { /** * @notice checks whether the staking of a LP token is supported by the reward scheme * @param lpToken address of LP Token contract * @return true if the reward scheme supports `lpToken`, false otherwise */ function isSupported(address lpToken) external returns (bool); /** * @param user user address * @return list of addresses of LP user has engaged in */ function getUserEngagedPool(address user) external view returns (address[] memory); /** * @return list of addresses of LP registered in this contract */ function getPoolList() external view returns (address[] memory); /** * @return amount of FLURRY distrubuted for all LP per block, * to be shared by the staking pools according to allocation points */ function rewardsRate() external view returns (uint256); /** * @notice Admin function - set rewards rate earned for all LP per block * @param newRewardsRate amount of FLURRY (in wei) per block */ function setRewardsRate(uint256 newRewardsRate) external; /** * @notice Retrieve the stake balance for a stakeholder. * @param addr Stakeholder address * @param lpToken Address of LP Token contract * @return user staked amount (in wei) */ function stakeOf(address addr, address lpToken) external view returns (uint256); /** * @notice A method to allow a stakeholder to check his rewards for one LP token * @param user The stakeholder to check rewards for * @param lpToken Address of LP Token contract * @return Accumulated rewards of addr holder (in wei) */ function rewardOf(address user, address lpToken) external view returns (uint256); /** * @notice A method to allow a stakeholder to check his rewards earned for all LP token * @param user The stakeholder to check rewards for * @return Accumulated rewards of addr holder (in wei) */ function totalRewardOf(address user) external view returns (uint256); /** * @notice A method to allow a stakeholder to check his claimble rewards for all LP token * @param user The stakeholder to check rewards for * @return Accumulated rewards of addr holder (in wei) */ function totalClaimableRewardOf(address user) external view returns (uint256); /** * @notice A method to add a stake. * @param lpToken Address of LP Token contract * @param amount amount of flurry tokens to be staked (in wei) */ function stake(address lpToken, uint256 amount) external; /** * @notice NOT for external use * @dev allows Flurry Staking Rewards contract to claim rewards for one LP on behalf of a user * @param onBehalfOf address of the user to claim rewards for * @param lpToken Address of LP Token contract */ function claimReward(address onBehalfOf, address lpToken) external; /** * @notice A method to allow a LP token holder to claim his rewards for one LP token * @param lpToken Address of LP Token contract * Note: If stakingRewards contract do not have enough tokens to pay, * this will fail silently and user rewards remains as a credit in this contract */ function claimReward(address lpToken) external; /** * @notice NOT for external use * @dev allows Flurry Staking Rewards contract to claim rewards for all LP on behalf of a user * @param onBehalfOf address of the user to claim rewards for */ function claimAllReward(address onBehalfOf) external; /** * @notice A method to allow a LP token holder to claim his rewards for all LP token * Note: If stakingRewards contract do not have enough tokens to pay, * this will fail silently and user rewards remains as a credit in this contract */ function claimAllReward() external; /** * @notice A method to unstake. * @param lpToken Address of LP Token contract * @param amount amount to unstake (in wei) */ function withdraw(address lpToken, uint256 amount) external; /** * @notice A method to allow a stakeholder to withdraw full stake. * @param lpToken Address of LP Token contract * Rewards are not automatically claimed. Use claimReward() */ function exit(address lpToken) external; /** * @notice Total accumulated reward per token * @param lpToken Address of LP Token contract * @return Reward entitlement per LP token staked (in wei) */ function rewardsPerToken(address lpToken) external view returns (uint256); /** * @notice current reward rate per LP token staked * @param lpToken Address of LP Token contract * @return rewards rate in FLURRY per block per LP staked scaled by 18 decimals */ function rewardRatePerTokenStaked(address lpToken) external view returns (uint256); /** * @notice Admin function - A method to set reward duration * @param lpToken Address of LP Token contract * @param rewardDuration Reward Duration in number of blocks */ function startRewards(address lpToken, uint256 rewardDuration) external; /** * @notice Admin function - End Rewards distribution earlier if there is one running * @param lpToken Address of LP Token contract */ function endRewards(address lpToken) external; /** * @return true if rewards are locked for given lpToken, false if rewards are unlocked or if lpTokenis not supported * @param lpToken address of LP Token contract */ function isLocked(address lpToken) external view returns (bool); /** * @notice Admin function - lock rewards for given lpToken * @param lpToken address of the lpToken contract * @param lockDuration lock duration in number of blocks */ function setTimeLock(address lpToken, uint256 lockDuration) external; /** * @notice Admin function - lock rewards for given lpToken until a specific block * @param lpToken address of the lpToken contract * @param lockEndBlock lock rewards until specific block no. */ function setTimeLockEndBlock(address lpToken, uint256 lockEndBlock) external; /** * @notice Admin function - lock all lpToken rewards * @param lockDuration lock duration in number of blocks */ function setTimeLockForAllLPTokens(uint256 lockDuration) external; /** * @notice Admin function - lock all lpToken rewards until a specific block * @param lockEndBlock lock rewards until specific block no. */ function setTimeLockEndBlockForAllLPTokens(uint256 lockEndBlock) external; /** * @notice Admin function - unlock rewards for given lpToken * @param lpToken address of the lpToken contract */ function earlyUnlock(address lpToken) external; /** * @param lpToken address of the lpToken contract * @return the current lock end block number */ function getLockEndBlock(address lpToken) external view returns (uint256); /** * @notice Admin function - register a LP to this contract * @param lpToken address of the LP to be registered * @param allocPoint allocation points (weight) assigned to the given LP */ function addLP(address lpToken, uint256 allocPoint) external; /** * @notice Admin function - change the allocation points of a LP registered in this contract * @param lpToken address of the LP subject to change * @param allocPoint allocation points (weight) assigned to the given LP */ function setLP(address lpToken, uint256 allocPoint) external; /** * @notice Admin function - withdraw random token transfer to this contract * @param token ERC20 token address to be sweeped * @param to address for sending sweeped tokens to */ function sweepERC20Token(address token, address to) external; /** * @return reference to RhoToken Rewards contract */ function flurryStakingRewards() external returns (IFlurryStakingRewards); } //SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {IFlurryStakingRewards} from "../interfaces/IFlurryStakingRewards.sol"; /** * @title RhoToken Rewards Interface * @notice Interface for bonus FLURRY token rewards contract for RhoToken holders */ interface IRhoTokenRewards { /** * @notice checks whether the rewards for a rhoToken is supported by the reward scheme * @param rhoToken address of rhoToken contract * @return true if the reward scheme supports `rhoToken`, false otherwise */ function isSupported(address rhoToken) external returns (bool); /** * @return list of addresses of rhoTokens registered in this contract */ function getRhoTokenList() external view returns (address[] memory); /** * @return amount of FLURRY distributed for all rhoTokens per block */ function rewardsRate() external view returns (uint256); /** * @notice Admin function - set reward rate earned for all rhoTokens per block * @param newRewardsRate amount of FLURRY (in wei) per block */ function setRewardsRate(uint256 newRewardsRate) external; /** * @notice A method to allow a stakeholder to check his rewards. * @param user The stakeholder to check rewards for. * @param rhoToken Address of rhoToken contract * @return Accumulated rewards of addr holder (in wei) */ function rewardOf(address user, address rhoToken) external view returns (uint256); /** * @notice A method to allow a stakeholder to check his rewards for all rhoToken * @param user The stakeholder to check rewards for * @return Accumulated rewards of addr holder (in wei) */ function totalRewardOf(address user) external view returns (uint256); /** * @notice A method to allow a stakeholder to check his rewards for all rhoToken * @param user The stakeholder to check rewards for * @return Accumulated rewards of addr holder (in wei) */ function totalClaimableRewardOf(address user) external view returns (uint256); /** * @notice Total accumulated reward per token * @param rhoToken Address of rhoToken contract * @return Reward entitlement for rho token */ function rewardsPerToken(address rhoToken) external view returns (uint256); /** * @notice current reward rate per token staked * @param rhoToken Address of rhoToken contract * @return reward rate denominated in FLURRY per block */ function rewardRatePerRhoToken(address rhoToken) external view returns (uint256); /** * @notice Admin function - A method to set reward duration * @param rhoToken Address of rhoToken contract * @param rewardDuration Reward duration in number of blocks */ function startRewards(address rhoToken, uint256 rewardDuration) external; /** * @notice Admin function - End Rewards distribution earlier, if there is one running * @param rhoToken Address of rhoToken contract */ function endRewards(address rhoToken) external; /** * @notice Calculate and allocate rewards token for address holder * Rewards should accrue from _lastUpdateBlock to lastBlockApplicable * rewardsPerToken is based on the total supply of the RhoToken, hence * this function needs to be called every time total supply changes * @dev intended to be called externally by RhoToken contract modifier, and internally * @param user the user to update reward for * @param rhoToken the rhoToken to update reward for */ function updateReward(address user, address rhoToken) external; /** * @notice NOT for external use * @dev allows Flurry Staking Rewards contract to claim rewards for one rhoToken on behalf of a user * @param onBehalfOf address of the user to claim rewards for * @param rhoToken Address of rhoToken contract */ function claimReward(address onBehalfOf, address rhoToken) external; /** * @notice A method to allow a rhoToken holder to claim his rewards for one rhoToken * @param rhoToken Address of rhoToken contract * Note: If stakingRewards contract do not have enough tokens to pay, * this will fail silently and user rewards remains as a credit in this contract */ function claimReward(address rhoToken) external; /** * @notice NOT for external use * @dev allows Flurry Staking Rewards contract to claim rewards for all rhoTokens on behalf of a user * @param onBehalfOf address of the user to claim rewards for */ function claimAllReward(address onBehalfOf) external; /** * @notice A method to allow a rhoToken holder to claim his rewards for all rhoTokens * Note: If stakingRewards contract do not have enough tokens to pay, * this will fail silently and user rewards remains as a credit in this contract */ function claimAllReward() external; /** * @return true if rewards are locked for given rhoToken, false if rewards are unlocked or if rhoToken is not supported * @param rhoToken address of rhoToken contract */ function isLocked(address rhoToken) external view returns (bool); /** * @notice Admin function - lock rewards for given rhoToken * @param rhoToken address of the rhoToken contract * @param lockDuration lock duration in number of blocks */ function setTimeLock(address rhoToken, uint256 lockDuration) external; /** * @notice Admin function - lock rewards for given rhoToken until a specific block * @param rhoToken address of the rhoToken contract * @param lockEndBlock lock rewards until specific block no. */ function setTimeLockEndBlock(address rhoToken, uint256 lockEndBlock) external; /** * @notice Admin function - lock all rho Staking rewards * @param lockDuration lock duration in number of blocks */ function setTimeLockForAllRho(uint256 lockDuration) external; /** * @notice Admin function - lock all rho Staking rewards until a specific block * @param lockEndBlock lock rewards until specific block no. */ function setTimeLockEndBlockForAllRho(uint256 lockEndBlock) external; /** * @notice Admin function - unlock rewards for given rhoToken * @param rhoToken address of the rhoToken contract */ function earlyUnlock(address rhoToken) external; /** * @param rhoToken address of the rhoToken contract * @return the current lock end block number */ function getLockEndBlock(address rhoToken) external view returns (uint256); /** * @notice Admin function - register a rhoToken to this contract * @param rhoToken address of the rhoToken to be registered * @param allocPoint allocation points (weight) assigned to the given rhoToken */ function addRhoToken(address rhoToken, uint256 allocPoint) external; /** * @notice Admin function - change the allocation points of a rhoToken registered in this contract * @param rhoToken address of the rhoToken subject to change * @param allocPoint allocation points (weight) assigned to the given rhoToken */ function setRhoToken(address rhoToken, uint256 allocPoint) external; /** * @notice Admin function - withdraw random token transfer to this contract * @param token ERC20 token address to be sweeped * @param to address for sending sweeped tokens to */ function sweepERC20Token(address token, address to) external; /** * @return reference to RhoToken Rewards contract */ function flurryStakingRewards() external returns (IFlurryStakingRewards); } // 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; /** * @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; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } 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) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } 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; 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 "./IAccessControlUpgradeable.sol"; /** * @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); } // 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; /** * @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; /** * @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; /** * @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; 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); }
check and update state change interaction
function _withdrawUser(address user, uint256 amount) internal { require(amount > 0, "Cannot withdraw 0 amount"); require(userInfo[user].stake >= amount, "Exceeds staked amount"); updateReward(user); userInfo[user].stake -= amount; totalStakes -= amount; flurryToken.safeTransfer(user, amount); emit Withdrawn(user, block.number, amount); emit TotalStakesChanged(totalStakes); }
6,305,798
//Address: 0x08cdcf9ba0a4b5667f5a59b78b60fbefb145e64c //Contract name: WorldCupToken //Balance: 0.035250000000000002 Ether //Verification Date: 3/24/2018 //Transacion Count: 7 // CODE STARTS HERE pragma solidity ^0.4.18; 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; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); } contract WorldCupToken is ERC721 { /*****------ EVENTS -----*****/ // @dev whenever a token is sold. event WorldCupTokenWereSold(address indexed curOwner, uint256 indexed tokenId, uint256 oldPrice, uint256 newPrice, address indexed prevOwner, uint256 traddingTime);//indexed // @dev whenever Share Bonus. event ShareBonus(address indexed toOwner, uint256 indexed tokenId, uint256 indexed traddingTime, uint256 remainingAmount); // @dev Present. event Present(address indexed fromAddress, address indexed toAddress, uint256 amount, uint256 presentTime); // @dev Transfer event as defined in ERC721. event Transfer(address from, address to, uint256 tokenId); /*****------- CONSTANTS -------******/ mapping (uint256 => address) public worldCupIdToOwnerAddress; //@dev A mapping from world cup team id to the address that owns them. mapping (address => uint256) private ownerAddressToTokenCount; //@dev A mapping from owner address to count of tokens that address owns. mapping (uint256 => address) public worldCupIdToAddressForApproved; // @dev A mapping from token id to an address that has been approved to call. mapping (uint256 => uint256) private worldCupIdToPrice; // @dev A mapping from token id to the price of the token. //mapping (uint256 => uint256) private worldCupIdToOldPrice; // @dev A mapping from token id to the old price of the token. string[] private worldCupTeamDescribe; uint256 private SHARE_BONUS_TIME = uint256(now); address public ceoAddress; address public cooAddress; /*****------- MODIFIERS -------******/ modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } function destroy() public onlyCEO { selfdestruct(ceoAddress); } function payAllOut() public onlyCLevel { ceoAddress.transfer(this.balance); } /*****------- CONSTRUCTOR -------******/ function WorldCupToken() public { ceoAddress = msg.sender; cooAddress = msg.sender; for (uint256 i = 0; i < 32; i++) { uint256 newWorldCupTeamId = worldCupTeamDescribe.push("I love world cup!") - 1; worldCupIdToPrice[newWorldCupTeamId] = 0 ether;//SafeMath.sub(uint256(3.2 ether), SafeMath.mul(uint256(0.1 ether), i)); //worldCupIdToOldPrice[newWorldCupTeamId] = 0 ether; _transfer(address(0), msg.sender, newWorldCupTeamId); } } /*****------- PUBLIC FUNCTIONS -------******/ function approve(address _to, uint256 _tokenId) public { require(_isOwner(msg.sender, _tokenId)); worldCupIdToAddressForApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account function balanceOf(address _owner) public view returns (uint256 balance) { return ownerAddressToTokenCount[_owner]; } /// @notice Returns all the world cup team information by token id. function getWorlCupByID(uint256 _tokenId) public view returns (string wctDesc, uint256 sellingPrice, address owner) { wctDesc = worldCupTeamDescribe[_tokenId]; sellingPrice = worldCupIdToPrice[_tokenId]; owner = worldCupIdToOwnerAddress[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return "WorldCupToken"; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return "WCT"; } // @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = worldCupIdToOwnerAddress[_tokenId]; require(owner != address(0)); return owner; } function setWorldCupTeamDesc(uint256 _tokenId, string descOfOwner) public { if(ownerOf(_tokenId) == msg.sender){ worldCupTeamDescribe[_tokenId] = descOfOwner; } } /// Allows someone to send ether and obtain the token ///function PresentToCEO() public payable { /// ceoAddress.transfer(msg.value); /// Present(msg.sender, ceoAddress, msg.value, uint256(now)); ///} // Allows someone to send ether and obtain the token function buyWorldCupTeamToken(uint256 _tokenId) public payable { address oldOwner = worldCupIdToOwnerAddress[_tokenId]; address newOwner = msg.sender; require(oldOwner != newOwner); // Make sure token owner is not sending to self require(_addressNotNull(newOwner)); //Safety check to prevent against an unexpected 0x0 default. uint256 oldSoldPrice = worldCupIdToPrice[_tokenId];//worldCupIdToOldPrice[_tokenId]; uint256 diffPrice = SafeMath.sub(msg.value, oldSoldPrice); uint256 priceOfOldOwner = SafeMath.add(oldSoldPrice, SafeMath.div(diffPrice, 2)); uint256 priceOfDevelop = SafeMath.div(diffPrice, 4); worldCupIdToPrice[_tokenId] = msg.value;//SafeMath.add(msg.value, SafeMath.div(msg.value, 10)); //worldCupIdToOldPrice[_tokenId] = msg.value; _transfer(oldOwner, newOwner, _tokenId); if (oldOwner != address(this)) { oldOwner.transfer(priceOfOldOwner); } ceoAddress.transfer(priceOfDevelop); if(this.balance >= uint256(3.2 ether)){ if((uint256(now) - SHARE_BONUS_TIME) >= 86400){ for(uint256 i=0; i<32; i++){ worldCupIdToOwnerAddress[i].transfer(0.1 ether); ShareBonus(worldCupIdToOwnerAddress[i], i, uint256(now), this.balance); } SHARE_BONUS_TIME = uint256(now); //ShareBonus(SHARE_BONUS_TIME, this.balance); } } WorldCupTokenWereSold(newOwner, _tokenId, oldSoldPrice, msg.value, oldOwner, uint256(now)); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return worldCupIdToPrice[_tokenId]; } /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = worldCupIdToOwnerAddress[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCars = totalSupply(); uint256 resultIndex = 0; uint256 carId; for (carId = 0; carId <= totalCars; carId++) { if (worldCupIdToOwnerAddress[carId] == _owner) { result[resultIndex] = carId; resultIndex++; } } return result; } } function getCEO() public view returns (address ceoAddr) { return ceoAddress; } //Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return worldCupTeamDescribe.length; } //return BonusPool $ function getBonusPool() public view returns (uint256) { return this.balance; } function getTimeFromPrize() public view returns (uint256) { return uint256(now) - SHARE_BONUS_TIME; } /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _tokenId) public { require(_isOwner(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) public { require(_isOwner(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /********----------- PRIVATE FUNCTIONS ------------********/ function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } function _approved(address _to, uint256 _tokenId) private view returns (bool) { return worldCupIdToAddressForApproved[_tokenId] == _to; } function _isOwner(address checkAddress, uint256 _tokenId) private view returns (bool) { return checkAddress == worldCupIdToOwnerAddress[_tokenId]; } function _transfer(address _from, address _to, uint256 _tokenId) private { ownerAddressToTokenCount[_to]++; worldCupIdToOwnerAddress[_tokenId] = _to; //transfer ownership if (_from != address(0)) { ownerAddressToTokenCount[_from]--; delete worldCupIdToAddressForApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } }
Returns all the world cup team information by token id.
function getWorlCupByID(uint256 _tokenId) public view returns (string wctDesc, uint256 sellingPrice, address owner) { wctDesc = worldCupTeamDescribe[_tokenId]; sellingPrice = worldCupIdToPrice[_tokenId]; owner = worldCupIdToOwnerAddress[_tokenId]; }
6,428,867
./full_match/11155111/0xA91CF95Af2C57aA1D5F4461a5Aa6cb2e027e42d8/sources/contracts/collections/ERC721A/presets/ERC721AOneOfOneCollection.sol
Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings./
function isApprovedForAll(address owner, address operator) public view override(ERC721A, ERC721AOpenSeaNoGasExtension) returns (bool) { return super.isApprovedForAll(owner, operator); }
3,824,244
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Corebank { // dictionary that map address to balances mapping(address => uint256) public balances; // Users to system address[] public accounts; // Interest rate uint256 rate = 3; address public owner; modifier onlyOwner() { require(owner == msg.sender, "you're not authorize to perform this function"); _; } constructor() public { owner = msg.sender; } function deposit() public payable returns (uint256) { if (0 == balances[msg.sender]) { accounts.push(msg.sender); } balances[msg.sender] += msg.value; return balances[msg.sender]; } function withdraw(uint256 withdrawAmount) public onlyOwner returns (uint256 remainingBalance) { require(balances[msg.sender] >= withdrawAmount, " Your remaining is not enough to withdraw..! "); balances[msg.sender] -= withdrawAmount; // Transfer ether back to user, revert on failed payable(msg.sender).transfer(withdrawAmount); // Return balances[msg.sender] remainingBalance = balances[msg.sender]; } function systemBalance() public view returns (uint256) { return address(this).balance; } function systemWithdraw(uint256 withdrawAmount) public onlyOwner returns (uint256) { require(withdrawAmount <= systemBalance(), "amount to withdraw is not enough!"); // Transfer ether back to user on failed payable(msg.sender).transfer(withdrawAmount); return systemBalance(); } function systemDeposit() public payable onlyOwner returns (uint256) { return systemBalance(); } function payDividentPerYear() public payable onlyOwner { uint256 totalInterest = 0; for (uint256 i = 0; i < accounts.length; i++) { address account = accounts[i]; //uint256 interest = calculateInterest(account, rate); //balances[account] += interest; //totalInterest += interest; } require(msg.value == totalInterest, "Not enough interest to pay"); } }
uint256 interest = calculateInterest(account, rate);balances[account] += interest;totalInterest += interest;
function payDividentPerYear() public payable onlyOwner { uint256 totalInterest = 0; for (uint256 i = 0; i < accounts.length; i++) { address account = accounts[i]; } require(msg.value == totalInterest, "Not enough interest to pay"); }
12,604,835
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "./erc721.sol"; import "./utils.sol"; import "./utf8.sol"; import "./IEns.sol"; contract Xtitle is ERC721Enumerable, ReentrancyGuard, Ownable, EnsOwnable { uint256 constant _maxTitlePerAddr = 3; uint256 _minTitleLen = 9; uint256 _maxTitleLen = 32; event TitleMint ( address owner, string title, uint tokenId ); struct TitleInfo { string title; uint256 tokenId; } uint256[] _priceTable = [0, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21]; //ens contract address, same for Mainnet, Testnet address private _ensRegistry = address(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); //admin, who receive ETH from users who add title address payable private _contractAdmin = payable(0x1F79544C06bd94c044Bd388ffeE03FeE72025052); mapping(uint256 => string) _titles; mapping(bytes32 => bool) _titlesHash; uint256 _lastTokenId; function updateSettings(uint256 minTitleLen, uint256 maxTitleLen) public { require(msg.sender == _contractAdmin, "admin only"); _minTitleLen = minTitleLen; _maxTitleLen = maxTitleLen; } function queryTitles(address user) public view returns (TitleInfo[] memory) { uint256 tokenCount = balanceOf(user); TitleInfo[] memory titleInfos = new TitleInfo[](tokenCount); for(uint i=0; i<tokenCount; i++) { uint256 tokenId = tokenOfOwnerByIndex(user, i); TitleInfo memory info = TitleInfo(_titles[tokenId], tokenId); titleInfos[i] = info; } return titleInfos; } function disableEnsCheck() public onlyOwner() { requireENS = false; } function mint(string memory inputTitle) public nonReentrant payable onlyEnsOwner { uint ensTitleCount = balanceOf(msg.sender); require(ensTitleCount < _maxTitlePerAddr, "number of titles exceeded"); uint256 priceNeed = _priceTable[ensTitleCount]; require(msg.value >= priceNeed, "paid not enough"); string memory titleWords = Utils.trim(inputTitle); require(bytes(titleWords).length >= _minTitleLen, "title too short"); require(bytes(titleWords).length <= _maxTitleLen, "title too long"); //check duplication (bytes32 thash, bool titleUsed) = checkTitleUsed(titleWords); require(!titleUsed, "title already occupied"); //save data uint256 tokenId = _lastTokenId + 1; _titlesHash[thash] = true; _titles[tokenId] = titleWords; _safeMint(msg.sender, tokenId); //transfer money _contractAdmin.transfer(msg.value); //increase tokenId _lastTokenId = tokenId; emit TitleMint(msg.sender, _titles[tokenId], tokenId); } function checkTitleChars(string memory str) internal pure returns (bool) { //now, only allow ascii or emoji //emoji unicode: https://www.w3schools.com/charsets/ref_emoji.asp (int ret, uint32[] memory unicodes) = UTF8.decode(str); if (ret < 0) { return false; } for (uint i=0; i<unicodes.length; i++) { uint32 u = unicodes[i]; if (u < 128) { continue; } else if (u==8986 || u==8987) { continue; } else if (u>=9193 && u <= 12953) { continue; } else if (u>=126980 && u <= 129510) { continue; } else { return false; } } return true; } function genTitleHash(string memory titleWords) internal pure returns (bytes32) { require(checkTitleChars(titleWords), "only ascii characters or emoji are allowed"); string memory lowerCaseTitle = Utils.lowercase(titleWords); bytes32 thash = keccak256(abi.encodePacked(lowerCaseTitle)); return thash; } //check if title already used function checkTitleUsed(string memory titleWords) public view returns (bytes32, bool) { bytes32 thash = genTitleHash(titleWords); return (thash, _titlesHash[thash]); } constructor () ERC721("XTitle", "XT") Ownable() {} function tokenURI(uint256 tokenId) override public view returns (string memory) { require(tokenId <= _lastTokenId, "not minted"); require(tokenId > 0, "invalid tokenid"); string[7] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white'; parts[1] = '; font-family: serif; font-size: 25px; } </style>'; parts[2] = '<rect width="100%" height="100%" fill="balck" /><text x="10" y="40" class="base">'; parts[3] = _titles[tokenId]; parts[4] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4])); string memory json = Utils.b64encode(bytes(string(abi.encodePacked('{"name": "XTitle #', Utils.uint2str(tokenId), '", "description": "XTitle is title for ENS.", "image": "data:image/svg+xml;base64,', Utils.b64encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; /** * @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; } /** * @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 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 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); } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 {} } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // Reference: https://www.cl.cam.ac.uk/~mgk25/ucs/utf-8-history.txt // Rewrite by sjy.eth in Solidity pragma solidity >=0.4.22 <0.9.0; library UTF8 { struct Tab { uint32 cmask; uint32 cval; uint32 shift; uint64 lmask; uint64 lval; } function tabForUTF8() internal pure returns (Tab[] memory) { Tab[] memory tab = new Tab[](6); //statck memory, less gas used tab[0] = Tab(0x80, 0x00, 0*6, 0x7F,0); tab[1] = Tab(0xE0, 0xC0, 1*6, 0x7FF, 0x80); tab[2] = Tab(0xF0, 0xE0, 2*6, 0xFFFF, 0x800); tab[3] = Tab(0xF8, 0xF0, 3*6, 0x1FFFFF, 0x10000); tab[4] = Tab(0xFC, 0xF8, 4*6, 0x3FFFFFF, 0x200000); tab[5] = Tab(0xFE, 0xFC, 5*6, 0x7FFFFFFF, 0x4000000); return tab; } //reference: https://www.cl.cam.ac.uk/~mgk25/ucs/utf-8-history.txt function decode(string memory s) external pure returns (int retCode, uint32[] memory) { Tab[] memory tab = tabForUTF8(); uint64 l; uint32 c0; uint32 c; uint32 nc; uint si; uint ui; bool matched; bytes memory ss = bytes(s); uint32[] memory unicodes = new uint32[](ss.length); //at most if(ss.length == 0) return (0, new uint32[](0)); while(si < ss.length) { nc = 0; c0 = uint8(ss[si]) & 0xff; l = c0; matched = false; for(uint i=0; i<tab.length; i++) { Tab memory t = tab[i]; nc++; if((c0 & t.cmask) == t.cval) { l &= t.lmask; if(l < t.lval) return (-1, unicodes); unicodes[ui] = uint32(l); ui++; matched = true; si++; break; } if (ss.length <= nc) return (-2, unicodes); si++; c = (uint8(ss[si]) ^ 0x80) & 0xFF; if(c & 0xC0 == 1) return (-3, unicodes); l = (l<<6) | c; } if (!matched) return (-4, unicodes); } uint32[] memory result = new uint32[](ui); for (uint i=0; i<ui; i++) { result[i] = unicodes[i]; } return (0, result); } function encode(uint32[] memory unicodes) external pure returns (bytes memory) { Tab[] memory tab = tabForUTF8(); uint8[] memory s = new uint8[](unicodes.length * 5); uint64 l; uint32 c; uint32 nc; uint si; for (uint i = 0; i < unicodes.length; i++) { l = unicodes[i]; nc = 0; for(uint j = 0; j < tab.length; j++) { nc++; Tab memory t = tab[j]; if(l <= t.lmask) { c = t.shift; s[si] = uint8(t.cval | (l>>c)); si++; while(c > 0) { c -= 6; s[si] = uint8(0x80 | ((l>>c) & 0x3F)); si++; } break; } } } bytes memory result = new bytes(si); for (uint i=0; i<si; i++) { result[i] = bytes1(s[i]); } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; library Utils { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function b64encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } function uint2str(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function addr2str(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(bytes1 b) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function trim(string memory str) internal pure returns (string memory) { bytes memory bStr = bytes(str); uint nStart = 0; uint nEnd = bStr.length-1; while (uint8(bStr[nStart]) == 32 && nStart <= bStr.length-1) { nStart++; } while (uint8(bStr[nEnd]) == 32 && nEnd >= nStart) { nEnd--; } if (nStart > nEnd) { return ""; } bytes memory newBytes = new bytes(nEnd - nStart + 1); //copy uint j=0; for(uint i = nStart; i<= nEnd; i++) { newBytes[j] = bStr[i]; j++; } return string(newBytes); } function lowercase(string memory str) internal pure returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // A-Z... --> a-z if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } function getChainId() internal view returns (uint256 chainId) { assembly { chainId := chainid() } } function getNetwork() internal view returns (string memory) { string[6] memory networks; networks[1] = "mainnet"; networks[3] = "ropsten"; networks[4] = "rinkeby"; networks[5] = "goerli"; uint256 cid = getChainId(); return networks[cid]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; interface IENS { // 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; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address owner, address operator) external view returns (bool); } abstract contract EnsOwnable { address private _ensRegistry = address(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; bool requireENS = true; function node(address addr) pure internal returns (bytes32 ret) { return keccak256(abi.encodePacked(ADDR_REVERSE_NODE, sha3HexAddress(addr))); } function contractDeployed(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } function hasENS(address addr) internal view returns(bool) { if (!contractDeployed(_ensRegistry)) { return true; //local chain, bypass } bytes32 namehash = node(addr); return IENS(_ensRegistry).owner(namehash) != address(0); } function sha3HexAddress(address addr) private pure returns (bytes32 ret) { addr; ret; // Stop warning us about unused variables assembly { let lookup := 0x3031323334353637383961626364656600000000000000000000000000000000 for { let i := 40 } gt(i, 0) { } { i := sub(i, 1) mstore8(i, byte(and(addr, 0xf), lookup)) addr := div(addr, 0x10) i := sub(i, 1) mstore8(i, byte(and(addr, 0xf), lookup)) addr := div(addr, 0x10) } ret := keccak256(0, 40) } } modifier onlyEnsOwner() { if (requireENS) { require(hasENS(msg.sender), "only for ENS owner"); } _; } }
Encodes some bytes to the base64 representation multiply by 4/3 rounded up Add some extra buffer at the end
function b64encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; uint256 encodedLen = 4 * ((len + 2) / 3); bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); }
12,239,685
./full_match/1/0x66d97FD4DefEcD79904B3D3587dC4f8ed66Cf4Ab/sources/src/lib/LSSVMPairCloner.sol
Checks if a contract is a clone of a LSSVMPairERC1155ERC20. Only checks the runtime bytecode, does not check the extra data. implementation the LSSVMPairERC1155ERC20 implementation contract query the contract to check return result True if the contract is a clone, false otherwise/ solhint-disable-next-line no-inline-assembly compare expected bytecode with that of the queried contract
function isERC1155ERC20PairClone(address factory, address implementation, address query) internal view returns (bool result) { assembly { let ptr := mload(0x40) mstore(ptr, hex"3d3d3d3d363d3d37607160353639366071013d73000000000000000000000000") mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), hex"5af43d3d93803e603357fd5bf300000000000000000000000000000000000000") mstore(add(ptr, 0x35), shl(0x60, factory)) let other := add(ptr, 0x49) extcodecopy(query, other, 0, 0x49) result := and( eq(mload(ptr), mload(other)), and( eq(mload(add(ptr, 0x20)), mload(add(other, 0x20))), eq(mload(add(ptr, 0x29)), mload(add(other, 0x29))) ) ) } }
8,298,143
/** *Submitted for verification at Etherscan.io on 2021-06-14 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /** * @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); 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); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ 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); } 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; } } 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 () { 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"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); 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 feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract EthanolX is Ownable, IERC20Metadata { IUniswapV2Factory public uniswapV2Factory; IUniswapV2Router02 public uniswapV2Router; string private _name; string private _symbol; uint256 private _totalSupply; uint256 public startTime; uint256 private _cashbackInterval; uint256 private _initialDitributionAmount; uint256 public ditributionRewardsPool; uint256 public liquidityRewardsPool; uint256 public taxPercentage; uint8 public activateFeatures; uint256 public stabilizingRewardsPool; uint8 public lastStabilizeAction; uint256 private _stabilizeTokenAmount; address public referralWallet; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping(address => Cashback) public cashbacks; mapping(address => bool) public excluded; mapping(address => address) public referrers; mapping(address => uint256) public weeklyPayouts; struct Cashback { address user; uint256 timestamp; uint256 totalClaimedRewards; } event CashBackClaimed(address indexed user, uint256 amount, uint256 timestamp); event Refund(address indexed user, uint256 amount, uint256 timestamp); event SwapAndAddLiquidity(address indexed sender, uint256 tokensSwapped, uint256 ethReceived); event Referral(address indexed user, address indexed referrer, uint256 timestamp); event Stablize(string action, uint256 tokenAmount, uint256 ethAmount, uint256 timestamp); constructor(address _referralWallet) { _name = "EthanolX"; _symbol = "ENOX"; uint256 _initialSupply = 10000000 ether; uint256 _minterAmount = (_initialSupply * 70) / 100; uint256 _ditributionAmount = (_initialSupply * 30) / 100; startTime = block.timestamp; _cashbackInterval = 24 hours; taxPercentage = 8; activateFeatures = 0; lastStabilizeAction = 0; _stabilizeTokenAmount = 1000 ether; _initialDitributionAmount = _ditributionAmount; ditributionRewardsPool = _ditributionAmount; _mint(_msgSender(), _minterAmount); _mint(address(this), _ditributionAmount); referralWallet = _referralWallet; /* instantiate uniswapV2Router & uniswapV2Factory uniswapV2Router address: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D pancakeswapV2Router address: 0xD99D1c33F9fC3444f8101754aBC46c52416550D1 */ uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Factory = IUniswapV2Factory(uniswapV2Router.factory()); // create ENOX -> WETH pair uniswapV2Factory.createPair(address(this), uniswapV2Router.WETH()); excluded[address(this)] = true; excluded[address(uniswapV2Router)] = true; excluded[address(uniswapV2Factory)] = true; excluded[getPair()] = true; } receive() external payable { } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns(uint256) { uint256 _initialBalance = _balances[account]; uint256 _finalBalance = _initialBalance + calculateRewards(account); return _finalBalance; } 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 transfer(address recipient, uint256 amount) public virtual override returns (bool) { // claim accumulated cashbacks _claimCashback(recipient); // transfer token from caller to recipient _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { // claim accumulated cashbacks for sender and the recipient _claimCashback(sender); _claimCashback(recipient); // transfer token from sender to recipient _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); // calculate tax from transferred amount (uint256 _finalAmount, uint256 _tax) = _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += _finalAmount; _balances[address(this)] += _tax; _distributeTax(_tax); /* Note:: A static "startTime" might lead to an unforseen _cashback bug in the future. A way of mitigating this is to automaticaly update the startTime every 24 hours on deployment */ if((block.timestamp - startTime) >= _cashbackInterval) startTime = block.timestamp; emit Transfer(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); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function burn(uint256 _amount) external { _burn(_msgSender(), _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, address, uint256 amount) internal virtual returns(uint256 _finalAmount, uint256 _tax) { if(taxPercentage == 0 || activateFeatures == 0 || excluded[_msgSender()]) return(amount, 0); _tax = (amount * 8) / 100; _finalAmount = amount - _tax; return(_finalAmount, _tax); } function setActivateFeatures() external onlyOwner { if(activateFeatures == 0) activateFeatures = 1; else activateFeatures = 0; } function setExcluded(address _account, bool _status) external onlyOwner { excluded[_account] = _status; } function setTransferFee(uint256 _amount) public onlyOwner { taxPercentage = _amount; } function _distributeTax(uint256 _amount) internal returns(uint8) { if(getPair() == address(0) || activateFeatures == 0 || _amount == 0) return 0; uint256 _splitedAmount = _amount / 4; /* Add twice of the _splitedAmount to ditributionRewardsPool, this will later be deducted as referrer's rewards */ ditributionRewardsPool += (_splitedAmount * 2); stabilizingRewardsPool += _splitedAmount; liquidityRewardsPool += _splitedAmount; _balances[referralWallet] += _splitedAmount; return 1; } function injectLpToken() public onlyOwner returns(uint8) { if(liquidityRewardsPool == 0) return 0; _addLiquidity(liquidityRewardsPool); return 1; } function withdrawLpToken() external onlyOwner { _transfer(address(this), _msgSender(), liquidityRewardsPool); liquidityRewardsPool = 0; } // Start CashBack Logics function setCashbackInterval(uint256 _value) external onlyOwner { _cashbackInterval = _value; } function _claimCashback(address _account) internal returns(uint8) { if(calculateRewards(_account) == 0) return 0; uint256 _totalClaimedRewards = cashbacks[_account].totalClaimedRewards; uint256 _rewards = _transferRewards(_account); cashbacks[_account] = Cashback(_account, block.timestamp, _totalClaimedRewards + _rewards); emit CashBackClaimed(_account, _rewards, block.timestamp); return 1; } function calculateRewards(address _account) public view returns(uint256) { // should return zero is _account has zero balance || _account => contract address if(_balances[_account] == 0 || _isContract(_account) || _cashbackInterval == 0) return 0; uint256 _lastClaimedTime = 0; /* This logic sets the initial claimedTime to the timestamp the contract was deployed. Since the cashbacks[_account].timestamp will always be zero for all users when the contract is being deployed */ cashbacks[_account].timestamp == 0 ? _lastClaimedTime = startTime : _lastClaimedTime = cashbacks[_account].timestamp; // calculates for the unclaimed days using (current time - last claimed time) / cashbackInterval (24 hours on deployment) uint256 _unclaimedDays = (block.timestamp - _lastClaimedTime) / _cashbackInterval; uint256 _rewards = _unclaimedDays * calculateDailyCashback(_account); return _rewards; } function calculateDailyCashback(address _account) public view returns(uint256 _rewardsPerDay) { uint256 _accountBalance = _balances[_account]; _rewardsPerDay = (_accountBalance * 2) / 100; return _rewardsPerDay; } function _transferRewards(address _account) private returns(uint256) { uint256 _rewards = calculateRewards(_account); uint256 _seventyPercent = (ditributionRewardsPool * 70) / 100; uint256 _diff = ditributionRewardsPool - _initialDitributionAmount; if(ditributionRewardsPool <= _seventyPercent) { _mint(address(this), _diff); ditributionRewardsPool += _diff; } if(_rewards > ditributionRewardsPool) { _mint(address(this), _rewards); ditributionRewardsPool += _rewards; } ditributionRewardsPool -= _rewards; _transfer(address(this), _account, _rewards); return _rewards; } // End CashBack Logics // Referral Logics function registerReferrer(address _referrer) external { require(referrers[_msgSender()] == address(0), "EthanolX: Referrer has already been registered"); require(_msgSender() != _referrer, "EthanolX: Can not register self as referrer"); require(balanceOf(_msgSender()) != 0, "EthanolX: Balance must be greater than zero to register a referrer"); require(!_isContract(_referrer), "EthanolX: Referrer can not be contract address"); referrers[_msgSender()] = _referrer; emit Referral(_msgSender(), _referrer, block.timestamp); } // End Referral Logics // Stabilizing mechanism function stabilize() public onlyOwner { _stab(); } function _stab() internal returns(uint8 _res) { address[] memory path = new address[](2); uint256[] memory amounts; /* lastStabilizeAction == 0 => Swap ENOX -> ETH lastStabilizeAction == 1 => Swap ETH -> ENOX */ if(lastStabilizeAction == 0) { if(stabilizingRewardsPool < _stabilizeTokenAmount) return 0; path[0] = address(this); path[1] = uniswapV2Router.WETH(); amounts = getAmountsOut(address(this), uniswapV2Router.WETH(), _stabilizeTokenAmount); // approve _stabilizeTokenAmount to be swapped for ETH _approve(address(this), address(uniswapV2Router), _stabilizeTokenAmount); // swap ENOX => ETH uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(_stabilizeTokenAmount, 0, path, address(this), block.timestamp); // re-set global state variable stabilizingRewardsPool -= _stabilizeTokenAmount; lastStabilizeAction = 1; emit Stablize("SELL", _stabilizeTokenAmount, amounts[1], block.timestamp); } else { path[0] = uniswapV2Router.WETH(); path[1] = address(this); amounts = getAmountsOut(address(this), uniswapV2Router.WETH(), _stabilizeTokenAmount); // swap ETH => ENOX uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amounts[1]}( 0, path, owner(), block.timestamp ); _transfer(owner(), address(this), amounts[0]); // re-set global state variable stabilizingRewardsPool += _stabilizeTokenAmount; lastStabilizeAction = 0; emit Stablize("BUY", amounts[0], amounts[1], block.timestamp); return 1; } } function withdrawStabilizeRewards() public onlyOwner { _transfer(address(this), _msgSender(), stabilizingRewardsPool); stabilizingRewardsPool = 0; } function setStabilizeTokenAmount(uint256 _amount) external onlyOwner { _stabilizeTokenAmount = _amount; } function getStabilizeTokenAmount() external view returns(uint256) { return _stabilizeTokenAmount; } // End stabilizing mechanism // Uniswap Trade Logics function getPair() public view returns(address pair) { pair = uniswapV2Factory.getPair(address(this), uniswapV2Router.WETH()); return pair; } function getAmountsOut(address token1, address token2, uint256 _amount) public view returns(uint256[] memory amounts) { address[] memory path = new address[](2); path[0] = token1; path[1] = token2; amounts = uniswapV2Router.getAmountsOut(_amount, path); return amounts; } function _addLiquidity(uint256 tokenAmount) private { uint256 _half = tokenAmount / 2; address[] memory path = new address[](2); uint256[] memory amounts = getAmountsOut(address(this), uniswapV2Router.WETH(), _half); path[0] = address(this); path[1] = uniswapV2Router.WETH(); // approve transferred amount to uniswapV2Router _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( _half, 0, path, address(this), block.timestamp ); uniswapV2Router.addLiquidityETH{value: amounts[1]}( address(this), _half, 0, 0, owner(), block.timestamp ); emit SwapAndAddLiquidity(owner(), _half, amounts[1]); } function withdrawETH() external onlyOwner { (bool _success, ) = payable(_msgSender()).call{ value: address(this).balance }(bytes("")); require(_success, "EthanolX: ETH withdrawal failed"); } function _isContract(address account) internal view returns(bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } }
claim accumulated cashbacks for sender and the recipient transfer token from sender to recipient
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _claimCashback(sender); _claimCashback(recipient); _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; }
15,418,923
// File: contracts/interfaces/ILiquidationManager.sol pragma solidity 0.6.12; /** * @title BiFi's liquidation manager interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface ILiquidationManager { function setCircuitBreaker(bool _emergency) external returns (bool); function partialLiquidation(address payable delinquentBorrower, uint256 targetHandler, uint256 liquidateAmount, uint256 receiveHandler) external returns (uint256); function checkLiquidation(address payable userAddr) external view returns (bool); } // File: contracts/interfaces/IManagerSlotSetter.sol pragma solidity 0.6.12; /** * @title BiFi's Manager Context Setter interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IManagerSlotSetter { function ownershipTransfer(address payable _owner) external returns (bool); function setOperator(address payable adminAddr, bool flag) external returns (bool); function setOracleProxy(address oracleProxyAddr) external returns (bool); function setRewardErc20(address erc20Addr) external returns (bool); function setBreakerTable(address _target, bool _status) external returns (bool); function setCircuitBreaker(bool _emergency) external returns (bool); function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) external returns (bool); function setLiquidationManager(address liquidationManagerAddr) external returns (bool); function setHandlerSupport(uint256 handlerID, bool support) external returns (bool); function setPositionStorageAddr(address _positionStorageAddr) external returns (bool); function setNFTAddr(address _nftAddr) external returns (bool); function setDiscountBase(uint256 handlerID, uint256 feeBase) external returns (bool); } // File: contracts/interfaces/IHandlerManager.sol pragma solidity 0.6.12; /** * @title BiFi's Manager Interest interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IHandlerManager { function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256); function interestUpdateReward() external returns (bool); function updateRewardParams(address payable userAddr) external returns (bool); function rewardClaimAll(address payable userAddr) external returns (uint256); function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256); function ownerRewardTransfer(uint256 _amount) external returns (bool); } // File: contracts/interfaces/IManagerFlashloan.sol pragma solidity 0.6.12; interface IManagerFlashloan { function withdrawFlashloanFee(uint256 handlerID) external returns (bool); function flashloan( uint256 handlerID, address receiverAddress, uint256 amount, bytes calldata params ) external returns (bool); function getFee(uint256 handlerID, uint256 amount) external view returns (uint256); function getFeeTotal(uint256 handlerID) external view returns (uint256); function getFeeFromArguments(uint256 handlerID, uint256 amount, uint256 bifiAmo) external view returns (uint256); } // File: contracts/SafeMath.sol pragma solidity ^0.6.12; // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol // Subject to the MIT license. /** * @title BiFi's safe-math Contract * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ library SafeMath { uint256 internal constant unifiedPoint = 10 ** 18; /******************** Safe Math********************/ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "a"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "s"); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return _mul(a, b); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return _div(a, b, "d"); } function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function _mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a* b; require((c / a) == b, "m"); return c; } function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, unifiedPoint), b, "d"); } function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, b), unifiedPoint, "m"); } } // File: contracts/interfaces/IManagerDataStorage.sol pragma solidity 0.6.12; /** * @title BiFi's manager data storage interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IManagerDataStorage { function getGlobalRewardPerBlock() external view returns (uint256); function setGlobalRewardPerBlock(uint256 _globalRewardPerBlock) external returns (bool); function getGlobalRewardDecrement() external view returns (uint256); function setGlobalRewardDecrement(uint256 _globalRewardDecrement) external returns (bool); function getGlobalRewardTotalAmount() external view returns (uint256); function setGlobalRewardTotalAmount(uint256 _globalRewardTotalAmount) external returns (bool); function getAlphaRate() external view returns (uint256); function setAlphaRate(uint256 _alphaRate) external returns (bool); function getAlphaLastUpdated() external view returns (uint256); function setAlphaLastUpdated(uint256 _alphaLastUpdated) external returns (bool); function getRewardParamUpdateRewardPerBlock() external view returns (uint256); function setRewardParamUpdateRewardPerBlock(uint256 _rewardParamUpdateRewardPerBlock) external returns (bool); function getRewardParamUpdated() external view returns (uint256); function setRewardParamUpdated(uint256 _rewardParamUpdated) external returns (bool); function getInterestUpdateRewardPerblock() external view returns (uint256); function setInterestUpdateRewardPerblock(uint256 _interestUpdateRewardPerblock) external returns (bool); function getInterestRewardUpdated() external view returns (uint256); function setInterestRewardUpdated(uint256 _interestRewardLastUpdated) external returns (bool); function setTokenHandler(uint256 handlerID, address handlerAddr) external returns (bool); function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address); function getTokenHandlerID(uint256 index) external view returns (uint256); function getTokenHandlerAddr(uint256 handlerID) external view returns (address); function setTokenHandlerAddr(uint256 handlerID, address handlerAddr) external returns (bool); function getTokenHandlerExist(uint256 handlerID) external view returns (bool); function setTokenHandlerExist(uint256 handlerID, bool exist) external returns (bool); function getTokenHandlerSupport(uint256 handlerID) external view returns (bool); function setTokenHandlerSupport(uint256 handlerID, bool support) external returns (bool); function setLiquidationManagerAddr(address _liquidationManagerAddr) external returns (bool); function getLiquidationManagerAddr() external view returns (address); function setManagerAddr(address _managerAddr) external returns (bool); } // File: contracts/interfaces/IOracleProxy.sol pragma solidity 0.6.12; /** * @title BiFi's oracle proxy interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IOracleProxy { function getTokenPrice(uint256 tokenID) external view returns (uint256); function getOracleFeed(uint256 tokenID) external view returns (address, uint256); function setOracleFeed(uint256 tokenID, address feedAddr, uint256 decimals, bool needPriceConvert, uint256 priceConvertID) external returns (bool); } // File: contracts/interfaces/IERC20.sol // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external ; 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 ; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IObserver.sol pragma solidity 0.6.12; /** * @title BiFi's Observer interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IObserver { function getAlphaBaseAsset() external view returns (uint256[] memory); function setChainGlobalRewardPerblock(uint256 _idx, uint256 globalRewardPerBlocks) external returns (bool); function updateChainMarketInfo(uint256 _idx, uint256 chainDeposit, uint256 chainBorrow) external returns (bool); } // File: contracts/interfaces/IProxy.sol pragma solidity 0.6.12; /** * @title BiFi's proxy interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IProxy { function handlerProxy(bytes memory data) external returns (bool, bytes memory); function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory); function siProxy(bytes memory data) external returns (bool, bytes memory); function siViewProxy(bytes memory data) external view returns (bool, bytes memory); } // File: contracts/interfaces/IMarketHandler.sol pragma solidity 0.6.12; /** * @title BiFi's market handler interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketHandler { function setCircuitBreaker(bool _emergency) external returns (bool); function setCircuitBreakWithOwner(bool _emergency) external returns (bool); function getTokenName() external view returns (string memory); function ownershipTransfer(address payable newOwner) external returns (bool); function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function executeFlashloan( address receiverAddress, uint256 amount ) external returns (bool); function depositFlashloanFee( uint256 amount ) external returns (bool); function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256); function getTokenHandlerLimit() external view returns (uint256, uint256); function getTokenHandlerBorrowLimit() external view returns (uint256); function getTokenHandlerMarginCallLimit() external view returns (uint256); function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool); function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool); function getTokenLiquidityAmountWithInterest(address payable userAddr) external view returns (uint256); function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256); function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256); function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256); function checkFirstAction() external returns (bool); function applyInterest(address payable userAddr) external returns (uint256, uint256); function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool); function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool); function withdrawFlashloanFee(uint256 unifiedTokenAmount) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function getSIRandBIR() external view returns (uint256, uint256); function getERC20Addr() external view returns (address); } // File: contracts/interfaces/IServiceIncentive.sol pragma solidity 0.6.12; /** * @title BiFi's si interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IServiceIncentive { function setCircuitBreakWithOwner(bool emergency) external returns (bool); function setCircuitBreaker(bool emergency) external returns (bool); function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool); function updateRewardLane(address payable userAddr) external returns (bool); function getBetaRateBaseTotalAmount() external view returns (uint256); function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256); function claimRewardAmountUser(address payable userAddr) external returns (uint256); } // File: contracts/Errors.sol pragma solidity 0.6.12; contract Modifier { string internal constant ONLY_OWNER = "O"; string internal constant ONLY_MANAGER = "M"; string internal constant CIRCUIT_BREAKER = "emergency"; } contract ManagerModifier is Modifier { string internal constant ONLY_HANDLER = "H"; string internal constant ONLY_LIQUIDATION_MANAGER = "LM"; string internal constant ONLY_BREAKER = "B"; } contract HandlerDataStorageModifier is Modifier { string internal constant ONLY_BIFI_CONTRACT = "BF"; } contract SIDataStorageModifier is Modifier { string internal constant ONLY_SI_HANDLER = "SI"; } contract HandlerErrors is Modifier { string internal constant USE_VAULE = "use value"; string internal constant USE_ARG = "use arg"; string internal constant EXCEED_LIMIT = "exceed limit"; string internal constant NO_LIQUIDATION = "no liquidation"; string internal constant NO_LIQUIDATION_REWARD = "no enough reward"; string internal constant NO_EFFECTIVE_BALANCE = "not enough balance"; string internal constant TRANSFER = "err transfer"; } contract SIErrors is Modifier { } contract InterestErrors is Modifier { } contract LiquidationManagerErrors is Modifier { string internal constant NO_DELINQUENT = "not delinquent"; } contract ManagerErrors is ManagerModifier { string internal constant REWARD_TRANSFER = "RT"; string internal constant UNSUPPORTED_TOKEN = "UT"; } contract OracleProxyErrors is Modifier { string internal constant ZERO_PRICE = "price zero"; } contract RequestProxyErrors is Modifier { } contract ManagerDataStorageErrors is ManagerModifier { string internal constant NULL_ADDRESS = "err addr null"; } // File: contracts/marketManager/ManagerSlot.sol pragma solidity 0.6.12; /** * @title BiFi's Slot contract * @notice Manager Slot Definitions & Allocations * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract ManagerSlot is ManagerErrors { using SafeMath for uint256; address public owner; mapping(address => bool) operators; mapping(address => Breaker) internal breakerTable; bool public emergency = false; IManagerDataStorage internal dataStorageInstance; IOracleProxy internal oracleProxy; /* feat: manager reward token instance*/ IERC20 internal rewardErc20Instance; IObserver public Observer; address public slotSetterAddr; address public handlerManagerAddr; address public flashloanAddr; // BiFi-X address public positionStorageAddr; address public nftAddr; uint256 public tokenHandlerLength; struct FeeRateParams { uint256 unifiedPoint; uint256 minimum; uint256 slope; uint256 discountRate; } struct HandlerFlashloan { uint256 flashFeeRate; uint256 discountBase; uint256 feeTotal; } mapping(uint256 => HandlerFlashloan) public handlerFlashloan; struct UserAssetsInfo { uint256 depositAssetSum; uint256 borrowAssetSum; uint256 marginCallLimitSum; uint256 depositAssetBorrowLimitSum; uint256 depositAsset; uint256 borrowAsset; uint256 price; uint256 callerPrice; uint256 depositAmount; uint256 borrowAmount; uint256 borrowLimit; uint256 marginCallLimit; uint256 callerBorrowLimit; uint256 userBorrowableAsset; uint256 withdrawableAsset; } struct Breaker { bool auth; bool tried; } struct ContractInfo { bool support; address addr; address tokenAddr; uint256 expectedBalance; uint256 afterBalance; IProxy tokenHandler; bytes data; IMarketHandler handlerFunction; IServiceIncentive siFunction; IOracleProxy oracleProxy; IManagerDataStorage managerDataStorage; } modifier onlyOwner { require(msg.sender == owner, ONLY_OWNER); _; } modifier onlyHandler(uint256 handlerID) { _isHandler(handlerID); _; } modifier onlyOperators { address payable sender = msg.sender; require(operators[sender] || sender == owner); _; } function _isHandler(uint256 handlerID) internal view { address msgSender = msg.sender; require((msgSender == dataStorageInstance.getTokenHandlerAddr(handlerID)) || (msgSender == owner), ONLY_HANDLER); } modifier onlyLiquidationManager { _isLiquidationManager(); _; } function _isLiquidationManager() internal view { address msgSender = msg.sender; require((msgSender == dataStorageInstance.getLiquidationManagerAddr()) || (msgSender == owner), ONLY_LIQUIDATION_MANAGER); } modifier circuitBreaker { _isCircuitBreak(); _; } function _isCircuitBreak() internal view { require((!emergency) || (msg.sender == owner), CIRCUIT_BREAKER); } modifier onlyBreaker { _isBreaker(); _; } function _isBreaker() internal view { require(breakerTable[msg.sender].auth, ONLY_BREAKER); } } // File: contracts/marketManager/TokenManager.sol // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; /** * @title BiFi's marketManager contract * @notice Implement business logic and manage handlers * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract TokenManager is ManagerSlot { /** * @dev Constructor for marketManager * @param managerDataStorageAddr The address of the manager storage contract * @param oracleProxyAddr The address of oracle proxy contract (e.g., price feeds) * @param breaker The address of default circuit breaker * @param erc20Addr The address of reward token (ERC-20) */ constructor (address managerDataStorageAddr, address oracleProxyAddr, address _slotSetterAddr, address _handlerManagerAddr, address _flashloanAddr, address breaker, address erc20Addr) public { owner = msg.sender; dataStorageInstance = IManagerDataStorage(managerDataStorageAddr); oracleProxy = IOracleProxy(oracleProxyAddr); rewardErc20Instance = IERC20(erc20Addr); slotSetterAddr = _slotSetterAddr; handlerManagerAddr = _handlerManagerAddr; flashloanAddr = _flashloanAddr; breakerTable[owner].auth = true; breakerTable[breaker].auth = true; } /** * @dev Transfer ownership * @param _owner the address of the new owner * @return result the setter call in contextSetter contract */ function ownershipTransfer(address payable _owner) onlyOwner public returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .ownershipTransfer.selector, _owner ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setOperator(address payable adminAddr, bool flag) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setOperator.selector, adminAddr, flag ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set the address of OracleProxy contract * @param oracleProxyAddr The address of OracleProxy contract * @return result the setter call in contextSetter contract */ function setOracleProxy(address oracleProxyAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setOracleProxy.selector, oracleProxyAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set the address of BiFi reward token contract * @param erc20Addr The address of BiFi reward token contract * @return result the setter call in contextSetter contract */ function setRewardErc20(address erc20Addr) onlyOwner public returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setRewardErc20.selector, erc20Addr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Authorize admin user for circuitBreaker * @param _target The address of the circuitBreaker admin user. * @param _status The boolean status of circuitBreaker (on/off) * @return result the setter call in contextSetter contract */ function setBreakerTable(address _target, bool _status) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setBreakerTable.selector, _target, _status ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set circuitBreak to freeze/unfreeze all handlers * @param _emergency The boolean status of circuitBreaker (on/off) * @return result the setter call in contextSetter contract */ function setCircuitBreaker(bool _emergency) onlyBreaker external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setCircuitBreaker.selector, _emergency ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setPositionStorageAddr(address _positionStorageAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter.setPositionStorageAddr.selector, _positionStorageAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setNFTAddr(address _nftAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter.setNFTAddr.selector, _nftAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setDiscountBase(uint256 handlerID, uint256 feeBase) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setDiscountBase.selector, handlerID, feeBase ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Get the circuitBreak status * @return The circuitBreak status */ function getCircuitBreaker() external view returns (bool) { return emergency; } /** * @dev Get information for a handler * @param handlerID Handler ID * @return (success or failure, handler address, handler name) */ function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory) { bool support; address tokenHandlerAddr; string memory tokenName; if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID); IProxy TokenHandler = IProxy(tokenHandlerAddr); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getTokenName.selector ) ); tokenName = abi.decode(data, (string)); support = true; } return (support, tokenHandlerAddr, tokenName); } /** * @dev Register a handler * @param handlerID Handler ID and address * @param tokenHandlerAddr The handler address * @return result the setter call in contextSetter contract */ function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .handlerRegister.selector, handlerID, tokenHandlerAddr, flashFeeRate, discountBase ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set a liquidation manager contract * @param liquidationManagerAddr The address of liquidiation manager * @return result the setter call in contextSetter contract */ function setLiquidationManager(address liquidationManagerAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setLiquidationManager.selector, liquidationManagerAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Update the (SI) rewards for a user * @param userAddr The address of the user * @param callerID The handler ID * @return true (TODO: validate results) */ function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool) { ContractInfo memory handlerInfo; (handlerInfo.support, handlerInfo.addr) = dataStorageInstance.getTokenHandlerInfo(callerID); if (handlerInfo.support) { IProxy TokenHandler; TokenHandler = IProxy(handlerInfo.addr); TokenHandler.siProxy( abi.encodeWithSelector( IServiceIncentive .updateRewardLane.selector, userAddr ) ); } return true; } /** * @dev Update interest of a user for a handler (internal) * @param userAddr The user address * @param callerID The handler ID * @param allFlag Flag for the full calculation mode (calculting for all handlers) * @return (uint256, uint256, uint256, uint256, uint256, uint256) */ function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .applyInterestHandlers.selector, userAddr, callerID, allFlag ); (bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256, uint256, uint256, uint256, uint256, uint256)); } /** * @dev Reward the user (msg.sender) with the reward token after calculating interest. * @return result the interestUpdateReward call in ManagerInterest contract */ function interestUpdateReward() external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .interestUpdateReward.selector ); (result, ) = handlerManagerAddr.delegatecall(callData); assert(result); } /** * @dev (Update operation) update the rewards parameters. * @param userAddr The address of operator * @return result the updateRewardParams call in ManagerInterest contract */ function updateRewardParams(address payable userAddr) onlyOperators external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .updateRewardParams.selector, userAddr ); (result, ) = handlerManagerAddr.delegatecall(callData); assert(result); } /** * @dev Claim all rewards for the user * @param userAddr The user address * @return true (TODO: validate results) */ function rewardClaimAll(address payable userAddr) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .rewardClaimAll.selector, userAddr ); (bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Claim handler rewards for the user * @param handlerID The ID of claim reward handler * @param userAddr The user address * @return true (TODO: validate results) */ function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .claimHandlerReward.selector, handlerID, userAddr ); (bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Transfer reward tokens to owner (for administration) * @param _amount The amount of the reward token * @return result (TODO: validate results) */ function ownerRewardTransfer(uint256 _amount) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .ownerRewardTransfer.selector, _amount ); (result, ) = handlerManagerAddr.delegatecall(callData); assert(result); } /** * @dev Get the token price of the handler * @param handlerID The handler ID * @return The token price of the handler */ function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256) { return _getTokenHandlerPrice(handlerID); } /** * @dev Get the margin call limit of the handler (external) * @param handlerID The handler ID * @return The margin call limit */ function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256) { return _getTokenHandlerMarginCallLimit(handlerID); } /** * @dev Get the margin call limit of the handler (internal) * @param handlerID The handler ID * @return The margin call limit */ function _getTokenHandlerMarginCallLimit(uint256 handlerID) internal view returns (uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getTokenHandlerMarginCallLimit.selector ) ); return abi.decode(data, (uint256)); } /** * @dev Get the borrow limit of the handler (external) * @param handlerID The handler ID * @return The borrow limit */ function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256) { return _getTokenHandlerBorrowLimit(handlerID); } /** * @dev Get the borrow limit of the handler (internal) * @param handlerID The handler ID * @return The borrow limit */ function _getTokenHandlerBorrowLimit(uint256 handlerID) internal view returns (uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getTokenHandlerBorrowLimit.selector ) ); return abi.decode(data, (uint256)); } /** * @dev Get the handler status of whether the handler is supported or not. * @param handlerID The handler ID * @return Whether the handler is supported or not */ function getTokenHandlerSupport(uint256 handlerID) external view returns (bool) { return dataStorageInstance.getTokenHandlerSupport(handlerID); } /** * @dev Set the length of the handler list * @param _tokenHandlerLength The length of the handler list * @return true (TODO: validate results) */ function setTokenHandlersLength(uint256 _tokenHandlerLength) onlyOwner external returns (bool) { tokenHandlerLength = _tokenHandlerLength; return true; } /** * @dev Get the length of the handler list * @return the length of the handler list */ function getTokenHandlersLength() external view returns (uint256) { return tokenHandlerLength; } /** * @dev Get the handler ID at the index in the handler list * @param index The index of the handler list (array) * @return The handler ID */ function getTokenHandlerID(uint256 index) external view returns (uint256) { return dataStorageInstance.getTokenHandlerID(index); } /** * @dev Get the amount of token that the user can borrow more * @param userAddr The address of user * @param handlerID The handler ID * @return The amount of token that user can borrow more */ function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256) { return _getUserExtraLiquidityAmount(userAddr, handlerID); } /** * @dev Get the deposit and borrow amount of the user with interest added * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount of the user with interest */ /* about user market Information function*/ function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256) { return _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); } /** * @dev Get the depositTotalCredit and borrowTotalCredit * @param userAddr The address of the user * @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit) * @return borrowTotalCredit The sum of borrow amount for all handlers */ function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256) { return _getUserTotalIntraCreditAsset(userAddr); } /** * @dev Get the borrow and margin call limits of the user for all handlers * @param userAddr The address of the user * @return userTotalBorrowLimitAsset the sum of borrow limit for all handlers * @return userTotalMarginCallLimitAsset the sume of margin call limit for handlers */ function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256) { uint256 userTotalBorrowLimitAsset; uint256 userTotalMarginCallLimitAsset; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { uint256 depositHandlerAsset; uint256 borrowHandlerAsset; (depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID); uint256 marginCallLimit = _getTokenHandlerMarginCallLimit(handlerID); uint256 userBorrowLimitAsset = depositHandlerAsset.unifiedMul(borrowLimit); uint256 userMarginCallLimitAsset = depositHandlerAsset.unifiedMul(marginCallLimit); userTotalBorrowLimitAsset = userTotalBorrowLimitAsset.add(userBorrowLimitAsset); userTotalMarginCallLimitAsset = userTotalMarginCallLimitAsset.add(userMarginCallLimitAsset); } else { continue; } } return (userTotalBorrowLimitAsset, userTotalMarginCallLimitAsset); } /** * @dev Get the maximum allowed amount to borrow of the user from the given handler * @param userAddr The address of the user * @param callerID The target handler to borrow * @return extraCollateralAmount The maximum allowed amount to borrow from the handler. */ function getUserCollateralizableAmount(address payable userAddr, uint256 callerID) external view returns (uint256) { uint256 userTotalBorrowAsset; uint256 depositAssetBorrowLimitSum; uint256 depositHandlerAsset; uint256 borrowHandlerAsset; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { (depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); userTotalBorrowAsset = userTotalBorrowAsset.add(borrowHandlerAsset); depositAssetBorrowLimitSum = depositAssetBorrowLimitSum .add( depositHandlerAsset .unifiedMul( _getTokenHandlerBorrowLimit(handlerID) ) ); } } if (depositAssetBorrowLimitSum > userTotalBorrowAsset) { return depositAssetBorrowLimitSum .sub(userTotalBorrowAsset) .unifiedDiv( _getTokenHandlerBorrowLimit(callerID) ) .unifiedDiv( _getTokenHandlerPrice(callerID) ); } return 0; } /** * @dev Partial liquidation for a user * @param delinquentBorrower The address of the liquidation target * @param liquidateAmount The amount to liquidate * @param liquidator The address of the liquidator (liquidation operator) * @param liquidateHandlerID The hander ID of the liquidating asset * @param rewardHandlerID The handler ID of the reward token for the liquidator * @return (uint256, uint256, uint256) */ function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) onlyLiquidationManager external returns (uint256, uint256, uint256) { address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(liquidateHandlerID); IProxy TokenHandler = IProxy(tokenHandlerAddr); bytes memory data; data = abi.encodeWithSelector( IMarketHandler .partialLiquidationUser.selector, delinquentBorrower, liquidateAmount, liquidator, rewardHandlerID ); (, data) = TokenHandler.handlerProxy(data); return abi.decode(data, (uint256, uint256, uint256)); } /** * @dev Get the maximum liquidation reward by checking sufficient reward amount for the liquidator. * @param delinquentBorrower The address of the liquidation target * @param liquidateHandlerID The hander ID of the liquidating asset * @param liquidateAmount The amount to liquidate * @param rewardHandlerID The handler ID of the reward token for the liquidator * @param rewardRatio delinquentBorrowAsset / delinquentDepositAsset * @return The maximum reward token amount for the liquidator */ function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256) { uint256 liquidatePrice = _getTokenHandlerPrice(liquidateHandlerID); uint256 rewardPrice = _getTokenHandlerPrice(rewardHandlerID); uint256 delinquentBorrowerRewardDeposit; (delinquentBorrowerRewardDeposit, ) = _getHandlerAmount(delinquentBorrower, rewardHandlerID); uint256 rewardAsset = delinquentBorrowerRewardDeposit.unifiedMul(rewardPrice).unifiedMul(rewardRatio); if (liquidateAmount.unifiedMul(liquidatePrice) > rewardAsset) { return rewardAsset.unifiedDiv(liquidatePrice); } else { return liquidateAmount; } } /** * @dev Reward the liquidator * @param delinquentBorrower The address of the liquidation target * @param rewardAmount The amount of reward token * @param liquidator The address of the liquidator (liquidation operator) * @param handlerID The handler ID of the reward token for the liquidator * @return The amount of reward token */ function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external returns (uint256) { address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID); IProxy TokenHandler = IProxy(tokenHandlerAddr); bytes memory data; data = abi.encodeWithSelector( IMarketHandler .partialLiquidationUserReward.selector, delinquentBorrower, rewardAmount, liquidator ); (, data) = TokenHandler.handlerProxy(data); return abi.decode(data, (uint256)); } /** * @dev Execute flashloan contract with delegatecall * @param handlerID The ID of the token handler to borrow. * @param receiverAddress The address of receive callback contract * @param amount The amount of borrow through flashloan * @param params The encode metadata of user * @return Whether or not succeed */ function flashloan( uint256 handlerID, address receiverAddress, uint256 amount, bytes calldata params ) external returns (bool) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .flashloan.selector, handlerID, receiverAddress, amount, params ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (bool)); } /** * @dev Call flashloan logic contract with delegatecall * @param handlerID The ID of handler with accumulated flashloan fee * @return The amount of fee accumlated to handler */ function getFeeTotal(uint256 handlerID) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .getFeeTotal.selector, handlerID ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Withdraw accumulated flashloan fee with delegatecall * @param handlerID The ID of handler with accumulated flashloan fee * @return Whether or not succeed */ function withdrawFlashloanFee( uint256 handlerID ) external onlyOwner returns (bool) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .withdrawFlashloanFee.selector, handlerID ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (bool)); } /** * @dev Get flashloan fee for flashloan amount before make product(BiFi-X) * @param handlerID The ID of handler with accumulated flashloan fee * @param amount The amount of flashloan amount * @param bifiAmount The amount of Bifi amount * @return The amount of fee for flashloan amount */ function getFeeFromArguments( uint256 handlerID, uint256 amount, uint256 bifiAmount ) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .getFeeFromArguments.selector, handlerID, amount, bifiAmount ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Get the deposit and borrow amount of the user for the handler (internal) * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount */ function _getHandlerAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getUserAmount.selector, userAddr ) ); return abi.decode(data, (uint256, uint256)); } /** * @dev Get the deposit and borrow amount with interest of the user for the handler (internal) * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount with interest */ function _getHandlerAmountWithAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getUserAmountWithInterest.selector, userAddr ) ); return abi.decode(data, (uint256, uint256)); } /** * @dev Set the support stauts for the handler * @param handlerID the handler ID * @param support the support status (boolean) * @return result the setter call in contextSetter contract */ function setHandlerSupport(uint256 handlerID, bool support) onlyOwner public returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setHandlerSupport.selector, handlerID, support ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Get owner's address of the manager contract * @return The address of owner */ function getOwner() public view returns (address) { return owner; } /** * @dev Get the deposit and borrow amount of the user with interest added * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount of the user with interest */ function _getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { uint256 price = _getTokenHandlerPrice(handlerID); IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); uint256 depositAmount; uint256 borrowAmount; bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler.getUserAmountWithInterest.selector, userAddr ) ); (depositAmount, borrowAmount) = abi.decode(data, (uint256, uint256)); uint256 depositAsset = depositAmount.unifiedMul(price); uint256 borrowAsset = borrowAmount.unifiedMul(price); return (depositAsset, borrowAsset); } /** * @dev Get the depositTotalCredit and borrowTotalCredit * @param userAddr The address of the user * @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit) * @return borrowTotalCredit The sum of borrow amount for all handlers */ function _getUserTotalIntraCreditAsset(address payable userAddr) internal view returns (uint256, uint256) { uint256 depositTotalCredit; uint256 borrowTotalCredit; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { uint256 depositHandlerAsset; uint256 borrowHandlerAsset; (depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID); uint256 depositHandlerCredit = depositHandlerAsset.unifiedMul(borrowLimit); depositTotalCredit = depositTotalCredit.add(depositHandlerCredit); borrowTotalCredit = borrowTotalCredit.add(borrowHandlerAsset); } else { continue; } } return (depositTotalCredit, borrowTotalCredit); } /** * @dev Get the amount of token that the user can borrow more * @param userAddr The address of user * @param handlerID The handler ID * @return The amount of token that user can borrow more */ function _getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256) { uint256 depositCredit; uint256 borrowCredit; (depositCredit, borrowCredit) = _getUserTotalIntraCreditAsset(userAddr); if (depositCredit == 0) { return 0; } if (depositCredit > borrowCredit) { return depositCredit.sub(borrowCredit).unifiedDiv(_getTokenHandlerPrice(handlerID)); } else { return 0; } } function getFeePercent(uint256 handlerID) external view returns (uint256) { return handlerFlashloan[handlerID].flashFeeRate; } /** * @dev Get the token price for the handler * @param handlerID The handler id * @return The token price of the handler */ function _getTokenHandlerPrice(uint256 handlerID) internal view returns (uint256) { return (oracleProxy.getTokenPrice(handlerID)); } /** * @dev Get the address of reward token * @return The address of reward token */ function getRewardErc20() public view returns (address) { return address(rewardErc20Instance); } /** * @dev Get the reward parameters * @return (uint256,uint256,uint256) rewardPerBlock, rewardDecrement, rewardTotalAmount */ function getGlobalRewardInfo() external view returns (uint256, uint256, uint256) { IManagerDataStorage _dataStorage = dataStorageInstance; return (_dataStorage.getGlobalRewardPerBlock(), _dataStorage.getGlobalRewardDecrement(), _dataStorage.getGlobalRewardTotalAmount()); } function setObserverAddr(address observerAddr) onlyOwner external returns (bool) { Observer = IObserver( observerAddr ); } /** * @dev fallback function where handler can receive native coin */ fallback () external payable { } }
Set the address of BiFi reward token contract erc20Addr The address of BiFi reward token contract return result the setter call in contextSetter contract/
function setRewardErc20(address erc20Addr) onlyOwner public returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setRewardErc20.selector, erc20Addr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); }
1,718,511
pragma solidity ^0.4.18; /** * @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; } } /** * @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; } } //Announcement of an interface for recipient approving interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData)public; } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ShareXERC20 is Ownable{ //===================public variables definition start================== string public name; //Name of your Token string public symbol; //Symbol of your Token uint8 public decimals; //Decimals of your Token uint256 public totalSupply; //Maximum amount of Token supplies //define dictionaries of balance mapping (address => uint256) public balanceOf; //Announce the dictionary of account's balance mapping (address => mapping (address => uint256)) public allowance; //Announce the dictionary of account's available balance //===================public variables definition end================== //===================events definition start================== event Transfer(address indexed from, address indexed to, uint256 value); //Event on blockchain which notify client //===================events definition end================== //===================Contract Initialization Sequence Definition start=================== function ShareXERC20 () public { decimals=8; //Assignment of Token's decimals totalSupply = 1000000000 * 10 ** uint256(decimals); //Assignment of Token's total supply with decimals balanceOf[owner] = totalSupply; //Assignment of Token's creator initial tokens name = "ShareX"; //Set the name of Token symbol = "SEXC"; //Set the symbol of Token } //===================Contract Initialization Sequence definition end=================== //===================Contract behavior & funtions definition start=================== /* * Funtion: Transfer funtions * Type:Internal * Parameters: @_from: address of sender's account @_to: address of recipient's account @_value:transaction amount */ function _transfer(address _from, address _to, uint _value) internal { //Fault-tolerant processing require(_to != 0x0); // require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); //Execute transaction uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); //Verify transaction assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /* * Funtion: Transfer tokens * Type:Public * Parameters: @_to: address of recipient's account @_value:transaction amount */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /* * Funtion: Transfer tokens from other address * Type:Public * Parameters: @_from: address of sender's account @_to: address of recipient's account @_value:transaction amount */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); //Allowance verification allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /* * Funtion: Approve usable amount for an account * Type:Public * Parameters: @_spender: address of spender's account @_value: approve amount */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /* * Funtion: Approve usable amount for other address and then notify the contract * Type:Public * Parameters: @_spender: address of other account @_value: approve amount @_extraData:additional 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; } } /* * Funtion: Transfer owner's authority and account balance * Type:Public and onlyOwner * Parameters: @newOwner: address of newOwner */ function transferOwnershipWithBalance(address newOwner) onlyOwner public{ if (newOwner != address(0)) { _transfer(owner,newOwner,balanceOf[owner]); owner = newOwner; } } //===================Contract behavior & funtions definition end=================== } contract ShareXTokenVault is Ownable { using SafeMath for uint256; //Wallet Addresses for allocation address public teamReserveWallet = 0x78e27c0347fa3afcc31e160b0fbc6f90186fd2b6; address public firstReserveWallet = 0xef2ab7226c1a3d274caad2dec6d79a4db5d5799e; address public CEO = 0x2Fc7607CE5f6c36979CC63aFcDA6D62Df656e4aE; address public COO = 0x08465f80A28E095DEE4BE0692AC1bA1A2E3EEeE9; address public CTO = 0xB22E5Ac6C3a9427C48295806a34f7a3C0FD21443; address public CMO = 0xf34C06cd907AD036b75cee40755b6937176f24c3; address public CPO = 0xa33da3654d5fdaBC4Dd49fB4e6c81C58D28aA74a; address public CEO_TEAM =0xc0e3294E567e965C3Ff3687015fCf88eD3CCC9EA; address public AWD = 0xc0e3294E567e965C3Ff3687015fCf88eD3CCC9EA; uint256 public CEO_SHARE = 45; uint256 public COO_SHARE = 12; uint256 public CTO_SHARE = 9; uint256 public CMO_SHARE = 9; uint256 public CPO_SHARE = 9; uint256 public CEO_TEAM_SHARE =6; uint256 public AWD_SHARE =10; uint256 public DIV = 100; //Token Allocations uint256 public teamReserveAllocation = 16 * (10 ** 7) * (10 ** 8); uint256 public firstReserveAllocation = 4 * (10 ** 7) * (10 ** 8); //Total Token Allocations uint256 public totalAllocation = 2 * (10 ** 8) * (10 ** 8); uint256 public teamVestingStages = 8; //first unlocked Token uint256 public firstTime =1531584000; //2018-07-15 00:00:00 //teamTimeLock uint256 public teamTimeLock = 2 * 365 days; //team unlocked over uint256 public secondTime =firstTime.add(teamTimeLock); /** Reserve allocations */ mapping(address => uint256) public allocations; /** When timeLocks are over (UNIX Timestamp) */ mapping(address => uint256) public timeLocks; /** How many tokens each reserve wallet has claimed */ mapping(address => uint256) public claimed; /** When this vault was locked (UNIX Timestamp)*/ uint256 public lockedAt = 0; ShareXERC20 public token; /** Allocated reserve tokens */ event Allocated(address wallet, uint256 value); /** Distributed reserved tokens */ event Distributed(address wallet, uint256 value); /** Tokens have been locked */ event Locked(uint256 lockTime); //Any of the two reserve wallets modifier onlyReserveWallets { require(allocations[msg.sender] > 0); _; } //Only ShareX team reserve wallet modifier onlyTeamReserve { require(msg.sender == teamReserveWallet); require(allocations[msg.sender] > 0); _; } //Only first and second token reserve wallets modifier onlyTokenReserve { require(msg.sender == firstReserveWallet ); require(allocations[msg.sender] > 0); _; } //Has not been locked yet modifier notLocked { require(lockedAt == 0); _; } modifier locked { require(lockedAt > 0); _; } //Token allocations have not been set modifier notAllocated { require(allocations[teamReserveWallet] == 0); require(allocations[firstReserveWallet] == 0); _; } function ShareXTokenVault(ERC20 _token) public { owner = msg.sender; token = ShareXERC20(_token); } function allocate() public notLocked notAllocated onlyOwner { //Makes sure Token Contract has the exact number of tokens require(token.balanceOf(address(this)) == totalAllocation); allocations[teamReserveWallet] = teamReserveAllocation; allocations[firstReserveWallet] = firstReserveAllocation; Allocated(teamReserveWallet, teamReserveAllocation); Allocated(firstReserveWallet, firstReserveAllocation); lock(); } //Lock the vault for the two wallets function lock() internal notLocked onlyOwner { lockedAt = block.timestamp; // timeLocks[teamReserveWallet] = lockedAt.add(teamTimeLock); timeLocks[teamReserveWallet] = secondTime; // timeLocks[firstReserveWallet] = lockedAt.add(firstReserveTimeLock); timeLocks[firstReserveWallet] = firstTime; Locked(lockedAt); } //In the case locking failed, then allow the owner to reclaim the tokens on the contract. //Recover Tokens in case incorrect amount was sent to contract. function recoverFailedLock() external notLocked notAllocated onlyOwner { // Transfer all tokens on this contract back to the owner require(token.transfer(owner, token.balanceOf(address(this)))); } // Total number of tokens currently in the vault function getTotalBalance() public view returns (uint256 tokensCurrentlyInVault) { return token.balanceOf(address(this)); } // Number of tokens that are still locked function getLockedBalance() public view onlyReserveWallets returns (uint256 tokensLocked) { return allocations[msg.sender].sub(claimed[msg.sender]); } //Claim tokens for first reserve wallets function claimTokenReserve() onlyTokenReserve locked public { address reserveWallet = msg.sender; // Can't claim before Lock ends require(block.timestamp > timeLocks[reserveWallet]); // Must Only claim once require(claimed[reserveWallet] == 0); uint256 amount = allocations[reserveWallet]; claimed[reserveWallet] = amount; require(token.transfer(CEO,amount.mul(CEO_SHARE).div(DIV))); require(token.transfer(COO,amount.mul(COO_SHARE).div(DIV))); require(token.transfer(CTO,amount.mul(CTO_SHARE).div(DIV))); require(token.transfer(CMO,amount.mul(CMO_SHARE).div(DIV))); require(token.transfer(CPO,amount.mul(CPO_SHARE).div(DIV))); require(token.transfer(CEO_TEAM,amount.mul(CEO_TEAM_SHARE).div(DIV))); require(token.transfer(AWD,amount.mul(AWD_SHARE).div(DIV))); Distributed(CEO, amount.mul(CEO_SHARE).div(DIV)); Distributed(COO, amount.mul(COO_SHARE).div(DIV)); Distributed(CTO, amount.mul(CTO_SHARE).div(DIV)); Distributed(CMO, amount.mul(CMO_SHARE).div(DIV)); Distributed(CPO, amount.mul(CPO_SHARE).div(DIV)); Distributed(CEO_TEAM, amount.mul(CEO_TEAM_SHARE).div(DIV)); Distributed(AWD, amount.mul(AWD_SHARE).div(DIV)); } //Claim tokens for ShareX team reserve wallet function claimTeamReserve() onlyTeamReserve locked public { uint256 vestingStage = teamVestingStage(); //Amount of tokens the team should have at this vesting stage uint256 totalUnlocked = vestingStage.mul(allocations[teamReserveWallet]).div(teamVestingStages); require(totalUnlocked <= allocations[teamReserveWallet]); //Previously claimed tokens must be less than what is unlocked require(claimed[teamReserveWallet] < totalUnlocked); uint256 payment = totalUnlocked.sub(claimed[teamReserveWallet]); claimed[teamReserveWallet] = totalUnlocked; // require(token.transfer(teamReserveWallet, payment)); require(token.transfer(AWD,payment)); Distributed(AWD, payment); } //Current Vesting stage for ShareX team function teamVestingStage() public view onlyTeamReserve returns(uint256){ // Every 3 months uint256 vestingMonths = teamTimeLock.div(teamVestingStages); // uint256 stage = (block.timestamp.sub(lockedAt)).div(vestingMonths); uint256 stage = (block.timestamp).sub(firstTime).div(vestingMonths); //Ensures team vesting stage doesn't go past teamVestingStages if(stage > teamVestingStages){ stage = teamVestingStages; } return stage; } // Checks if msg.sender can collect tokens function canCollect() public view onlyReserveWallets returns(bool) { return block.timestamp > timeLocks[msg.sender] && claimed[msg.sender] == 0; } }
Lock the vault for the two wallets timeLocks[teamReserveWallet] = lockedAt.add(teamTimeLock); timeLocks[firstReserveWallet] = lockedAt.add(firstReserveTimeLock);
function lock() internal notLocked onlyOwner { lockedAt = block.timestamp; timeLocks[teamReserveWallet] = secondTime; timeLocks[firstReserveWallet] = firstTime; Locked(lockedAt); }
12,860,350
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; interface InvestmentRankingInterface { function createInvestmentManagerIfNotExists (address investmentManagerAddress, address proxyContractAddress) external; function saveInvestment(address investmentAddress, address investmentManagerAddress) external; function isInvestmentAllowed(address investmentManagerAddress, uint256 investmentCost) external returns(bool); function getInvestmentManagerRanking(address investmentManagerAddress) external returns (uint8); function getProxyContractsOfAddress (address investmentManagerAddress) external returns (address[] memory); } contract InvestmentFactory { address public _manager; //creator of the investment factory event InvestmentCreated (address indexed managerAddress, address indexed investmentContractAddress); Investment[] public deployedInvestments; InvestmentRankingInterface public investmentRankingContract; address public _investmentRankingContractAddress; modifier onlyManager() { require(msg.sender == _manager, "only owner"); _; } constructor(address investmentRankingContractAddress) public{ investmentRankingContract = InvestmentRankingInterface(investmentRankingContractAddress); _investmentRankingContractAddress = investmentRankingContractAddress; _manager = msg.sender; } function updateInvestmentRankingContractAddress (address contractAddress) external onlyManager() { investmentRankingContract = InvestmentRankingInterface(contractAddress); _investmentRankingContractAddress = contractAddress; } function createInvestment(address manager, uint256 totalInvestmentCost, string memory investmentTitle, string memory investmentRationale, uint256 createdAt, uint256 investmentDeadlineTimestamp, uint256 commissionFee) public{ //create this investment manager if they do not exist //msg.sender corresponds to the proxy contract using uPort investmentRankingContract.createInvestmentManagerIfNotExists(manager, msg.sender); //check that investment manager is allowed to create this investment based on their ranking require(investmentRankingContract.isInvestmentAllowed(manager, totalInvestmentCost) == true, "investment cost exceeds ranking cap"); //get manager's ranking uint8 managerRanking = investmentRankingContract.getInvestmentManagerRanking(manager); Investment newInvestment = new Investment( manager, totalInvestmentCost, investmentTitle, investmentRationale, createdAt, investmentDeadlineTimestamp, commissionFee, managerRanking, _investmentRankingContractAddress ); //store investment deployedInvestments.push(newInvestment); //emit event emit InvestmentCreated(manager, address(newInvestment)); //update investmentManagers details in ranking contract investmentRankingContract.saveInvestment(address(newInvestment), manager); } function contractBalance() public view returns(uint256){ return address(this).balance; } function getBlockTimestamp() public view returns (uint){ return block.timestamp; } function getDeployedInvestments() public view returns (Investment[] memory){ return deployedInvestments; } } contract Investment { using SafeMath for uint256; address public _manager; //creator of the investment uint8 public _managerRanking; //investment ranking of the creator of the investment mapping(address => uint256) public _investments;//mapping of all the addresses that have invested and their investment amounts mapping(address => uint256) public _percentageShares; //mapping of all the percentages that investors are entitled to based on their investment contribution uint256 public _totalInvestmentCost; //investment goal to be funded uint256 public _totalInvestmentContributed; //total investment amount contributed string public _investmentTitle; //investment title string public _investmentRationale; //investment rationale string public _openLawContract = ""; //OpenLaw contract bool private _openLawContractSignedViaTransaction = false; //indicates that manager has signed the openlaw contract using metamask/uport (marked private so that only internal calls can alter value) uint256 public _commissionFee; //fee charged by investment creator uint8 public _investorCount; //number of investors uint public _createdAt; //unix timestamp indicating Investment creation uint public _investmentDeadlineTimestamp; //deadline for funding this investment uint256 public _precision = 10 ** 8; enum InvestmentStatus {INPROGRESS, COMPLETED, FAILED} //status of investment InvestmentStatus public _investmentStatus; //current status of investment //keeps track of whether manager has already withdrawn the investments (once investment is in COMPLETED InvestmentStatus state) enum InvestmentTransferStatus {INCOMPLETE, COMPLETED} InvestmentTransferStatus public _investmentTransferStatus; struct Payment { uint256 timestamp; uint256 amount; address payerAddress; } mapping(address => Payment[]) public _paymentsFromAddress; //mapping of all payments made to this contract Payment[] public _allPayments; //all payments made to this investment contract (regardless of sender) uint256 public _totalPayments; //sum of all payments made to this investment contract (regardless of sender) mapping (address => uint256) _paymentIndexWithdrawnByAddress; //mapping containing the payments index withdrawn by a particular investor InvestmentRankingInterface public _investmentRankingContract; //instance of investment ranking contract constructor(address manager, uint256 totalInvestmentCost, string memory investmentTitle, string memory investmentRationale, uint256 createdAt, uint256 investmentDeadlineTimestamp, uint256 commissionFee, uint8 managerRanking, address investmentRankingContractAddress) public payable{ _manager = manager; _totalInvestmentCost = totalInvestmentCost; _investmentTitle = investmentTitle; _investmentRationale = investmentRationale; _createdAt = createdAt; _investmentDeadlineTimestamp = investmentDeadlineTimestamp; _investmentStatus = InvestmentStatus.INPROGRESS; _investmentTransferStatus = InvestmentTransferStatus.INCOMPLETE; _commissionFee = commissionFee; _managerRanking = managerRanking; _investmentRankingContract = InvestmentRankingInterface(investmentRankingContractAddress); } modifier onlyManager() { require(msg.sender == _manager, "only owner"); _; } function invest() external payable { //check the status of the contract, investments are only allowed into investments which are still in progress checkContractStatus(); if (_investmentStatus == InvestmentStatus.FAILED || _investmentStatus == InvestmentStatus.COMPLETED){ msg.sender.transfer(msg.value); return; } //increment the number of investors, only if its a new investor if (_investments[msg.sender] == 0) { _investorCount++; } //ensure that investors cannot overinvest (precaution) uint256 currentInvestmentContribution = msg.value; uint256 totalInvestmentWithCurrentContribution = _totalInvestmentContributed + currentInvestmentContribution; if (totalInvestmentWithCurrentContribution > _totalInvestmentCost) { uint256 refund = totalInvestmentWithCurrentContribution - _totalInvestmentCost; msg.sender.transfer(refund); currentInvestmentContribution = currentInvestmentContribution - refund; } //record the investors investment _investments[msg.sender] = _investments[msg.sender] + currentInvestmentContribution; //calculate percentage share calculatePercentageShare(_investments[msg.sender]); //update total investment made _totalInvestmentContributed += currentInvestmentContribution; //mark investment as completed if totalInvestmentCost has been contributed if(_totalInvestmentContributed >= _totalInvestmentCost){ _investmentStatus = InvestmentStatus.COMPLETED; } } function hashCompareWithLengthCheck(string memory a, string memory b) internal pure returns (bool) { if(bytes(a).length != bytes(b).length) { return false; } else { return keccak256(bytes(a)) == keccak256(bytes(b)); } } function getOpenLawContractSignedViaTransaction() public view returns(bool) { return _openLawContractSignedViaTransaction; } function signOpenLawContract(string memory openLawContract) public { //check that contract hasn't already been signed, security against changing agreement require(_openLawContractSignedViaTransaction == false, "open law contract already signed"); //assert that contract being signed is the exact contract assigned to this contract at creation time // require(hashCompareWithLengthCheck(_openLawContractHash, openLawContractHash), "incorrect openlaw contract being signed"); //get manager's proxy contracts address[] memory proxyContracts = _investmentRankingContract.getProxyContractsOfAddress(_manager); //there should not be a significant amount of proxy contracts (if this changes, then consider a mapping rather) bool isProxyContract = false; for(uint i = 0; i < proxyContracts.length; i++){ if (proxyContracts[i] == msg.sender){ isProxyContract = true; } } require(isProxyContract, "error: must be proxy contract"); //set contract signed _openLawContract = openLawContract; _openLawContractSignedViaTransaction = true; } function transferInvestmentContributions() external { //check that the manager has signed an openlaw contract require(_openLawContractSignedViaTransaction, "openlaw contract must be signed before releasing funds"); //check that investment is complete and that transfer has not already been done before allowing manager to withdraw funds checkContractStatus(); if (_investmentStatus != InvestmentStatus.COMPLETED || _investmentTransferStatus == InvestmentTransferStatus.COMPLETED){ return; } //get manager's proxy contracts address[] memory proxyContracts = _investmentRankingContract.getProxyContractsOfAddress(_manager); //there should not be a significant amount of proxy contracts (if this changes, then consider a mapping rather) bool isProxyContract = false; for(uint i = 0; i < proxyContracts.length; i++){ if (proxyContracts[i] == msg.sender){ isProxyContract = true; } } require(isProxyContract, "error: must be proxy contract"); //transfer investment contributions to manager msg.sender.transfer(_totalInvestmentCost); //set InvestmentTransferStatus to COMPLETED _investmentTransferStatus = InvestmentTransferStatus.COMPLETED; } function pay() external payable { //check the status of the contract, payments are only allowed if invesment is completely funded (COMPLETED) checkContractStatus(); if (_investmentStatus != InvestmentStatus.COMPLETED){ msg.sender.transfer(msg.value); return; } //create payment record Payment memory payment = Payment(block.timestamp, msg.value, msg.sender); _paymentsFromAddress[msg.sender].push(payment); _allPayments.push(payment); _totalPayments = _totalPayments.add(msg.value); } function getPaymentRecords(address payerAddress) public view returns (Payment[] memory) { return _paymentsFromAddress[payerAddress]; } function getAllPaymentRecords() public view returns (Payment[] memory){ return _allPayments; } function calculatePercentageShare(uint256 contribution) internal { uint numerator = contribution.mul(_precision); uint temp = numerator.div(_totalInvestmentCost).add(5); // proper rounding up _percentageShares[msg.sender] = temp.div(10); } function calculatePercentage(uint percentage) internal view returns (uint256) { return percentage.mul(_precision).div(10 ** 4); } function withdrawPayments () external { //ensure that caller is actually an investor if (_investments[msg.sender] == 0){ return; } //get contributer's percentage share uint256 percentageShare = _percentageShares[msg.sender]; //get payment index uint256 paymentIndex = _paymentIndexWithdrawnByAddress[msg.sender]; //loop through payments not yet withdrawn and calculate amount owed to investor (after fee's) uint256 numberOfPayments = _allPayments.length; //assert that there are payments to withdraw if (paymentIndex >= numberOfPayments){ return; } uint totalPaymentShare = 0; for(uint i = paymentIndex; i < numberOfPayments; i++){ //calculate percentage uint paymentAmount = _allPayments[i].amount; //manager fee 10% => 10 000 00 uint oneHundredPercent = calculatePercentage(100); uint managerFee = calculatePercentage(_commissionFee); uint feePercentage = oneHundredPercent.sub(managerFee); uint baseAmountSubtractingFees = paymentAmount.mul(feePercentage).div(10 ** 7); uint paymentShare = baseAmountSubtractingFees.mul(percentageShare).div(10 ** 7); totalPaymentShare += paymentShare.mul(10 ** 1); paymentIndex++; } //update payments that have been withdrawn for this address _paymentIndexWithdrawnByAddress[msg.sender] = paymentIndex; //transfer money msg.sender.transfer(totalPaymentShare); } function withdrawPaymentsAsManager () external onlyManager(){ //get payment index uint256 paymentIndex = _paymentIndexWithdrawnByAddress[msg.sender]; //loop through payments not yet withdrawn and calculate amount owed to investor (after fee's) uint256 numberOfPayments = _allPayments.length; //assert that there are payments to withdraw if (paymentIndex >= numberOfPayments){ return; } uint totalPaymentShare = 0; for(uint i = paymentIndex; i < numberOfPayments; i++){ //calculate percentage uint paymentAmount = _allPayments[i].amount; uint managerFee = calculatePercentage(_commissionFee); uint paymentShare = paymentAmount.mul(managerFee).div(10 ** 7); totalPaymentShare += paymentShare.mul(10 ** 1); paymentIndex++; } //update payments that have been withdrawn for this address _paymentIndexWithdrawnByAddress[msg.sender] = paymentIndex; //transfer money msg.sender.transfer(totalPaymentShare); } //returns the investment contribution of an address function getInvestmentContribution (address contributerAddress) public view returns (uint256){ return _investments[contributerAddress]; } //returns the percentage share of this investment associated with the calling address function getPercentageShare (address contributerAddress) public view returns (uint256){ return _percentageShares[contributerAddress]; } function getBlockTimestamp() public view returns (uint){ return block.timestamp; } function getInvestmentContributionSummary() public view returns (uint256, uint256) { uint256 investmentContribution = _investments[msg.sender]; uint256 investmentPercentageShare = _percentageShares[msg.sender]; return ( investmentContribution, investmentPercentageShare ); } function checkContractStatus() public { if (_investmentStatus != InvestmentStatus.COMPLETED && block.timestamp > _investmentDeadlineTimestamp) { _investmentStatus = InvestmentStatus.FAILED; } } function withdrawInvestment() external { //ensure that caller is actually an investor if (_investments[msg.sender] == 0){ return; } checkContractStatus(); if (_investmentStatus == InvestmentStatus.FAILED){ //transfer money back to investor msg.sender.transfer(_investments[msg.sender]); //reset investment contribution _investments[msg.sender] = 0; } } function getInvestmentSummary() public view returns (address, uint256, string memory, string memory, uint256, uint256, InvestmentStatus, uint256, uint256, uint8, InvestmentTransferStatus, uint8) { return ( _manager, _totalInvestmentCost, _investmentTitle, _investmentRationale, _createdAt, _investmentDeadlineTimestamp, _investmentStatus, _commissionFee, _totalInvestmentContributed, _investorCount, _investmentTransferStatus, _managerRanking ); } }
create this investment manager if they do not existmsg.sender corresponds to the proxy contract using uPortcheck that investment manager is allowed to create this investment based on their rankingget manager's rankingstore investmentemit eventupdate investmentManagers details in ranking contract
function createInvestment(address manager, uint256 totalInvestmentCost, string memory investmentTitle, string memory investmentRationale, uint256 createdAt, uint256 investmentDeadlineTimestamp, uint256 commissionFee) public{ investmentRankingContract.createInvestmentManagerIfNotExists(manager, msg.sender); require(investmentRankingContract.isInvestmentAllowed(manager, totalInvestmentCost) == true, "investment cost exceeds ranking cap"); uint8 managerRanking = investmentRankingContract.getInvestmentManagerRanking(manager); Investment newInvestment = new Investment( manager, totalInvestmentCost, investmentTitle, investmentRationale, createdAt, investmentDeadlineTimestamp, commissionFee, managerRanking, _investmentRankingContractAddress ); deployedInvestments.push(newInvestment); emit InvestmentCreated(manager, address(newInvestment)); investmentRankingContract.saveInvestment(address(newInvestment), manager); }
7,236,923
// File: @openzeppelin/contracts/utils/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { 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) { 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) { 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) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: contracts/IRegistry.sol /** * @title IRegistry * @dev This contract represents the interface of a registry contract */ interface IRegistry { /** * @dev This event will be emitted every time a new proxy is created * @param proxy representing the address of the proxy created */ event ProxyCreated(address proxy); /** * @dev This event will be emitted every time a new implementation is registered * @param version representing the version name of the registered implementation * @param implementation representing the address of the registered implementation */ event VersionAdded(uint256 version, address implementation); /** * @dev Registers a new version with its implementation address * @param version representing the version name of the new implementation to be registered * @param implementation representing the address of the new implementation to be registered */ function addVersion(uint256 version, address implementation) external; /** * @dev Tells the address of the implementation for a given version * @param version to query the implementation of * @return address of the implementation registered for the given version */ function getVersion(uint256 version) external view returns (address); } // File: contracts/Proxy.sol /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ abstract 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 virtual returns (address); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ fallback() external payable { address _impl = implementation(); require(_impl != address(0),"ERR_IMPLEMENTEION_ZERO"); 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) } } } } // File: contracts/UpgradeabilityStorage.sol /** * @title UpgradeabilityStorage * @dev This contract holds all the necessary state variables to support the upgrade functionality */ contract UpgradeabilityStorage is Proxy { // Versions registry IRegistry public registry; // Address of the current implementation address internal _implementation; /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view override returns (address) { return _implementation; } } // File: contracts/Upgradeable.sol /** * @title Upgradeable * @dev This contract holds all the minimum required functionality for a behavior to be upgradeable. * This means, required state variables for owned upgradeability purpose and simple initialization validation. */ contract Upgradeable is UpgradeabilityStorage { /** * @dev Validates the caller is the versions registry. * THIS FUNCTION SHOULD BE OVERRIDDEN CALLING SUPER */ function initialize() public view { require(msg.sender == address(registry),"ERR_ONLY_REGISTRERY_CAN_CALL"); } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/ERC721.sol /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721 { using Address for address; using Strings for uint256; // Token name string public _name ; // Token symbol string public _symbol ; string internal baseURI; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @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 {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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: contracts/ERC721Enumerable.sol /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } /** * @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 { address public _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @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 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) internal { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/NFTCards.sol //import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; interface IJungleToken{ function mintForPublic(address to,uint mintQuantity, uint256 mintIndex) external returns(bool); function burn(address recipient,uint256 burnQuantity) external returns (bool); } interface NFTProxyInitializeInterface { function initialize( address _admin, uint256 _timestamp ) external; } contract NFTCards is Upgradeable,ERC721Enumerable,NFTProxyInitializeInterface,IERC721Metadata,Ownable{ using SafeMath for uint256; using Address for address; using Strings for uint256; using EnumerableSet for EnumerableSet.UintSet; uint256 public SALE_START_TIMESTAMP; uint256 public MAX_NFT_SUPPLY ; uint256 public NAME_CHANGE_PRICE; uint256 public NFTPrice ; uint256 public REVEAL_TIMESTAMP ; string public PROVENANCE; uint256 public TOKENS_PER_NFT; address public nctAddress; uint256 firstGeneCount ; uint256 internal MINTING_TIMESTAMP; address _walletAddress; address tokenReceiver; // Mapping from token ID to name mapping (uint256 => string) internal _tokenName; // Mapping if certain name string has already been reserved mapping (string => bool) internal _nameReserved; //Mapping to keep track of users that buy nft after reveal time mapping (uint256 => uint256)public afterReveal; //Mapping to keep track of timestamp of token mapping (uint256 => uint256)public tokenTimestamp; //Mapping to keep track of breeding Price mapping(uint256 => uint256)internal _breedCount; //Mapping to keep track of breed Count mapping(uint256 => uint256)internal breedPrice; //Mapping to store the parents of the breeds mapping(uint256 => uint256[2])internal breedParents; //Mapping to specify which tokenId is bred mapping(uint256 => bool)internal isBred; function initialize(address admin, uint256 _revealTimestamp) public override { super.initialize(); SALE_START_TIMESTAMP = _revealTimestamp; MAX_NFT_SUPPLY = 10000; NAME_CHANGE_PRICE = 100 * (10 ** 18); NFTPrice = 0.05 ether; PROVENANCE = ""; TOKENS_PER_NFT = 500 *1e18; firstGeneCount = 10000; MINTING_TIMESTAMP = block.timestamp + 90 days; tokenReceiver=0x0F693B6634A696134AfBF7e968eb8d0D88720157; _setOwner(admin); _name = "JUNGLEVERSE"; _symbol = "JUNGLEVERSE"; } function changeSupplyAmount(uint256 _amt) external onlyOwner{ MAX_NFT_SUPPLY=_amt; } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _default = "default.json"; string memory baseURI = _baseURI(); string memory trailingzeros = ""; if(tokenId < 10) { trailingzeros = "0000"; } else if(tokenId < 100) { trailingzeros = "000"; } else if(tokenId < 1000) { trailingzeros = "00"; } else if(tokenId < 10000) { trailingzeros = "0"; } if( bytes(baseURI).length == 0 ) { return ""; } else if(block.timestamp > tokenTimestamp[tokenId] + 10 minutes ){ return string(abi.encodePacked(baseURI,trailingzeros,tokenId.toString(),".json")); } else{ return string(abi.encodePacked(baseURI, _default)); } } /** * @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 baseURI; } /* *Function to withdraw ether from smart contract account , callable only by admin. */ function withdraw() external onlyOwner { uint balance = address(this).balance; payable(tokenReceiver).transfer(balance); } /* *Function mints NFT upto 20 number of NFTs. */ function mintNFT(uint256 numberOfNfts) public payable { require(block.timestamp > SALE_START_TIMESTAMP,"Sale has not started" ); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY"); require(NFTPrice.mul(numberOfNfts) == msg.value, "Ether value sent is not correct"); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); require(IJungleToken(nctAddress).mintForPublic(msg.sender,TOKENS_PER_NFT,mintIndex),"Error in transfer"); tokenTimestamp[mintIndex] = block.timestamp; if(block.timestamp > REVEAL_TIMESTAMP) { afterReveal[mintIndex] = block.timestamp; } } } /** @dev Mints NFTs to multiple addresses. */ function mintReservedNfts(address[] memory addressList) external onlyOwner{ for(uint i=0;i < addressList.length;i++){ uint mintIndex = totalSupply(); _safeMint(addressList[i], mintIndex); require(IJungleToken(nctAddress).mintForPublic(addressList[i],TOKENS_PER_NFT,mintIndex),"Error in transfer"); tokenTimestamp[mintIndex] = block.timestamp; } } /** @dev Method for changing price, only callable by owner. */ function changePrice(uint256 newPrice) external onlyOwner { require(newPrice> 0,"Price should be greater than zero!"); NFTPrice=newPrice; } /** @dev Method for changing teh name change token address, only callable by owner. */ function setNCTAddress(address _nctAddress) external onlyOwner { nctAddress=_nctAddress; } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[str] = isReserve; } /** * @dev Returns name of the NFT at index. */ function tokenNameByIndex(uint256 index) public view returns (string memory) { return _tokenName[index]; } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[nameString]; } /** @dev Add/Set's provenance. callable only by owner. */ function changeProvenace(string memory _PROVENANCE) external onlyOwner { PROVENANCE=_PROVENANCE; } /** @dev Add/Set's BaseURI. callable only by owner. */ function setBaseURI(string memory _uri) external onlyOwner { baseURI=_uri; } /** @dev Add/Set's reveal timestamp. callable only by owner. */ function changeRevealTimestamp(uint256 _timestamp) external onlyOwner { REVEAL_TIMESTAMP = _timestamp; } /** @dev Add/Set's minting timestamp. callable only by owner. */ function changeMintTimeStamp(uint256 _timestamp) public onlyOwner{ MINTING_TIMESTAMP = _timestamp; } /** @dev Add/Sets name change price. callable only by owner. */ function changeNamePrice(uint256 _price) external onlyOwner{ NAME_CHANGE_PRICE=_price; } /** *Function removes name of NFT */ function removeName(uint256 tokenId)external{ string memory s=tokenNameByIndex(tokenId); require(keccak256(abi.encodePacked((s))) != keccak256(abi.encodePacked((""))),"Can't remove name of unnamed token!"); address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); _tokenName[tokenId] = ""; } event NameChange (uint256 indexed NFTIndex, string newName); /** @dev Change name for given "tokenId". only callable by "tokenId" owner. */ function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; IJungleToken(nctAddress).burn(msg.sender,NAME_CHANGE_PRICE); emit NameChange(tokenId, newName); } function getTokenBreedPrice(uint256 _tokenId) internal returns(uint){ uint breedCount = getBreedCount(_tokenId); if(breedCount == 0){ breedPrice[_tokenId] = 150 ether; } else if(breedCount == 1){ breedPrice[_tokenId] = 300 ether; } else if(breedCount == 2){ breedPrice[_tokenId] = 450 ether; } else if(breedCount == 3){ breedPrice[_tokenId] = 600 ether; } else if(breedCount == 4){ breedPrice[_tokenId] = 750 ether; } else if(breedCount == 5){ breedPrice[_tokenId] = 900 ether; } else if(breedCount == 6){ breedPrice[_tokenId] = 1050 ether; } else{ breedPrice[_tokenId] = 1200 ether; } return breedPrice[_tokenId]; } function getBreedCount(uint256 _tokenId)internal view returns(uint256){ return(_breedCount[_tokenId]); } function breed(uint256 _Parent1, uint256 _Parent2) external returns(bool){ address user = msg.sender; uint256 mintIndex = totalSupply(); require(block.timestamp > MINTING_TIMESTAMP,"ERR_CANNOT_BREED"); uint256 existenceParent1 = getExistanceDaysofNFT(_Parent1); uint256 existenceParent2 = getExistanceDaysofNFT(_Parent2); require(user == ownerOf(_Parent1) && user == ownerOf(_Parent2),"ERR_NOT_AUTHORIZED"); require(existenceParent1 > 21 days && existenceParent2 > 21 days,"ERR_CANNOT_BREED_21"); uint256 _breedPrice1 = getTokenBreedPrice(_Parent1); uint256 _breedPrice2 = getTokenBreedPrice(_Parent2); uint256 _breedCountParent1 = getBreedCount(_Parent1); uint256 _breedCountParent2 = getBreedCount(_Parent2); if(_Parent1 <= firstGeneCount){ require(_breedCountParent1 < 8 ,"ERR_YOU_CAN_ONLY_BREED_8_TIMES"); }else{ require(_breedCountParent1 < 5 ,"ERR_YOU_CAN_ONLY_BREED_5_TIMES"); } if(_Parent2 <= firstGeneCount){ require(_breedCountParent2 < 8 ,"ERR_YOU_CAN_ONLY_BREED_8_TIMES"); }else{ require(_breedCountParent2 < 5 ,"ERR_YOU_CAN_ONLY_BREED_5_TIMES"); } require(IJungleToken(nctAddress).burn(msg.sender,_breedPrice1.add(_breedPrice2)),"ERR_IN_TRANSFER"); _safeMint(user,mintIndex); _breedCount[_Parent1] = _breedCount[_Parent1].add(1); _breedCount[_Parent2] = _breedCount[_Parent2].add(1); breedParents[mintIndex] =[_Parent1,_Parent2]; isBred[mintIndex] = true; return true; } function getExistanceDaysofNFT(uint _tokenId) internal view returns(uint256){ if(!_exists(_tokenId)) return 0; uint256 timestamp = tokenTimestamp[_tokenId]; uint256 Days = ((block.timestamp.sub(timestamp))); return Days; } function getBeedParents(uint256 _tokenId) external view returns(uint256[2] memory){ require(isBred[_tokenId],"The character is not bred"); return breedParents[_tokenId]; } /** @dev Validate token name provided by caller. */ function validateName(string memory str) public pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (i > 0) { if (char >= 0x41 && char <= 0x5A){ return false; } } if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } }
Function mints NFT upto 20 number of NFTs./
function mintNFT(uint256 numberOfNfts) public payable { require(block.timestamp > SALE_START_TIMESTAMP,"Sale has not started" ); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY"); require(NFTPrice.mul(numberOfNfts) == msg.value, "Ether value sent is not correct"); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); require(IJungleToken(nctAddress).mintForPublic(msg.sender,TOKENS_PER_NFT,mintIndex),"Error in transfer"); tokenTimestamp[mintIndex] = block.timestamp; if(block.timestamp > REVEAL_TIMESTAMP) { afterReveal[mintIndex] = block.timestamp; } } }
12,935,538
pragma solidity ^0.4.24; /** * @title ERC20 * @dev ERC20 Contract interface(s) */ contract ERC20 { function balanceOf (address _owner) public constant returns (uint256 balance); function transfer ( address _to, uint256 _value) public returns (bool success); function transferFrom (address _from, address _to, uint256 _value) public returns (bool success); function approve (address _spender, uint256 _value) public returns (bool success); function allowance (address _owner, address _spender) public constant returns (uint256 remaining); function totalSupply () public constant returns (uint); event Transfer (address indexed _from, address indexed _to, uint _value); event Approval (address indexed _owner, address indexed _spender, uint _value); } /** * @title TokenRecipient */ interface TokenRecipient { /* fundtion definitions */ function receiveApproval (address _from, uint256 _value, address _token, bytes _extraData) external; } /** * @title SafeMath math library * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev 'a + b', Adds two numbers, throws on overflow */ function add (uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require (c >= a); return c; } /** * @dev 'a - b', Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend) */ function sub (uint256 a, uint256 b) internal pure returns (uint256 c) { require (a >= b); c = a - b; return c; } /** * @dev 'a * b', multiplies two numbers, throws on overflow */ function mul (uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require (a == 0 || c / a == b); return c; } /** * @dev 'a / b', Integer division of two numbers, truncating the quotient */ function div (uint256 a, uint256 b) internal pure returns (uint256 c) { require (b > 0); c = a / b; return c; } } /** * @title ERC20Token * @dev Implementation of the ERC20 Token */ contract ERC20Token is ERC20 { using SafeMath for uint256; /* balance of each account */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /** * @dev Creates a ERC20 Contract with its name, symbol, decimals, and total supply of token * @param _name name of token * @param _symbol name of symbol * @param _decimals decimals * @param _initSupply total supply of tokens */ constructor (string _name, string _symbol, uint8 _decimals, uint256 _initSupply) public { name = _name; // set the name for display purpose symbol = _symbol; // set the symbol for display purpose decimals = _decimals; // 18 decimals is the strongly suggested totalSupply = _initSupply * (10 ** uint256 (decimals)); // update total supply with the decimal amount balances[msg.sender] = totalSupply; // give the creator all initial tokens emit Transfer (address(0), msg.sender, totalSupply); } /** * @dev Get the token balance for account `_owner` */ function balanceOf (address _owner) public view returns (uint256 balance) { return balances[_owner]; } /* function to access name, symbol, decimals, total-supply of token. */ function name () public view returns (string _name ) { return name; } function symbol () public view returns (string _symbol ) { return symbol; } function decimals () public view returns (uint8 _decimals) { return decimals; } function totalSupply () public view returns (uint256 _supply ) { return totalSupply; } /** * @dev Internal transfer, only can be called by this contract */ function _transfer (address _from, address _to, uint256 _value) internal { require (_to != 0x0); // prevent transfer to 0x0 address require (balances[_from] >= _value); // check if the sender has enough require (balances[_to ] + _value > balances[_to]);// check for overflows uint256 previous = balances[_from] + balances[_to]; // save this for an assertion in the future balances[_from] = balances[_from].sub (_value); // subtract from the sender balances[_to ] = balances[_to ].add (_value); // add the same to the recipient emit Transfer (_from, _to, _value); /* Asserts are used to use static analysis to find bugs in your code. They should never fail */ assert (balances[_from] + balances[_to] == previous); } /** * @dev Transfer the balance from owner's account to another account "_to" * owner's account must have sufficient balance to transfer * 0 value transfers are allowed * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transfer (address _to, uint256 _value) public returns (bool success) { _transfer (msg.sender, _to, _value); return true; } /** * @dev Send `_value` amount of tokens from `_from` account to `_to` account * The calling account must already have sufficient tokens approved for * spending from the `_from` account * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transferFrom (address _from, address _to, uint256 _value) public returns (bool success) { require (allowed[_from][msg.sender] >= _value); // check allowance allowed [_from][msg.sender] = allowed [_from][msg.sender].sub (_value); _transfer (_from, _to, _value); return true; } /** * @dev Get the amount of tokens approved by the owner that can be transferred * to the spender's account * @param _owner The address owner * @param _spender The address authorized to spend * @return The amount of tokens remained for the approved by the owner that can * be transferred */ function allowance (address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } /** * @dev Set allowance for other address * Allow `_spender` to withdraw from your account, multiple times, * up to the `_value` amount. If this function is called again it * overwrites the current allowance with _value. * Token owner can approve for `spender` to transferFrom (...) `tokens` * from the token owner's account * @param _spender The address authorized to spend * @param _value the max amount they can spend * @return true if the operation was successful. */ function approve (address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * @dev Set allowance for other address and notify * Allows `_spender` to spend no more than `_value` tokens in your behalf, * and then ping the contract about it * @param _spender the address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true if the operation was successful. */ function approveAndCall (address _spender, uint256 _value, bytes _extraData) public returns (bool success) { TokenRecipient spender = TokenRecipient (_spender); if (approve (_spender, _value)) { spender.receiveApproval (msg.sender, _value, address (this), _extraData); return true; } } } /** * @title Ownable * @notice For user and inter-contract ownership and safe ownership transfers. * @dev The Ownable contract has an owner address, and provides basic * authorization control functions */ contract Ownable { address public owner; /* the address of the contract's owner */ /* logged on change & renounce of owner */ event OwnershipTransferred (address indexed _owner, address indexed _to); event OwnershipRenounced (address indexed _owner); /** * @dev Sets the original 'owner' of the contract to the sender account */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner */ modifier onlyOwner { require (msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a '_to' * @param _to The address to transfer ownership to */ function transferOwnership (address _to) public onlyOwner { require (_to != address(0)); emit OwnershipTransferred (owner, _to); owner = _to; } /** * @dev Allows the current owner to relinquish control of the contract. * This will remove all ownership of the contract, _safePhrase must * be equal to "This contract is to be disowned" * @param _safePhrase Input string to prevent one's mistake */ function renounceOwnership (bytes32 _safePhrase) public onlyOwner { require (_safePhrase == "This contract is to be disowned."); emit OwnershipRenounced (owner); owner = address(0); } } /** * @title ExpERC20Token */ contract ExpERC20Token is ERC20Token, Ownable { /** * @dev Creates a ERC20 Contract with its name, symbol, decimals, and total supply of token * @param _name name of token * @param _symbol name of symbol * @param _decimals decimals * @param _initSupply total supply of tokens */ constructor ( string _name, // name of token string _symbol, // name of symbol uint8 _decimals, // decimals uint256 _initSupply // total supply of tokens ) ERC20Token (_name, _symbol, _decimals, _initSupply) public {} /** * @notice Only the creator can alter the name & symbol * @param _name newer token name to be changed * @param _symbol newer token symbol to be changed */ function changeName (string _name, string _symbol) onlyOwner public { name = _name; symbol = _symbol; } /* ====================================================================== * Burnable functions */ /* This notifies clients about the amount burnt */ event Burn (address indexed from, uint256 value); /** * Internal burn, only can be called by this contract */ function _burn (address _from, uint256 _value) internal { require (balances[_from] >= _value); // check if the sender has enough balances[_from] = balances[_from].sub (_value); // subtract from the sender totalSupply = totalSupply.sub (_value); // updates totalSupply emit Burn (_from, _value); } /** * @dev remove `_value` tokens from the system irreversibly * @param _value the amount of money to burn * @return true if the operation was successful. */ function burn (uint256 _value) public returns (bool success) { _burn (msg.sender, _value); return true; } /** * @dev remove `_value` tokens from the system irreversibly on behalf of `_from` * @param _from the address of the sender * @param _value the amount of money to burn * @return true if the operation was successful. */ function burnFrom (address _from, uint256 _value) public returns (bool success) { require (allowed [_from][msg.sender] >= _value); allowed [_from][msg.sender] = allowed [_from][msg.sender].sub (_value); _burn (_from, _value); return true; } /* ====================================================================== * Mintable functions */ /* event for mint's */ event Mint (address indexed _to, uint256 _amount); event MintFinished (); bool public mintingFinished = false; /* Throws if it is not mintable status */ modifier canMint () { require (!mintingFinished); _; } /* Throws if called by any account other than the owner */ modifier hasMintPermission () { require (msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint (address _to, uint256 _amount) hasMintPermission canMint public returns (bool) { totalSupply = totalSupply.add (_amount); balances[_to] = balances[_to].add (_amount); emit Mint (_to, _amount); emit Transfer (address (0), this, _amount); emit Transfer ( this, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting () onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished (); return true; } /* ====================================================================== * Lockable Token */ bool public tokenLocked = false; /* event for Token's lock or unlock */ event Lock (address indexed _target, bool _locked); mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds (address target, bool frozen); /** * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param _target address to be frozen * @param _freeze either to freeze it or not */ function freezeAccount (address _target, bool _freeze) onlyOwner public { frozenAccount[_target] = _freeze; emit FrozenFunds (_target, _freeze); } /* Throws if it is not locked status */ modifier whenTokenUnlocked () { require (!tokenLocked); _; } /* Internal token-lock, only can be called by this contract */ function _lock (bool _value) internal { require (tokenLocked != _value); tokenLocked = _value; emit Lock (this, tokenLocked); } /** * @dev function to check token is lock or not */ function isTokenLocked () public view returns (bool success) { return tokenLocked; } /** * @dev function to lock/unlock this token * @param _value flag to be locked or not */ function lock (bool _value) onlyOwner public returns (bool) { _lock (_value); return true; } /** * @dev Transfer the balance from owner's account to another account "_to" * owner's account must have sufficient balance to transfer * 0 value transfers are allowed * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transfer (address _to, uint256 _value) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_to ]); // check if recipient is frozen return super.transfer (_to, _value); } /** * @dev Send `_value` amount of tokens from `_from` account to `_to` account * The calling account must already have sufficient tokens approved for * spending from the `_from` account * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transferFrom (address _from, address _to, uint256 _value) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_from]); // check if token-owner is frozen require (!frozenAccount[_to ]); // check if recipient is frozen return super.transferFrom (_from, _to, _value); } /** * @dev Set allowance for other address * Allow `_spender` to withdraw from your account, multiple times, * up to the `_value` amount. If this function is called again it * overwrites the current allowance with _value. * Token owner can approve for `spender` to transferFrom (...) `tokens` * from the token owner's account * @param _spender The address authorized to spend * @param _value the max amount they can spend * @return true if the operation was successful. */ function approve (address _spender, uint256 _value) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_spender ]); // check if token-owner is frozen return super.approve (_spender, _value); } /** * @dev Set allowance for other address and notify * Allows `_spender` to spend no more than `_value` tokens in your behalf, * and then ping the contract about it * @param _spender the address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true if the operation was successful. */ function approveAndCall (address _spender, uint256 _value, bytes _extraData) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_spender ]); // check if token-owner is frozen return super.approveAndCall (_spender, _value, _extraData); } /* ====================================================================== * buy & sell functions */ uint256 public sellPrice; uint256 public buyPrice; /* Internal transfer, only can be called by this contract */ function _transfer (address _from, address _to, uint _value) internal { require (_to != 0x0); // prevent transfer to 0x0 address require (balances[_from] >= _value); // check if the sender has enough require (balances[_to ] + _value >= balances[_to]); // check for overflows require (!frozenAccount[_from]); // check if sender is frozen require (!frozenAccount[_to ]); // check if recipient is frozen balances[_from] = balances[_from].sub (_value); // Subtract from the sender balances[_to ] = balances[_to ].add (_value); // Add the same to the recipient emit Transfer (_from, _to, _value); } /** * @notice allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth * @param _sellPrice Price the users can sell to the contract * @param _buyPrice Price users can buy from the contract */ function setPrices (uint256 _sellPrice, uint256 _buyPrice) onlyOwner public { sellPrice = _sellPrice; buyPrice = _buyPrice ; } /** * @notice Buy tokens from contract by sending ether */ function buy () whenTokenUnlocked payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer (this, msg.sender, amount); // makes the transfers } /** * @notice sell `_amount` tokens to contract * @param _amount amount of tokens to be sold */ function sell (uint256 _amount) whenTokenUnlocked public { require (balances[this] >= _amount * sellPrice); // checks if the contract has enough ether to buy _transfer (msg.sender, this, _amount); // makes the transfers msg.sender.transfer (_amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } }
remove `_value` tokens from the system irreversibly on behalf of `_from` _from the address of the sender _value the amount of money to burn return true if the operation was successful./
function burnFrom (address _from, uint256 _value) public returns (bool success) { require (allowed [_from][msg.sender] >= _value); allowed [_from][msg.sender] = allowed [_from][msg.sender].sub (_value); _burn (_from, _value); return true; } event MintFinished (); bool public mintingFinished = false;
5,376,291
/** *Submitted for verification at Etherscan.io on 2022-03-14 */ /** *Submitted for verification at Etherscan.io on 2022-03-13 */ /** *Submitted for verification at Etherscan.io on 2022-03-03 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/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/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/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // 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: ERC721A.sol // Creators: locationtba.eth, 2pmflow.eth pragma solidity ^0.8.10; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 public immutable maxBatchSize; // 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) private _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; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @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) { 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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } 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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, 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; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * 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`. */ 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. * * 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` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: dask.sol pragma solidity ^0.8.10; contract WorldofGolem is ERC721A, Ownable { using Strings for uint256; // Constant variables // ------------------------------------------------------------------------ uint256 public constant MAX_PRESALE_SUPPLY = 500; // Total amount of WorldofGolem available during presale uint256 public constant MAX_SUPPLY = MAX_PRESALE_SUPPLY + 9500; // Total amount of WorldofGolem uint256 public constant MAX_PER_WALLET_PRESALE = 20; // Max amount of WorldofGolem per wallet during whitelist period uint256 public constant MAX_PER_TX = 20; // Max amount of WorldofGolem per transaction uint256 public constant MAX_PER_WALLET_PUBLIC = 20; // Max amount of WorldofGolem per wallet during public sale uint256 public PRICE = 0.065 ether; // Price of a WorldofGolem uint256 public PRESALE_PRICE = 0.045 ether; // Presale Price of a WorldofGolem // Team addresses - // ------------------------------------------------------------------------ address private constant _a1 = 0x2F6a40D83fa905A6e1b10D02eFba2b187F31d045; address private constant _a2 = 0x54697ba9bCe35deAb1dBcDb8E904Dd8ceA695C3D; address private constant _a3 = 0xf7f1ED914EdF6eAC82736b5d384De6EE19D6f429; address private constant _a4 = 0x415dFa37d8Df33a617676d44E32E8d95AA8F631D; // State variables // ------------------------------------------------------------------------ bool public isPresaleActive = false; bool public isPublicSaleActive = false; // Presale mappings // ------------------------------------------------------------------------ mapping(address => uint256) private _presaleClaimed; mapping(address => uint256) private _publicSaleClaimed; function countClaimedPresale(address addr) external view returns (uint256) { require(addr != address(0), "Null Address"); return _presaleClaimed[addr]; } function countClaimedPublicSale(address addr) external view returns (uint256) { require(addr != address(0), "Null Address"); return _publicSaleClaimed[addr]; } // URI variables // ------------------------------------------------------------------------ string private _contractURI; string private _baseTokenURI; // Merkle Root Hash // ------------------------------------------------------------------------ bytes32 private _merkleRoot; // Events // ------------------------------------------------------------------------ event BaseTokenURIChanged(string baseTokenURI); event ContractURIChanged(string contractURI); // Modifiers // ------------------------------------------------------------------------ modifier onlyPresale() { require(isPresaleActive, "Presale is not active"); _; } modifier onlyPublicSale() { require(isPublicSaleActive, "Public sale is not active"); _; } // Modifier to ensure that the call is coming from an externally owned account, not a contract modifier onlyEOA() { require(tx.origin == msg.sender, "Contract caller must be externally owned account"); _; } modifier onlyValidQuantity(uint256 quantity) { require(quantity > 0, "Quantity cannot be zero"); // require that the transaction quantity > 0 require(quantity <= MAX_PER_TX, "Quantity exceeds max quantity per transaction"); // require that the transaction quantity is less than the max per transaction _; } // Constructor // ------------------------------------------------------------------------ constructor() ERC721A("WorldofGolem", "WOG", 20) {} // Presale functions // ------------------------------------------------------------------------ // check if a merkle proof and the sender is eligible for presale function isEligibleForPresaleMerkle(bytes32[] calldata _merkleProof) external view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); // hash the address of the sender return MerkleProof.verify(_merkleProof, _merkleRoot, leaf); // verify that the sender's address is valid for the merkle proof } function togglePresaleStatus() external onlyOwner { isPresaleActive = !isPresaleActive; } function togglePublicSaleStatus() external onlyOwner { isPublicSaleActive = !isPublicSaleActive; } // Mint functions // ------------------------------------------------------------------------ // Presale Mint using merkle proof function presaleGolem(bytes32[] calldata _merkleProof, uint256 quantity) external payable onlyPresale onlyValidQuantity(quantity) { // require that the buyer is eligible for presale using the merkle proof bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, _merkleRoot, leaf), "Wallet is not eligible for presale"); require(totalSupply() < MAX_PRESALE_SUPPLY, "Golem presale sold out"); require(totalSupply() + quantity <= MAX_PRESALE_SUPPLY, "Quantity exceeds maximum presale supply"); require(_presaleClaimed[msg.sender] < MAX_PER_WALLET_PRESALE, "Wallet has already claimed presale limit"); require(_presaleClaimed[msg.sender] + quantity <= MAX_PER_WALLET_PRESALE, "Quantity exceeds max quantity per wallet during presale"); // require that the buyer has not claimed their presale limit require(PRESALE_PRICE * quantity == msg.value, "Invalid ETH amount provided"); _presaleClaimed[msg.sender] += quantity; _safeMint(msg.sender, quantity); // using ERC721A we can mint multiple tokens using _safeMint } // Public Sale mint function publicSaleGolem(uint256 quantity) external payable onlyPublicSale onlyValidQuantity(quantity) { require(totalSupply() < MAX_SUPPLY, "Golem sold out"); require(totalSupply() + quantity <= MAX_SUPPLY, "Quantity exceeds maximum supply"); require(_publicSaleClaimed[msg.sender] < MAX_PER_WALLET_PUBLIC, "Wallet has already claimed public sale limit"); require(_publicSaleClaimed[msg.sender] + quantity <= MAX_PER_WALLET_PUBLIC, "Quantity exceeds max quantity per wallet during public sale"); require(PRICE * quantity == msg.value, "Invalid ETH amount provided"); _publicSaleClaimed[msg.sender] += quantity; _safeMint(msg.sender, quantity); // using ERC721A we can mint multiple tokens using _safeMint } //Owner mint function giveawayGolem(address to, uint256 quantity) external onlyOwner { require(totalSupply() + quantity <= MAX_SUPPLY, "WOG: Minting would exceed max supply"); require(quantity > 0, "WOG: Must mint at least one token"); _publicSaleClaimed[to] += quantity; _safeMint(to, quantity); } // Contract URI Functions // ------------------------------------------------------------------------ // Set the contract URI - must set to a URL which can return a JSON of metadata for the contract function setContractURI(string calldata URI) external onlyOwner { _contractURI = URI; emit ContractURIChanged(URI); } // Return the contract URI function contractURI() public view returns (string memory) { return _contractURI; } // Base URI Functions // ------------------------------------------------------------------------ // set the base token URI function setBaseTokenURI(string calldata URI) external onlyOwner { _baseTokenURI = URI; emit BaseTokenURIChanged(URI); } // override the _baseURI() method in the ERC721 contract // the tokenURI() method below will call the tokenURI() method in the ERC721A contract, which will need the _baseURI set above function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } function baseTokenURI() public view returns (string memory) { return _baseTokenURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { return super.tokenURI(tokenId); } // allow the owner of the contract to set the Merkle Root function setMerkleRoot(bytes32 rootHash) external onlyOwner { _merkleRoot = rootHash; } // Withdrawal functions -- NEED TO UPDATE WITH INFORMATION FOR WITHDRAWALS // ------------------------------------------------------------------------ function withdrawAll() external onlyOwner { uint _a1amount = address(this).balance * 45/100; uint _a2amount = address(this).balance * 45/100; uint _a3amount = address(this).balance * 5/100; uint _a4amount = address(this).balance * 5/100; require(payable(_a1).send(_a1amount), "Failed to send to a1"); require(payable(_a2).send(_a2amount), "Failed to send to a2"); require(payable(_a3).send(_a3amount), "Failed to send to a3"); require(payable(_a4).send(_a4amount), "Failed to send to a3"); } }
set the base token URI
function setBaseTokenURI(string calldata URI) external onlyOwner { _baseTokenURI = URI; emit BaseTokenURIChanged(URI); }
2,168,841
pragma solidity ^0.4.17; contract LatiumX { string public constant name = "LatiumX"; string public constant symbol = "LATX"; uint8 public constant decimals = 8; uint256 public constant totalSupply = 300000000 * 10 ** uint256(decimals); // owner of this contract address public owner; // balances for each account mapping (address => uint256) public balanceOf; // triggered when tokens are transferred event Transfer(address indexed _from, address indexed _to, uint _value); // constructor function LatiumX() { owner = msg.sender; balanceOf[owner] = totalSupply; } // transfer the balance from sender&#39;s account to another one function transfer(address _to, uint256 _value) { // prevent transfer to 0x0 address require(_to != 0x0); // sender and recipient should be different require(msg.sender != _to); // check if the sender has enough coins require(_value > 0 && balanceOf[msg.sender] >= _value); // check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // subtract coins from sender&#39;s account balanceOf[msg.sender] -= _value; // add coins to recipient&#39;s account balanceOf[_to] += _value; // notify listeners about this transfer Transfer(msg.sender, _to, _value); } } contract LatiumLocker { address private constant _latiumAddress = 0x2f85E502a988AF76f7ee6D83b7db8d6c0A823bf9; LatiumX private constant _latium = LatiumX(_latiumAddress); // total amount of Latium tokens that can be locked with this contract uint256 private _lockLimit = 0; // variables for release tiers and iteration thru them uint32[] private _timestamps = [ 1541034000 // 2018-11-01 01:00:00 UTC ]; uint32[] private _tokensToRelease = [ // without decimals 45000000 ]; mapping (uint32 => uint256) private _releaseTiers; // owner of this contract address public owner; // constructor function LatiumLocker() { owner = msg.sender; // initialize release tiers with pairs: // "UNIX timestamp" => "amount of tokens to release" (with decimals) for (uint8 i = 0; i < _timestamps.length; i++) { _releaseTiers[_timestamps[i]] = _tokensToRelease[i] * 10 ** uint256(_latium.decimals()); _lockLimit += _releaseTiers[_timestamps[i]]; } } // function to get current Latium balance (with decimals) // of this contract function latiumBalance() constant returns (uint256 balance) { return _latium.balanceOf(address(this)); } // function to get total amount of Latium tokens (with decimals) // that can be locked with this contract function lockLimit() constant returns (uint256 limit) { return _lockLimit; } // function to get amount of Latium tokens (with decimals) // that are locked at this moment function lockedTokens() constant returns (uint256 locked) { locked = 0; uint256 unlocked = 0; for (uint8 i = 0; i < _timestamps.length; i++) { if (now >= _timestamps[i]) { unlocked += _releaseTiers[_timestamps[i]]; } else { locked += _releaseTiers[_timestamps[i]]; } } uint256 balance = latiumBalance(); if (unlocked > balance) { locked = 0; } else { balance -= unlocked; if (balance < locked) { locked = balance; } } } // function to get amount of Latium tokens (with decimals) // that can be withdrawn at this moment function canBeWithdrawn() constant returns (uint256 unlockedTokens, uint256 excessTokens) { unlockedTokens = 0; excessTokens = 0; uint256 tiersBalance = 0; for (uint8 i = 0; i < _timestamps.length; i++) { tiersBalance += _releaseTiers[_timestamps[i]]; if (now >= _timestamps[i]) { unlockedTokens += _releaseTiers[_timestamps[i]]; } } uint256 balance = latiumBalance(); if (unlockedTokens > balance) { // actual Latium balance of this contract is smaller // than can be released at this moment unlockedTokens = balance; } else if (balance > tiersBalance) { // if actual Latium balance of this contract is greater // than can be locked, all excess tokens can be withdrawn // at any time excessTokens = (balance - tiersBalance); } } // functions with this modifier can only be executed by the owner modifier onlyOwner() { require(msg.sender == owner); _; } // function to withdraw Latium tokens that are unlocked at this moment function withdraw(uint256 _amount) onlyOwner { var (unlockedTokens, excessTokens) = canBeWithdrawn(); uint256 totalAmount = unlockedTokens + excessTokens; require(totalAmount > 0); if (_amount == 0) { // withdraw all available tokens _amount = totalAmount; } require(totalAmount >= _amount); uint256 unlockedToWithdraw = _amount > unlockedTokens ? unlockedTokens : _amount; if (unlockedToWithdraw > 0) { // update tiers data uint8 i = 0; while (unlockedToWithdraw > 0 && i < _timestamps.length) { if (now >= _timestamps[i]) { uint256 amountToReduce = unlockedToWithdraw > _releaseTiers[_timestamps[i]] ? _releaseTiers[_timestamps[i]] : unlockedToWithdraw; _releaseTiers[_timestamps[i]] -= amountToReduce; unlockedToWithdraw -= amountToReduce; } i++; } } // transfer tokens to owner&#39;s account _latium.transfer(msg.sender, _amount); } }
function to get amount of Latium tokens (with decimals) that can be withdrawn at this moment actual Latium balance of this contract is smaller than can be released at this moment if actual Latium balance of this contract is greater than can be locked, all excess tokens can be withdrawn at any time
function canBeWithdrawn() constant returns (uint256 unlockedTokens, uint256 excessTokens) { unlockedTokens = 0; excessTokens = 0; uint256 tiersBalance = 0; for (uint8 i = 0; i < _timestamps.length; i++) { tiersBalance += _releaseTiers[_timestamps[i]]; if (now >= _timestamps[i]) { unlockedTokens += _releaseTiers[_timestamps[i]]; } } uint256 balance = latiumBalance(); if (unlockedTokens > balance) { unlockedTokens = balance; excessTokens = (balance - tiersBalance); } }
7,963,829
pragma solidity ^0.4.21; /** * @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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = 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; } } /** * @title Team Fund Contract * @dev Lock conditions comply with the VNETToken contract */ contract TeamFund is Ownable { ERC20Basic public vnetToken; string public description; // Description event Donate(address indexed _from, uint256 _amount); /** * @dev Constructor */ constructor(ERC20Basic _token) public { vnetToken = _token; description = "Balance is locked by the VNETToken contract until 2021-6-30 23:59:59 UTC +0"; } /** * @dev Sending eth to this contract will be considered as a donation */ function () public payable { emit Donate(msg.sender, msg.value); } /** * @dev Withdraw VNET Token */ function withdrawVNET(address _to, uint256 _amount) external onlyOwner { assert(vnetToken.transfer(_to, _amount)); } /** * @dev Rescue compatible ERC20Basic Token * * @param _token ERC20Basic The address of the token contract */ function rescueTokens(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); assert(_token.transfer(owner, balance)); } /** * @dev Withdraw Ether */ function withdrawEther() external onlyOwner { owner.transfer(address(this).balance); } }
Sending eth to this contract will be considered as a donation/
function () public payable { emit Donate(msg.sender, msg.value); }
9,885
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address 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: openzeppelin-solidity/contracts/ownership/HasNoEther.sol /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be sent to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } } // File: openzeppelin-solidity/contracts/ownership/rbac/Roles.sol /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } // File: openzeppelin-solidity/contracts/ownership/rbac/RBAC.sol /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * @dev Supports unlimited numbers of roles and addresses. * @dev See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param roleNames the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] roleNames) { // bool hasAnyRole = false; // for (uint8 i = 0; i < roleNames.length; i++) { // if (hasRole(msg.sender, roleNames[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: openzeppelin-solidity/contracts/ownership/Whitelist.sol /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable, RBAC { event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { checkRole(msg.sender, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public { addRole(addr, ROLE_WHITELISTED); emit WhitelistedAddressAdded(addr); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address addr) public view returns (bool) { return hasRole(addr, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { addAddressToWhitelist(addrs[i]); } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public { removeRole(addr, ROLE_WHITELISTED); emit WhitelistedAddressRemoved(addr); } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { removeAddressFromWhitelist(addrs[i]); } } } // File: 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: openzeppelin-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: 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) 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 /** * @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 /** * @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/pixie/PixieToken.sol contract PixieToken is StandardToken, Whitelist, HasNoEther { string public constant name = "Pixie Token"; string public constant symbol = "PXE"; uint8 public constant decimals = 18; uint256 public constant initialSupply = 100000000000 * (10 ** uint256(decimals)); // 100 Billion PXE ^ decimal bool public transfersEnabled = false; address public bridge; event BridgeChange(address to); event TransfersEnabledChange(bool to); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() public Whitelist() { totalSupply_ = initialSupply; balances[msg.sender] = initialSupply; emit Transfer(0x0, msg.sender, initialSupply); // transfer bridge set to msg sender bridge = msg.sender; // owner is automatically whitelisted addAddressToWhitelist(msg.sender); } function transfer(address _to, uint256 _value) public returns (bool) { require( transfersEnabled || whitelist(msg.sender) || _to == bridge, "Unable to transfers locked or address not whitelisted or not sending to the bridge" ); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require( transfersEnabled || whitelist(msg.sender) || _to == bridge, "Unable to transfers locked or address not whitelisted or not sending to the bridge" ); return super.transferFrom(_from, _to, _value); } /** * @dev Allows for setting the bridge address * @dev Must be called by owner * * @param _new the address to set */ function changeBridge(address _new) external onlyOwner { require(_new != address(0), "Invalid address"); bridge = _new; emit BridgeChange(bridge); } /** * @dev Allows for setting transfer on/off - used as hard stop * @dev Must be called by owner * * @param _transfersEnabled the value to set */ function setTransfersEnabled(bool _transfersEnabled) external onlyOwner { transfersEnabled = _transfersEnabled; emit TransfersEnabledChange(transfersEnabled); } }
Allows for setting transfer on/off - used as hard stop Must be called by owner _transfersEnabled the value to set/
function setTransfersEnabled(bool _transfersEnabled) external onlyOwner { transfersEnabled = _transfersEnabled; emit TransfersEnabledChange(transfersEnabled); }
978,892
pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./utils/ReentrancyGuard.sol"; import "./libs/LibUnitConverter.sol"; import "./libs/LibValidator.sol"; import "./libs/MarginalFunctionality.sol"; import "./OrionVault.sol"; /** * @title Exchange * @dev Exchange contract for the Orion Protocol * @author @wafflemakr */ /* Overflow safety: We do not use SafeMath and control overflows by not accepting large ints on input. Balances inside contract are stored as int192. Allowed input amounts are int112 or uint112: it is enough for all practically used tokens: for instance if decimal unit is 1e18, int112 allow to encode up to 2.5e15 decimal units. That way adding/subtracting any amount from balances won't overflow, since minimum number of operations to reach max int is practically infinite: ~1e24. Allowed prices are uint64. Note, that price is represented as price per 1e8 tokens. That means that amount*price always fit uint256, while amount*price/1e8 not only fit int192, but also can be added, subtracted without overflow checks: number of malicion operations to overflow ~1e13. */ contract Exchange is OrionVault, ReentrancyGuard { using LibValidator for LibValidator.Order; using SafeERC20 for IERC20; // Flags for updateOrders // All flags are explicit uint8 constant kSell = 0; uint8 constant kBuy = 1; // if 0 - then sell uint8 constant kCorrectMatcherFeeByOrderAmount = 2; // EVENTS event NewAssetTransaction( address indexed user, address indexed assetAddress, bool isDeposit, uint112 amount, uint64 timestamp ); event NewTrade( address indexed buyer, address indexed seller, address baseAsset, address quoteAsset, uint64 filledPrice, uint192 filledAmount, uint192 amountQuote ); // MAIN FUNCTIONS /** * @dev Since Exchange will work behind the Proxy contract it can not have constructor */ function initialize() public payable initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev set basic Exchange params * @param orionToken - base token address * @param priceOracleAddress - adress of PriceOracle contract * @param allowedMatcher - address which has authorization to match orders */ function setBasicParams(address orionToken, address priceOracleAddress, address allowedMatcher) public onlyOwner { require((orionToken != address(0)) && (priceOracleAddress != address(0)), "E15"); _orionToken = IERC20(orionToken); _oracleAddress = priceOracleAddress; _allowedMatcher = allowedMatcher; } /** * @dev set marginal settings * @param _collateralAssets - list of addresses of assets which may be used as collateral * @param _stakeRisk - risk coefficient for staken orion as uint8 (0=0, 255=1) * @param _liquidationPremium - premium for liquidator as uint8 (0=0, 255=1) * @param _priceOverdue - time after that price became outdated * @param _positionOverdue - time after that liabilities became overdue and may be liquidated */ function updateMarginalSettings(address[] calldata _collateralAssets, uint8 _stakeRisk, uint8 _liquidationPremium, uint64 _priceOverdue, uint64 _positionOverdue) public onlyOwner { collateralAssets = _collateralAssets; stakeRisk = _stakeRisk; liquidationPremium = _liquidationPremium; priceOverdue = _priceOverdue; positionOverdue = _positionOverdue; } /** * @dev set risk coefficients for collateral assets * @param assets - list of assets * @param risks - list of risks as uint8 (0=0, 255=1) */ function updateAssetRisks(address[] calldata assets, uint8[] calldata risks) public onlyOwner { for(uint256 i; i< assets.length; i++) assetRisks[assets[i]] = risks[i]; } /** * @dev Deposit ERC20 tokens to the exchange contract * @dev User needs to approve token contract first * @param amount asset amount to deposit in its base unit */ function depositAsset(address assetAddress, uint112 amount) external { //require(asset.transferFrom(msg.sender, address(this), uint256(amount)), "E6"); IERC20(assetAddress).safeTransferFrom(msg.sender, address(this), uint256(amount)); generalDeposit(assetAddress,amount); } /** * @notice Deposit ETH to the exchange contract * @dev deposit event will be emitted with the amount in decimal format (10^8) * @dev balance will be stored in decimal format too */ function deposit() external payable { generalDeposit(address(0), uint112(msg.value)); } /** * @dev internal implementation of deposits */ function generalDeposit(address assetAddress, uint112 amount) internal { address user = msg.sender; bool wasLiability = assetBalances[user][assetAddress]<0; int112 safeAmountDecimal = LibUnitConverter.baseUnitToDecimal( assetAddress, amount ); assetBalances[user][assetAddress] += safeAmountDecimal; if(amount>0) emit NewAssetTransaction(user, assetAddress, true, uint112(safeAmountDecimal), uint64(block.timestamp)); if(wasLiability) MarginalFunctionality.updateLiability(user, assetAddress, liabilities, uint112(safeAmountDecimal), assetBalances[user][assetAddress]); } /** * @dev Withdrawal of remaining funds from the contract back to the address * @param assetAddress address of the asset to withdraw * @param amount asset amount to withdraw in its base unit */ function withdraw(address assetAddress, uint112 amount) external nonReentrant { int112 safeAmountDecimal = LibUnitConverter.baseUnitToDecimal( assetAddress, amount ); address user = msg.sender; assetBalances[user][assetAddress] -= safeAmountDecimal; require(assetBalances[user][assetAddress]>=0, "E1w1"); //TODO require(checkPosition(user), "E1w2"); //TODO uint256 _amount = uint256(amount); if(assetAddress == address(0)) { (bool success, ) = user.call{value:_amount}(""); require(success, "E6w"); } else { IERC20(assetAddress).safeTransfer(user, _amount); } emit NewAssetTransaction(user, assetAddress, false, uint112(safeAmountDecimal), uint64(block.timestamp)); } /** * @dev Get asset balance for a specific address * @param assetAddress address of the asset to query * @param user user address to query */ function getBalance(address assetAddress, address user) public view returns (int192) { return assetBalances[user][assetAddress]; } /** * @dev Batch query of asset balances for a user * @param assetsAddresses array of addresses of the assets to query * @param user user address to query */ function getBalances(address[] memory assetsAddresses, address user) public view returns (int192[] memory balances) { balances = new int192[](assetsAddresses.length); for (uint256 i; i < assetsAddresses.length; i++) { balances[i] = assetBalances[user][assetsAddresses[i]]; } } /** * @dev Batch query of asset liabilities for a user * @param user user address to query */ function getLiabilities(address user) public view returns (MarginalFunctionality.Liability[] memory liabilitiesArray) { return liabilities[user]; } /** * @dev Return list of assets which can be used for collateral */ function getCollateralAssets() public view returns (address[] memory) { return collateralAssets; } /** * @dev get hash for an order * @dev we use order hash as order id to prevent double matching of the same order */ function getOrderHash(LibValidator.Order memory order) public pure returns (bytes32){ return order.getTypeValueHash(); } /** * @dev get filled amounts for a specific order */ function getFilledAmounts(bytes32 orderHash, LibValidator.Order memory order) public view returns (int192 totalFilled, int192 totalFeesPaid) { totalFilled = int192(filledAmounts[orderHash]); //It is safe to convert here: filledAmounts is result of ui112 additions totalFeesPaid = int192(uint256(order.matcherFee)*uint112(totalFilled)/order.amount); //matcherFee is u64; safe multiplication here } /** * @notice Settle a trade with two orders, filled price and amount * @dev 2 orders are submitted, it is necessary to match them: check conditions in orders for compliance filledPrice, filledAmountbuyOrderHash change balances on the contract respectively with buyer, seller, matcbuyOrderHashher * @param buyOrder structure of buy side orderbuyOrderHash * @param sellOrder structure of sell side order * @param filledPrice price at which the order was settled * @param filledAmount amount settled between orders */ function fillOrders( LibValidator.Order memory buyOrder, LibValidator.Order memory sellOrder, uint64 filledPrice, uint112 filledAmount ) public nonReentrant { // --- VARIABLES --- // // Amount of quote asset uint256 _amountQuote = uint256(filledAmount)*filledPrice/(10**8); require(_amountQuote<2**112-1, "E12G"); uint112 amountQuote = uint112(_amountQuote); // Order Hashes bytes32 buyOrderHash = buyOrder.getTypeValueHash(); bytes32 sellOrderHash = sellOrder.getTypeValueHash(); // --- VALIDATIONS --- // // Validate signatures using eth typed sign V1 require( LibValidator.checkOrdersInfo( buyOrder, sellOrder, msg.sender, filledAmount, filledPrice, block.timestamp, _allowedMatcher ), "E3G" ); // --- UPDATES --- // //updateFilledAmount filledAmounts[buyOrderHash] += filledAmount; //it is safe to add ui112 to each other to get i192 filledAmounts[sellOrderHash] += filledAmount; require(filledAmounts[buyOrderHash] <= buyOrder.amount, "E12B"); require(filledAmounts[sellOrderHash] <= sellOrder.amount, "E12S"); // Update User's balances updateOrderBalance(buyOrder, filledAmount, amountQuote, kBuy | kCorrectMatcherFeeByOrderAmount); updateOrderBalance(sellOrder, filledAmount, amountQuote, kSell | kCorrectMatcherFeeByOrderAmount); require(checkPosition(buyOrder.senderAddress), "Incorrect margin position for buyer"); require(checkPosition(sellOrder.senderAddress), "Incorrect margin position for seller"); emit NewTrade( buyOrder.senderAddress, sellOrder.senderAddress, buyOrder.baseAsset, buyOrder.quoteAsset, filledPrice, filledAmount, amountQuote ); } /** * @dev wrapper for LibValidator methods, may be deleted. */ function validateOrder(LibValidator.Order memory order) public pure returns (bool isValid) { isValid = order.isPersonalSign ? LibValidator.validatePersonal(order) : LibValidator.validateV3(order); } /** * @notice update user balances and send matcher fee * @param flags uint8, see constants for possible flags of order */ function updateOrderBalance( LibValidator.Order memory order, uint112 filledAmount, uint112 amountQuote, uint8 flags ) internal { address user = order.senderAddress; bool isBuyer = ((flags & kBuy) != 0); int192 temp; // this variable will be used for temporary variable storage (optimization purpose) { // Stack too deep bool isCorrectFee = ((flags & kCorrectMatcherFeeByOrderAmount) != 0); if(isCorrectFee) { // matcherFee: u64, filledAmount u128 => matcherFee*filledAmount fit u256 // result matcherFee fit u64 order.matcherFee = uint64(uint256(order.matcherFee)*filledAmount/order.amount); //rewrite in memory only } } if(filledAmount > 0) { if(!isBuyer) (filledAmount, amountQuote) = (amountQuote, filledAmount); (address firstAsset, address secondAsset) = isBuyer? (order.quoteAsset, order.baseAsset): (order.baseAsset, order.quoteAsset); int192 firstBalance = assetBalances[user][firstAsset]; int192 secondBalance = assetBalances[user][secondAsset]; // 'Stack too deep' correction // WAS: // bool firstInLiabilities = firstBalance<0; // bool secondInLiabilities = secondBalance<0; // NOW: // ENDFIX temp = assetBalances[user][firstAsset] - amountQuote; assetBalances[user][firstAsset] = temp; assetBalances[user][secondAsset] += filledAmount; // 'Stack too deep' correction // WAS: // if(!firstInLiabilities && (temp<0)){ // NOW: if(!(firstBalance<0) && (temp<0)){ // ENDFIX setLiability(user, firstAsset, temp); } // 'Stack too deep' correction // WAS: // if(secondInLiabilities) { // NOW: if(secondBalance<0) { // ENDFIX MarginalFunctionality.updateLiability(user, secondAsset, liabilities, filledAmount, assetBalances[user][secondAsset]); } } // User pay for fees bool feeAssetInLiabilities = assetBalances[user][order.matcherFeeAsset]<0; temp = assetBalances[user][order.matcherFeeAsset] - order.matcherFee; assetBalances[user][order.matcherFeeAsset] = temp; if(!feeAssetInLiabilities && (temp<0)) { setLiability(user, order.matcherFeeAsset, temp); } assetBalances[order.matcherAddress][order.matcherFeeAsset] += order.matcherFee; } /** * @notice users can cancel an order * @dev write an orderHash in the contract so that such an order cannot be filled (executed) */ /* Unused for now function cancelOrder(LibValidator.Order memory order) public { require(order.validateV3(), "E2"); require(msg.sender == order.senderAddress, "Not owner"); bytes32 orderHash = order.getTypeValueHash(); require(!isOrderCancelled(orderHash), "E4"); ( int192 totalFilled, //uint totalFeesPaid ) = getFilledAmounts(orderHash); if (totalFilled > 0) orderStatus[orderHash] = Status.PARTIALLY_CANCELLED; else orderStatus[orderHash] = Status.CANCELLED; emit OrderUpdate(orderHash, msg.sender, orderStatus[orderHash]); assert( orderStatus[orderHash] == Status.PARTIALLY_CANCELLED || orderStatus[orderHash] == Status.CANCELLED ); } */ /** * @dev check user marginal position (compare assets and liabilities) * @return isPositive - boolean whether liabilities are covered by collateral or not */ function checkPosition(address user) public view returns (bool) { if(liabilities[user].length == 0) return true; return calcPosition(user).state == MarginalFunctionality.PositionState.POSITIVE; } /** * @dev internal methods which collect all variables used my MarginalFunctionality to one structure * @param user user address to query * @return UsedConstants - MarginalFunctionality.UsedConstants structure */ function getConstants(address user) internal view returns (MarginalFunctionality.UsedConstants memory) { return MarginalFunctionality.UsedConstants(user, _oracleAddress, address(this), address(_orionToken), positionOverdue, priceOverdue, stakeRisk, liquidationPremium); } /** * @dev calc user marginal position (compare assets and liabilities) * @param user user address to query * @return position - MarginalFunctionality.Position structure */ function calcPosition(address user) public view returns (MarginalFunctionality.Position memory) { MarginalFunctionality.UsedConstants memory constants = getConstants(user); return MarginalFunctionality.calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); } /** * @dev method to cover some of overdue broker liabilities and get ORN in exchange same as liquidation or margin call * @param broker - broker which will be liquidated * @param redeemedAsset - asset, liability of which will be covered * @param amount - amount of covered asset */ function partiallyLiquidate(address broker, address redeemedAsset, uint112 amount) public { MarginalFunctionality.UsedConstants memory constants = getConstants(broker); MarginalFunctionality.partiallyLiquidate(collateralAssets, liabilities, assetBalances, assetRisks, constants, redeemedAsset, amount); } /** * @dev method to add liability * @param user - user which created liability * @param asset - liability asset * @param balance - current negative balance */ function setLiability(address user, address asset, int192 balance) internal { liabilities[user].push( MarginalFunctionality.Liability({ asset: asset, timestamp: uint64(block.timestamp), outstandingAmount: uint192(-balance)}) ); } /** * @dev method to update liability forcing removing any liabilities if balance > 0 * @param assetAddress - liability asset */ function forceUpdateLiability(address assetAddress) public { address user = msg.sender; MarginalFunctionality.updateLiability(user, assetAddress, liabilities, 0, assetBalances[user][assetAddress]); } /** * @dev revert on fallback function */ fallback() external { revert("E6"); } /* Error Codes E1: Insufficient Balance, flavor S - stake E2: Invalid Signature, flavor B,S - buyer, seller E3: Invalid Order Info, flavor G - general, M - wrong matcher, M2 unauthorized matcher, As - asset mismatch, AmB/AmS - amount mismatch (buyer,seller), PrB/PrS - price mismatch(buyer,seller), D - direction mismatch, E4: Order expired, flavor B,S - buyer,seller E5: Contract not active, E6: Transfer error E7: Incorrect state prior to liquidation E8: Liquidator doesn't satisfy requirements E9: Data for liquidation handling is outdated E10: Incorrect state after liquidation E11: Amount overflow E12: Incorrect filled amount, flavor G,B,S: general(overflow), buyer order overflow, seller order overflow E14: Authorization error, sfs - seizeFromStake E15: Wrong passed params */ } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./libs/MarginalFunctionality.sol"; // Base contract which contain state variable of the first version of Exchange // deployed on mainnet. Changes of the state variables should be introduced // not in that contract but down the inheritance chain, to allow safe upgrades // More info about safe upgrades here: // https://blog.openzeppelin.com/the-state-of-smart-contract-upgrades/#upgrade-patterns contract ExchangeStorage { //order -> filledAmount mapping(bytes32 => uint192) public filledAmounts; // Get user balance by address and asset address mapping(address => mapping(address => int192)) internal assetBalances; // List of assets with negative balance for each user mapping(address => MarginalFunctionality.Liability[]) public liabilities; // List of assets which can be used as collateral and risk coefficients for them address[] internal collateralAssets; mapping(address => uint8) public assetRisks; // Risk coefficient for locked ORN uint8 public stakeRisk; // Liquidation premium uint8 public liquidationPremium; // Delays after which price and position become outdated uint64 public priceOverdue; uint64 public positionOverdue; // Base orion tokens (can be locked on stake) IERC20 _orionToken; // Address of price oracle contract address _oracleAddress; // Address from which matching of orders is allowed address _allowedMatcher; } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./Exchange.sol"; import "./utils/orionpool/periphery/interfaces/IOrionPoolV2Router02Ext.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract ExchangeWithOrionPool is Exchange { using SafeERC20 for IERC20; address public _orionpoolRouter; mapping (address => bool) orionpoolAllowances; modifier initialized { require(_orionpoolRouter!=address(0), "_orionpoolRouter is not set"); require(address(_orionToken)!=address(0), "_orionToken is not set"); require(_oracleAddress!=address(0), "_oracleAddress is not set"); require(_allowedMatcher!=address(0), "_allowedMatcher is not set"); _; } function _safeIncreaseAllowance(address token) internal { if(token != address(0) && !orionpoolAllowances[token]) { IERC20(token).safeIncreaseAllowance(_orionpoolRouter, 2**256-1); orionpoolAllowances[token] = true; } } /** * @dev set basic Exchange params * @param orionToken - base token address * @param priceOracleAddress - adress of PriceOracle contract * @param allowedMatcher - address which has authorization to match orders * @param orionpoolRouter - OrionPool Router address for changes through orionpool */ function setBasicParams(address orionToken, address priceOracleAddress, address allowedMatcher, address orionpoolRouter) public onlyOwner { _orionToken = IERC20(orionToken); _oracleAddress = priceOracleAddress; _allowedMatcher = allowedMatcher; _orionpoolRouter = orionpoolRouter; } // Important catch-all afunction that should only accept ethereum and don't allow do something with it // We accept ETH there only from out router. // If router sends some ETH to us - it's just swap completed, and we don't need to do smth // with ETH received - amount of ETH will be handled by ........... blah blah receive() external payable { require(msg.sender == _orionpoolRouter, "NPF"); } /** * @notice (partially) settle buy order with OrionPool as counterparty * @dev order and orionpool path are submitted, it is necessary to match them: check conditions in order for compliance filledPrice and filledAmount change tokens via OrionPool check that final price after exchange not worse than specified in order change balances on the contract respectively * @param order structure of buy side orderbuyOrderHash * @param filledAmount amount of purchaseable token * @param path array of assets addresses (each consequent asset pair is change pair) */ // Just to avoid stack too deep error; struct OrderExecutionData { uint64 filledPrice; uint112 amountQuote; uint tx_value; } function fillThroughOrionPool( LibValidator.Order memory order, uint112 filledAmount, uint64 blockchainFee, address[] calldata path ) public nonReentrant initialized { // Amount of quote asset uint256 _amountQuote = uint256(filledAmount)* order.price/(10**8); OrderExecutionData memory exec_data; if(order.buySide==1){ /* NOTE BUY ORDER ************************************************************/ (int112 amountQuoteBaseUnits, int112 filledAmountBaseUnits) = ( LibUnitConverter.decimalToBaseUnit(path[0], _amountQuote), LibUnitConverter.decimalToBaseUnit(path[path.length-1], filledAmount) ); // TODO: check // require(IERC20(order.quoteAsset).balanceOf(address(this)) >= uint(amountQuoteBaseUnits), "NEGT"); LibValidator.checkOrderSingleMatch(order, msg.sender, _allowedMatcher, filledAmount, block.timestamp, path, 1); // Change fee only after order validation if(blockchainFee < order.matcherFee) order.matcherFee = blockchainFee; _safeIncreaseAllowance(order.quoteAsset); if(order.quoteAsset == address(0)) exec_data.tx_value = uint(amountQuoteBaseUnits); try IOrionPoolV2Router02Ext(_orionpoolRouter).swapTokensForExactTokensAutoRoute{value: exec_data.tx_value}( uint(filledAmountBaseUnits), uint(amountQuoteBaseUnits), path, address(this)) // order.expiration/1000 returns(uint[] memory amounts) { exec_data.amountQuote = uint112(LibUnitConverter.baseUnitToDecimal( path[0], amounts[0] )); //require(_amountQuote<2**112-1, "E12G"); //TODO uint256 _filledPrice = exec_data.amountQuote*(10**8)/filledAmount; require(_filledPrice<= order.price, "EX"); //TODO exec_data.filledPrice = uint64(_filledPrice); // since _filledPrice<buyOrder.price it fits uint64 //uint112 amountQuote = uint112(_amountQuote); } catch(bytes memory) { filledAmount = 0; exec_data.filledPrice = order.price; } // Update User's balances updateOrderBalance(order, filledAmount, exec_data.amountQuote, kBuy); require(checkPosition(order.senderAddress), "Incorrect margin position for buyer"); }else{ /* NOTE: SELL ORDER **************************************************************************/ LibValidator.checkOrderSingleMatch(order, msg.sender, _allowedMatcher, filledAmount, block.timestamp, path, 0); // Change fee only after order validation if(blockchainFee < order.matcherFee) order.matcherFee = blockchainFee; (int112 amountQuoteBaseUnits, int112 filledAmountBaseUnits) = ( LibUnitConverter.decimalToBaseUnit(path[0], filledAmount), LibUnitConverter.decimalToBaseUnit(path[path.length-1], _amountQuote) ); _safeIncreaseAllowance(order.baseAsset); if(order.baseAsset == address(0)) exec_data.tx_value = uint(amountQuoteBaseUnits); try IOrionPoolV2Router02Ext(_orionpoolRouter).swapExactTokensForTokensAutoRoute{value: exec_data.tx_value}( uint(amountQuoteBaseUnits), uint(filledAmountBaseUnits), path, address(this)) // order.expiration/1000) returns (uint[] memory amounts) { exec_data.amountQuote = uint112(LibUnitConverter.baseUnitToDecimal( path[path.length-1], amounts[path.length-1] )); //require(_amountQuote<2**112-1, "E12G"); //TODO uint256 _filledPrice = exec_data.amountQuote*(10**8)/filledAmount; require(_filledPrice>= order.price, "EX"); //TODO exec_data.filledPrice = uint64(_filledPrice); // since _filledPrice<buyOrder.price it fits uint64 //uint112 amountQuote = uint112(_amountQuote); } catch(bytes memory) { filledAmount = 0; exec_data.filledPrice = order.price; } // Update User's balances updateOrderBalance(order, filledAmount, exec_data.amountQuote, kSell); require(checkPosition(order.senderAddress), "Incorrect margin position for seller"); } { // STack too deep workaround bytes32 orderHash = LibValidator.getTypeValueHash(order); uint192 total_amount = filledAmounts[orderHash]; // require(filledAmounts[orderHash]==0, "filledAmount already has some value"); // Old way total_amount += filledAmount; //it is safe to add ui112 to each other to get i192 require(total_amount >= filledAmount, "E12B_0"); require(total_amount <= order.amount, "E12B"); filledAmounts[orderHash] = total_amount; } emit NewTrade( order.senderAddress, address(1), //TODO //sellOrder.senderAddress, order.baseAsset, order.quoteAsset, exec_data.filledPrice, filledAmount, exec_data.amountQuote ); } /* BUY LIMIT ORN/USDT path[0] = USDT path[1] = ORN is_exact_spend = false; SELL LIMIT ORN/USDT path[0] = ORN path[1] = USDT is_exact_spend = true; */ event NewSwapOrionPool ( address user, address asset_spend, address asset_receive, int112 amount_spent, int112 amount_received ); function swapThroughOrionPool( uint112 amount_spend, uint112 amount_receive, address[] calldata path, bool is_exact_spend ) public nonReentrant initialized { (int112 amount_spend_base_units, int112 amount_receive_base_units) = ( LibUnitConverter.decimalToBaseUnit(path[0], amount_spend), LibUnitConverter.decimalToBaseUnit(path[path.length-1], amount_receive) ); // Checks require(getBalance(path[0], msg.sender) >= amount_spend, "NEGS1"); _safeIncreaseAllowance(path[0]); uint256 tx_value = path[0] == address(0) ? uint(amount_spend_base_units) : 0; uint[] memory amounts = is_exact_spend ? IOrionPoolV2Router02Ext(_orionpoolRouter).swapExactTokensForTokensAutoRoute {value: tx_value} ( uint(amount_spend_base_units), uint(amount_receive_base_units), path, address(this) ) : IOrionPoolV2Router02Ext(_orionpoolRouter).swapTokensForExactTokensAutoRoute {value: tx_value} ( uint(amount_receive_base_units), uint(amount_spend_base_units), path, address(this) ); // Anyway user gave amounts[0] and received amounts[len-1] int112 amount_actually_spent = LibUnitConverter.baseUnitToDecimal(path[0], amounts[0]); int112 amount_actually_received = LibUnitConverter.baseUnitToDecimal(path[path.length-1], amounts[path.length-1]); int192 balance_in_spent = assetBalances[msg.sender][path[0]]; require(amount_actually_spent >= 0 && balance_in_spent >= amount_actually_spent, "NEGS2_1"); balance_in_spent -= amount_actually_spent; assetBalances[msg.sender][path[0]] = balance_in_spent; require(checkPosition(msg.sender), "NEGS2_2"); address receiving_token = path[path.length - 1]; int192 balance_in_received = assetBalances[msg.sender][receiving_token]; bool is_need_update_liability = (balance_in_received < 0); balance_in_received += amount_actually_received; require(amount_actually_received >= 0 /* && balance_in_received >= amount_actually_received*/ , "NEGS2_3"); assetBalances[msg.sender][receiving_token] = balance_in_received; if(is_need_update_liability) MarginalFunctionality.updateLiability( msg.sender, receiving_token, liabilities, uint112(amount_actually_received), assetBalances[msg.sender][receiving_token] ); // TODO: remove emit NewSwapOrionPool ( msg.sender, path[0], receiving_token, amount_actually_spent, amount_actually_received ); } function increaseAllowance(address token) public { IERC20(token).safeIncreaseAllowance(_orionpoolRouter, 2**256-1); orionpoolAllowances[token] = true; } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./utils/Ownable.sol"; import "./ExchangeStorage.sol"; abstract contract OrionVault is ExchangeStorage, OwnableUpgradeSafe { enum StakePhase{ NOTSTAKED, LOCKED, RELEASING, READYTORELEASE, FROZEN } struct Stake { uint64 amount; // 100m ORN in circulation fits uint64 StakePhase phase; uint64 lastActionTimestamp; } uint64 constant releasingDuration = 3600*24; mapping(address => Stake) private stakingData; /** * @dev Returns Stake with on-fly calculated StakePhase * @dev Note StakePhase may depend on time for some phases. * @param user address */ function getStake(address user) public view returns (Stake memory stake){ stake = stakingData[user]; if(stake.phase == StakePhase.RELEASING && (block.timestamp - stake.lastActionTimestamp) > releasingDuration) { stake.phase = StakePhase.READYTORELEASE; } } /** * @dev Returns stake balance * @dev Note, this balance may be already unlocked * @param user address */ function getStakeBalance(address user) public view returns (uint256) { return getStake(user).amount; } /** * @dev Returns stake phase * @param user address */ function getStakePhase(address user) public view returns (StakePhase) { return getStake(user).phase; } /** * @dev Returns locked or frozen stake balance only * @param user address */ function getLockedStakeBalance(address user) public view returns (uint256) { Stake memory stake = getStake(user); if(stake.phase == StakePhase.LOCKED || stake.phase == StakePhase.FROZEN) return stake.amount; return 0; } /** * @dev Change stake phase to frozen, blocking release * @param user address */ function postponeStakeRelease(address user) external onlyOwner{ Stake storage stake = stakingData[user]; stake.phase = StakePhase.FROZEN; } /** * @dev Change stake phase to READYTORELEASE * @param user address */ function allowStakeRelease(address user) external onlyOwner { Stake storage stake = stakingData[user]; stake.phase = StakePhase.READYTORELEASE; } /** * @dev Request stake unlock for msg.sender * @dev If stake phase is LOCKED, that changes phase to RELEASING * @dev If stake phase is READYTORELEASE, that withdraws stake to balance * @dev Note, both unlock and withdraw is impossible if user has liabilities */ function requestReleaseStake() public { address user = _msgSender(); Stake memory current = getStake(user); require(liabilities[user].length == 0, "Can not release stake: user has liabilities"); Stake storage stake = stakingData[_msgSender()]; if(current.phase == StakePhase.READYTORELEASE) { assetBalances[user][address(_orionToken)] += stake.amount; stake.amount = 0; stake.phase = StakePhase.NOTSTAKED; } else if (current.phase == StakePhase.LOCKED) { stake.phase = StakePhase.RELEASING; stake.lastActionTimestamp = uint64(block.timestamp); } else { revert("Can not release funds from this phase"); } } /** * @dev Lock some orions from exchange balance sheet * @param amount orions in 1e-8 units to stake */ function lockStake(uint64 amount) public { address user = _msgSender(); require(assetBalances[user][address(_orionToken)]>amount, "E1S"); Stake storage stake = stakingData[user]; assetBalances[user][address(_orionToken)] -= amount; stake.amount += amount; if(stake.phase != StakePhase.FROZEN) { stake.phase = StakePhase.LOCKED; //what is frozen should stay frozen } stake.lastActionTimestamp = uint64(block.timestamp); } /** * @dev send some orion from user's stake to receiver balance * @dev This function is used during liquidations, to reimburse liquidator * with orions from stake for decreasing liabilities. * @dev Note, this function is used by MarginalFunctionality library, thus * it can not be made private, but at the same time this function * can only be called by contract itself. That way msg.sender check * is critical. * @param user - user whose stake will be decreased * @param receiver - user which get orions * @param amount - amount of withdrawn tokens */ function seizeFromStake(address user, address receiver, uint64 amount) public { require(msg.sender == address(this), "E14"); Stake storage stake = stakingData[user]; require(stake.amount >= amount, "UX"); //TODO stake.amount -= amount; assetBalances[receiver][address(_orionToken)] += amount; } } pragma solidity 0.7.4; interface OrionVaultInterface { /** * @dev Returns locked or frozen stake balance only * @param user address */ function getLockedStakeBalance(address user) external view returns (uint64); /** * @dev send some orion from user's stake to receiver balance * @dev This function is used during liquidations, to reimburse liquidator * with orions from stake for decreasing liabilities. * @param user - user whose stake will be decreased * @param receiver - user which get orions * @param amount - amount of withdrawn tokens */ function seizeFromStake(address user, address receiver, uint64 amount) external; } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface PriceOracleDataTypes { struct PriceDataOut { uint64 price; uint64 timestamp; } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./PriceOracleDataTypes.sol"; interface PriceOracleInterface is PriceOracleDataTypes { function assetPrices(address) external view returns (PriceDataOut memory); function givePrices(address[] calldata assetAddresses) external view returns (PriceDataOut[] memory); } pragma solidity 0.7.4; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; library LibUnitConverter { using SafeMath for uint; /** @notice convert asset amount from8 decimals (10^8) to its base unit */ function decimalToBaseUnit(address assetAddress, uint amount) public view returns(int112 baseValue){ uint256 result; if(assetAddress == address(0)){ result = amount.mul(1 ether).div(10**8); // 18 decimals } else { ERC20 asset = ERC20(assetAddress); uint decimals = asset.decimals(); result = amount.mul(10**decimals).div(10**8); } require(result < uint256(type(int112).max), "LibUnitConverter: Too big value"); baseValue = int112(result); } /** @notice convert asset amount from its base unit to 8 decimals (10^8) */ function baseUnitToDecimal(address assetAddress, uint amount) public view returns(int112 decimalValue){ uint256 result; if(assetAddress == address(0)){ result = amount.mul(10**8).div(1 ether); } else { ERC20 asset = ERC20(assetAddress); uint decimals = asset.decimals(); result = amount.mul(10**8).div(10**decimals); } require(result < uint256(type(int112).max), "LibUnitConverter: Too big value"); decimalValue = int112(result); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; library LibValidator { using ECDSA for bytes32; string public constant DOMAIN_NAME = "Orion Exchange"; string public constant DOMAIN_VERSION = "1"; uint256 public constant CHAIN_ID = 1; bytes32 public constant DOMAIN_SALT = 0xf2d857f4a3edcb9b78b4d503bfe733db1e3f6cdc2b7971ee739626c97e86a557; bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(string name,string version,uint256 chainId,bytes32 salt)" ) ); bytes32 public constant ORDER_TYPEHASH = keccak256( abi.encodePacked( "Order(address senderAddress,address matcherAddress,address baseAsset,address quoteAsset,address matcherFeeAsset,uint64 amount,uint64 price,uint64 matcherFee,uint64 nonce,uint64 expiration,uint8 buySide)" ) ); bytes32 public constant DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(DOMAIN_NAME)), keccak256(bytes(DOMAIN_VERSION)), CHAIN_ID, DOMAIN_SALT ) ); struct Order { address senderAddress; address matcherAddress; address baseAsset; address quoteAsset; address matcherFeeAsset; uint64 amount; uint64 price; uint64 matcherFee; uint64 nonce; uint64 expiration; uint8 buySide; // buy or sell bool isPersonalSign; bytes signature; } /** * @dev validate order signature */ function validateV3(Order memory order) public pure returns (bool) { bytes32 domainSeparator = DOMAIN_SEPARATOR; bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, getTypeValueHash(order) ) ); return digest.recover(order.signature) == order.senderAddress; } /** * @return hash order */ function getTypeValueHash(Order memory _order) internal pure returns (bytes32) { bytes32 orderTypeHash = ORDER_TYPEHASH; return keccak256( abi.encode( orderTypeHash, _order.senderAddress, _order.matcherAddress, _order.baseAsset, _order.quoteAsset, _order.matcherFeeAsset, _order.amount, _order.price, _order.matcherFee, _order.nonce, _order.expiration, _order.buySide ) ); } /** * @dev basic checks of matching orders against each other */ function checkOrdersInfo( Order memory buyOrder, Order memory sellOrder, address sender, uint256 filledAmount, uint256 filledPrice, uint256 currentTime, address allowedMatcher ) public pure returns (bool success) { buyOrder.isPersonalSign ? require(validatePersonal(buyOrder), "E2BP") : require(validateV3(buyOrder), "E2B"); sellOrder.isPersonalSign ? require(validatePersonal(sellOrder), "E2SP") : require(validateV3(sellOrder), "E2S"); // Same matcher address require( buyOrder.matcherAddress == sender && sellOrder.matcherAddress == sender, "E3M" ); if(allowedMatcher != address(0)) { require(buyOrder.matcherAddress == allowedMatcher, "E3M2"); } // Check matching assets require( buyOrder.baseAsset == sellOrder.baseAsset && buyOrder.quoteAsset == sellOrder.quoteAsset, "E3As" ); // Check order amounts require(filledAmount <= buyOrder.amount, "E3AmB"); require(filledAmount <= sellOrder.amount, "E3AmS"); // Check Price values require(filledPrice <= buyOrder.price, "E3"); require(filledPrice >= sellOrder.price, "E3"); // Check Expiration Time. Convert to seconds first require(buyOrder.expiration/1000 >= currentTime, "E4B"); require(sellOrder.expiration/1000 >= currentTime, "E4S"); require( buyOrder.buySide==1 && sellOrder.buySide==0, "E3D"); success = true; } function getEthSignedOrderHash(Order memory _order) public pure returns (bytes32) { return keccak256( abi.encodePacked( "order", _order.senderAddress, _order.matcherAddress, _order.baseAsset, _order.quoteAsset, _order.matcherFeeAsset, _order.amount, _order.price, _order.matcherFee, _order.nonce, _order.expiration, _order.buySide ) ).toEthSignedMessageHash(); } function validatePersonal(Order memory order) public pure returns (bool) { bytes32 digest = getEthSignedOrderHash(order); return digest.recover(order.signature) == order.senderAddress; } function checkOrderSingleMatch( Order memory buyOrder, address sender, address allowedMatcher, uint112 filledAmount, uint256 currentTime, address[] memory path, uint8 isBuySide ) public pure returns (bool success) { buyOrder.isPersonalSign ? require(validatePersonal(buyOrder), "E2BP") : require(validateV3(buyOrder), "E2B"); require(buyOrder.matcherAddress == sender && buyOrder.matcherAddress == allowedMatcher, "E3M2"); if(buyOrder.buySide==1){ require( buyOrder.baseAsset == path[path.length-1] && buyOrder.quoteAsset == path[0], "E3As" ); }else{ require( buyOrder.quoteAsset == path[path.length-1] && buyOrder.baseAsset == path[0], "E3As" ); } require(filledAmount <= buyOrder.amount, "E3AmB"); require(buyOrder.expiration/1000 >= currentTime, "E4B"); require( buyOrder.buySide==isBuySide, "E3D"); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../PriceOracleInterface.sol"; import "../OrionVaultInterface.sol"; library MarginalFunctionality { // We have the following approach: when liability is created we store // timestamp and size of liability. If the subsequent trade will deepen // this liability or won't fully cover it timestamp will not change. // However once outstandingAmount is covered we check wether balance on // that asset is positive or not. If not, liability still in the place but // time counter is dropped and timestamp set to `now`. struct Liability { address asset; uint64 timestamp; uint192 outstandingAmount; } enum PositionState { POSITIVE, NEGATIVE, // weighted position below 0 OVERDUE, // liability is not returned for too long NOPRICE, // some assets has no price or expired INCORRECT // some of the basic requirements are not met: too many liabilities, no locked stake, etc } struct Position { PositionState state; int256 weightedPosition; // sum of weighted collateral minus liabilities int256 totalPosition; // sum of unweighted (total) collateral minus liabilities int256 totalLiabilities; // total liabilities value } // Constants from Exchange contract used for calculations struct UsedConstants { address user; address _oracleAddress; address _orionVaultContractAddress; address _orionTokenAddress; uint64 positionOverdue; uint64 priceOverdue; uint8 stakeRisk; uint8 liquidationPremium; } /** * @dev method to multiply numbers with uint8 based percent numbers */ function uint8Percent(int192 _a, uint8 b) internal pure returns (int192 c) { int a = int256(_a); int d = 255; c = int192((a>65536) ? (a/d)*b : a*b/d ); } /** * @dev method to calc weighted and absolute collateral value * @notice it only count for assets in collateralAssets list, all other assets will add 0 to position. * @return outdated wether any price is outdated * @return weightedPosition in ORN * @return totalPosition in ORN */ function calcAssets(address[] storage collateralAssets, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants) internal view returns (bool outdated, int192 weightedPosition, int192 totalPosition) { uint256 collateralAssetsLength = collateralAssets.length; for(uint256 i = 0; i < collateralAssetsLength; i++) { address asset = collateralAssets[i]; if(assetBalances[constants.user][asset]<0) continue; // will be calculated in calcLiabilities (uint64 price, uint64 timestamp) = (1e8, 0xfffffff000000000); if(asset != constants._orionTokenAddress) { PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(asset);//TODO givePrices (price, timestamp) = (assetPriceData.price, assetPriceData.timestamp); } // balance: i192, price u64 => balance*price fits i256 // since generally balance <= N*maxInt112 (where N is number operations with it), // assetValue <= N*maxInt112*maxUInt64/1e8. // That is if N<= 2**17 *1e8 = 1.3e13 we can neglect overflows here int192 assetValue = int192(int256(assetBalances[constants.user][asset])*price/1e8); // Overflows logic holds here as well, except that N is the number of // operations for all assets if(assetValue>0) { weightedPosition += uint8Percent(assetValue, assetRisks[asset]); totalPosition += assetValue; // if assetValue == 0 ignore outdated price outdated = outdated || ((timestamp + constants.priceOverdue) < block.timestamp); } } return (outdated, weightedPosition, totalPosition); } /** * @dev method to calc liabilities * @return outdated wether any price is outdated * @return overdue wether any liability is overdue * @return weightedPosition weightedLiability == totalLiability in ORN * @return totalPosition totalLiability in ORN */ function calcLiabilities(mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, UsedConstants memory constants ) internal view returns (bool outdated, bool overdue, int192 weightedPosition, int192 totalPosition) { uint256 liabilitiesLength = liabilities[constants.user].length; for(uint256 i = 0; i < liabilitiesLength; i++) { Liability storage liability = liabilities[constants.user][i]; PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(liability.asset);//TODO givePrices (uint64 price, uint64 timestamp) = (assetPriceData.price, assetPriceData.timestamp); // balance: i192, price u64 => balance*price fits i256 // since generally balance <= N*maxInt112 (where N is number operations with it), // assetValue <= N*maxInt112*maxUInt64/1e8. // That is if N<= 2**17 *1e8 = 1.3e13 we can neglect overflows here int192 liabilityValue = int192( int256(assetBalances[constants.user][liability.asset]) *price/1e8 ); weightedPosition += liabilityValue; //already negative since balance is negative totalPosition += liabilityValue; overdue = overdue || ((liability.timestamp + constants.positionOverdue) < block.timestamp); outdated = outdated || ((timestamp + constants.priceOverdue) < block.timestamp); } return (outdated, overdue, weightedPosition, totalPosition); } /** * @dev method to calc Position * @return result position structure */ function calcPosition( address[] storage collateralAssets, mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants ) public view returns (Position memory result) { (bool outdatedPrice, int192 weightedPosition, int192 totalPosition) = calcAssets(collateralAssets, assetBalances, assetRisks, constants); (bool _outdatedPrice, bool overdue, int192 _weightedPosition, int192 _totalPosition) = calcLiabilities(liabilities, assetBalances, constants ); uint64 lockedAmount = OrionVaultInterface(constants._orionVaultContractAddress) .getLockedStakeBalance(constants.user); int192 weightedStake = uint8Percent(int192(lockedAmount), constants.stakeRisk); weightedPosition += weightedStake; totalPosition += lockedAmount; weightedPosition += _weightedPosition; totalPosition += _totalPosition; outdatedPrice = outdatedPrice || _outdatedPrice; bool incorrect = (liabilities[constants.user].length>0) && (lockedAmount==0); if(_totalPosition<0) { result.totalLiabilities = _totalPosition; } if(weightedPosition<0) { result.state = PositionState.NEGATIVE; } if(outdatedPrice) { result.state = PositionState.NOPRICE; } if(overdue) { result.state = PositionState.OVERDUE; } if(incorrect) { result.state = PositionState.INCORRECT; } result.weightedPosition = weightedPosition; result.totalPosition = totalPosition; } /** * @dev method removes liability */ function removeLiability(address user, address asset, mapping(address => Liability[]) storage liabilities) public { uint256 length = liabilities[user].length; for (uint256 i = 0; i < length; i++) { if (liabilities[user][i].asset == asset) { if (length>1) { liabilities[user][i] = liabilities[user][length - 1]; } liabilities[user].pop(); break; } } } /** * @dev method update liability * @notice implement logic for outstandingAmount (see Liability description) */ function updateLiability(address user, address asset, mapping(address => Liability[]) storage liabilities, uint112 depositAmount, int192 currentBalance) public { if(currentBalance>=0) { removeLiability(user,asset,liabilities); } else { uint256 i; uint256 liabilitiesLength=liabilities[user].length; for(; i<liabilitiesLength-1; i++) { if(liabilities[user][i].asset == asset) break; } Liability storage liability = liabilities[user][i]; if(depositAmount>=liability.outstandingAmount) { liability.outstandingAmount = uint192(-currentBalance); liability.timestamp = uint64(block.timestamp); } else { liability.outstandingAmount -= depositAmount; } } } /** * @dev partially liquidate, that is cover some asset liability to get ORN from meisbehaviour broker */ function partiallyLiquidate(address[] storage collateralAssets, mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants, address redeemedAsset, uint112 amount) public { //Note: constants.user - is broker who will be liquidated Position memory initialPosition = calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); require(initialPosition.state == PositionState.NEGATIVE || initialPosition.state == PositionState.OVERDUE , "E7"); address liquidator = msg.sender; require(assetBalances[liquidator][redeemedAsset]>=amount,"E8"); require(assetBalances[constants.user][redeemedAsset]<0,"E15"); assetBalances[liquidator][redeemedAsset] -= amount; assetBalances[constants.user][redeemedAsset] += amount; if(assetBalances[constants.user][redeemedAsset] >= 0) removeLiability(constants.user, redeemedAsset, liabilities); PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(redeemedAsset); (uint64 price, uint64 timestamp) = (assetPriceData.price, assetPriceData.timestamp); require((timestamp + constants.priceOverdue) > block.timestamp, "E9"); //Price is outdated reimburseLiquidator(amount, price, liquidator, assetBalances, constants); Position memory finalPosition = calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); require( int(finalPosition.state)<3 && //POSITIVE,NEGATIVE or OVERDUE (finalPosition.weightedPosition>initialPosition.weightedPosition), "E10");//Incorrect state position after liquidation if(finalPosition.state == PositionState.POSITIVE) require (finalPosition.weightedPosition<10e8,"Can not liquidate to very positive state"); } /** * @dev reimburse liquidator with ORN: first from stake, than from broker balance */ function reimburseLiquidator( uint112 amount, uint64 price, address liquidator, mapping(address => mapping(address => int192)) storage assetBalances, UsedConstants memory constants) internal { int192 _orionAmount = int192(int256(amount)*price/1e8); _orionAmount += uint8Percent(_orionAmount,constants.liquidationPremium); //Liquidation premium require(_orionAmount == int64(_orionAmount), "E11"); int64 orionAmount = int64(_orionAmount); // There is only 100m Orion tokens, fits i64 int64 onBalanceOrion = int64(assetBalances[constants.user][constants._orionTokenAddress]); (int64 fromBalance, int64 fromStake) = (onBalanceOrion>orionAmount)? (orionAmount, 0) : (onBalanceOrion>0)? (onBalanceOrion, orionAmount-onBalanceOrion) : (0, orionAmount); if(fromBalance>0) { assetBalances[constants.user][constants._orionTokenAddress] -= int192(fromBalance); assetBalances[liquidator][constants._orionTokenAddress] += int192(fromBalance); } if(fromStake>0) { OrionVaultInterface(constants._orionVaultContractAddress).seizeFromStake(constants.user, liquidator, uint64(fromStake)); } } } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; import "./Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; import "./Context.sol"; import "./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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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 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.7.4; contract ReentrancyGuard { bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } modifier nonReentrant() { // Ensure mutex is unlocked require(!getStorageBool(REENTRANCY_MUTEX_POSITION), ERROR_REENTRANT); // Lock mutex before function call setStorageBool(REENTRANCY_MUTEX_POSITION,true); // Perform function call _; // Unlock mutex after function call setStorageBool(REENTRANCY_MUTEX_POSITION, false); } } pragma solidity >=0.6.2; interface IOrionPoolV2Router02Ext { function swapExactTokensForTokensAutoRoute( uint amountIn, uint amountOutMin, address[] calldata path, address to ) external payable returns (uint[] memory amounts); function swapTokensForExactTokensAutoRoute( uint amountOut, uint amountInMax, address[] calldata path, address to ) external payable returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
method to add liability user - user which created liability asset - liability asset balance - current negative balance/
function setLiability(address user, address asset, int192 balance) internal { liabilities[user].push( MarginalFunctionality.Liability({ asset: asset, timestamp: uint64(block.timestamp), outstandingAmount: uint192(-balance)}) ); }
13,685,871
/** *Submitted for verification at Etherscan.io on 2021-10-13 */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; contract Dank { /// @notice EIP-20 token name for this token string public constant name = "Decentralized-Bank"; /// @notice EIP-20 token symbol for this token string public constant symbol = "DANK"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 100000000e18; // 100 million Dank /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; address public owner; address public pendingOwnerAddr; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); // Called when new token are issued // event Issue(uint amount); /** * @notice Construct a new Dank token */ constructor() public { owner = msg.sender; balances[owner] = uint96(totalSupply); emit Transfer(address(0), owner, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(- 1)) { amount = uint96(- 1); } else { amount = safe96(rawAmount, "Dank::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Dank::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issued // function issue(uint96 amount) public onlyOwner { // require(totalSupply + amount > totalSupply); // require(balances[owner] + amount > balances[owner]); // // balances[owner] += amount; // totalSupply = add96(uint96(totalSupply),amount,'Dank issue amount overflows'); // emit Issue(amount); // } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Dank::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(- 1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Dank::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Dank::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Dank::delegateBySig: invalid nonce"); require(now <= expiry, "Dank::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Dank::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Dank::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Dank::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Dank::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Dank::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Dank::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Dank::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Dank::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2 ** 32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2 ** 96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly {chainId := chainid()} return chainId; } event OwnershipTransferRequested(address indexed from, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); /** * @notice Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address to) external onlyOwner() { require(to != msg.sender, "Cannot transfer to self"); pendingOwnerAddr = to; emit OwnershipTransferRequested(owner, to); } /** * @notice Allows an ownership transfer to be dankleted by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwnerAddr, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwnerAddr = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @notice Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } }
Approve `spender` to transfer up to `amount` from `src` This will overwrite the approval amount for `spender` spender The address of the account which may transfer tokens rawAmount The number of tokens that are approved (2^256-1 means infinite) return Whether or not the approval succeeded/
function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(- 1)) { amount = uint96(- 1); amount = safe96(rawAmount, "Dank::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; }
10,823,915
pragma solidity ^0.4.18; /** * @title WeBetCrypto * @author AL_X * @dev The WBC ERC-223 Token Contract */ contract WeBetCrypto { string public name = "We Bet Crypto"; string public symbol = "WBA"; address public selfAddress; address public admin; address[] private users; uint8 public decimals = 7; uint256 public relativeDateSave; uint256 public totalFunds; uint256 public totalSupply = 400000000000000; uint256 public IOUSupply = 0; uint256 private amountInCirculation; uint256 private currentProfits; uint256 private currentIteration; uint256 private actualProfitSplit; bool public isFrozen; bool private running; mapping(address => uint256) balances; mapping(address => uint256) moneySpent; mapping(address => uint256) monthlyLimit; mapping(address => uint256) cooldown; mapping(address => bool) isAdded; mapping(address => bool) claimedBonus; mapping(address => bool) bannedUser; //mapping(address => bool) loggedUser; mapping (address => mapping (address => uint256)) allowed; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @notice Ensures admin is caller */ modifier isAdmin() { require(msg.sender == admin); //Continue executing rest of method body _; } /** * @notice Re-entry protection */ modifier isRunning() { require(!running); running = true; _; running = false; } /** * @notice Ensures system isn't frozen */ modifier noFreeze() { require(!isFrozen); _; } /** * @notice Ensures player isn't logged in on platform */ modifier userNotPlaying(address _user) { //require(!loggedUser[_user]); uint256 check = 0; check -= 1; require(cooldown[_user] == check); _; } /** * @notice Ensures player isn't bannedUser */ modifier userNotBanned(address _user) { require(!bannedUser[_user]); _; } /** * @notice SafeMath Library safeSub Import * @dev Since we are dealing with a limited currency circulation of 40 million tokens and values that will not surpass the uint256 limit, only safeSub is required to prevent underflows. */ function safeSub(uint256 a, uint256 b) internal pure returns (uint256 z) { assert((z = a - b) <= a); } /** * @notice WBC Constructor * @dev Constructor function containing proper initializations such as token distribution to the team members and pushing the first profit split to 6 months when the DApp will already be live. */ function WeBetCrypto() public { admin = msg.sender; selfAddress = this; balances[0x66AE070A8501E816CA95ac99c4E15C7e132fd289] = 200000000000000; addUser(0x66AE070A8501E816CA95ac99c4E15C7e132fd289); Transfer(selfAddress, 0x66AE070A8501E816CA95ac99c4E15C7e132fd289, 200000000000000); balances[0xcf8d242C523bfaDC384Cc1eFF852Bf299396B22D] = 50000000000000; addUser(0xcf8d242C523bfaDC384Cc1eFF852Bf299396B22D); Transfer(selfAddress, 0xcf8d242C523bfaDC384Cc1eFF852Bf299396B22D, 50000000000000); relativeDateSave = now + 40 days; balances[selfAddress] = 150000000000000; } /** * @notice Check the name of the token ~ ERC-20 Standard * @return { "_name": "The token name" } */ function name() external constant returns (string _name) { return name; } /** * @notice Check the symbol of the token ~ ERC-20 Standard * @return { "_symbol": "The token symbol" } */ function symbol() external constant returns (string _symbol) { return symbol; } /** * @notice Check the decimals of the token ~ ERC-20 Standard * @return { "_decimals": "The token decimals" } */ function decimals() external constant returns (uint8 _decimals) { return decimals; } /** * @notice Check the total supply of the token ~ ERC-20 Standard * @return { "_totalSupply": "Total supply of tokens" } */ function totalSupply() external constant returns (uint256 _totalSupply) { return totalSupply; } /** * @notice Query the available balance of an address ~ ERC-20 Standard * @param _owner The address whose balance we wish to retrieve * @return { "balance": "Balance of the address" } */ function balanceOf(address _owner) external constant returns (uint256 balance) { return balances[_owner]; } /** * @notice Query the amount of tokens the spender address can withdraw from the owner address ~ ERC-20 Standard * @param _owner The address who owns the tokens * @param _spender The address who can withdraw the tokens * @return { "remaining": "Remaining withdrawal amount" } */ function allowance(address _owner, address _spender) external constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @notice Query whether the user is eligible for claiming dividence * @param _user The address to query * @return _success Whether or not the user is eligible */ function eligibleForDividence(address _user) public view returns (bool _success) { if (moneySpent[_user] == 0) { return false; } else if ((balances[_user] + allowed[selfAddress][_user])/moneySpent[_user] > 20) { return false; } return true; } /** * @notice Transfer tokens from an address to another ~ ERC-20 Standard * @dev Adjusts the monthly limit in case the _from address is the Casino and ensures that the user isn't logged in when retrieving funds so as to prevent against a race attack with the Casino. * @param _from The address whose balance we will transfer * @param _to The recipient address * @param _value The amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) external noFreeze { var _allowance = allowed[_from][_to]; if (_from == selfAddress) { monthlyLimit[_to] = safeSub(monthlyLimit[_to], _value); require(cooldown[_to] < now /*&& !loggedUser[_to]*/); IOUSupply -= _value; } balances[_to] = balances[_to]+_value; balances[_from] = safeSub(balances[_from], _value); allowed[_from][_to] = safeSub(_allowance, _value); addUser(_to); Transfer(_from, _to, _value); } /** * @notice Authorize an address to retrieve funds from you ~ ERC-20 Standard * @dev 30 minute cooldown removed for easier participation in trading platforms such as Ether Delta * @param _spender The address you wish to authorize * @param _value The amount of tokens you wish to authorize */ function approve(address _spender, uint256 _value) external { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @notice Transfer the specified amount to the target address ~ ERC-20 Standard * @dev A boolean is returned so that callers of the function will know if their transaction went through. * @param _to The address you wish to send the tokens to * @param _value The amount of tokens you wish to send * @return { "success": "Transaction success" } */ function transfer(address _to, uint256 _value) external isRunning noFreeze returns (bool success) { bytes memory empty; if (_to == selfAddress) { return transferToSelf(_value); } else if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value); } } /** * @notice Check whether address is a contract ~ ERC-223 Proposed Standard * @param _address The address to check * @return { "is_contract": "Result of query" } */ function isContract(address _address) internal view returns (bool is_contract) { uint length; assembly { length := extcodesize(_address) } return length > 0; } /** * @notice Transfer the specified amount to the target address with embedded bytes data ~ ERC-223 Proposed Standard * @dev Includes an extra transferToSelf function to handle Casino deposits * @param _to The address to transfer to * @param _value The amount of tokens to transfer * @param _data Any extra embedded data of the transaction * @return { "success": "Transaction success" } */ function transfer(address _to, uint256 _value, bytes _data) external isRunning noFreeze returns (bool success){ if (_to == selfAddress) { return transferToSelf(_value); } else if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value); } } /** * @notice Handles transfer to an ECA (Externally Controlled Account), a normal account ~ ERC-223 Proposed Standard * @param _to The address to transfer to * @param _value The amount of tokens to transfer * @return { "success": "Transaction success" } */ function transferToAddress(address _to, uint256 _value) internal returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = balances[_to]+_value; addUser(_to); Transfer(msg.sender, _to, _value); return true; } /** * @notice Handles transfer to a contract ~ ERC-223 Proposed Standard * @param _to The address to transfer to * @param _value The amount of tokens to transfer * @param _data Any extra embedded data of the transaction * @return { "success": "Transaction success" } */ function transferToContract(address _to, uint256 _value, bytes _data) internal returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = balances[_to]+_value; WeBetCrypto rec = WeBetCrypto(_to); rec.tokenFallback(msg.sender, _value, _data); addUser(_to); Transfer(msg.sender, _to, _value); return true; } /** * @notice Handles Casino deposits ~ Custom ERC-223 Proposed Standard Addition * @param _value The amount of tokens to transfer * @return { "success": "Transaction success" } */ function transferToSelf(uint256 _value) internal returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[selfAddress] = balances[selfAddress]+_value; Transfer(msg.sender, selfAddress, _value); allowed[selfAddress][msg.sender] = _value + allowed[selfAddress][msg.sender]; IOUSupply += _value; Approval(selfAddress, msg.sender, allowed[selfAddress][msg.sender]); return true; } /** * @notice Empty tokenFallback method to ensure ERC-223 compatibility * @param _sender The address who sent the ERC-223 tokens * @param _value The amount of tokens the address sent to this contract * @param _data Any embedded data of the transaction */ function tokenFallback(address _sender, uint256 _value, bytes _data) public {} /** * @notice Check how much Casino withdrawal balance remains for address * @return { "remaining": "Withdrawal balance remaining" } */ function checkMonthlyLimit() external constant returns (uint256 remaining) { return monthlyLimit[msg.sender]; } /** * @notice Retrieve ERC Tokens sent to contract * @dev Feel free to contact us and retrieve your ERC tokens should you wish so. * @param _token The token contract address */ function claimTokens(address _token) isAdmin external { require(_token != selfAddress); WeBetCrypto token = WeBetCrypto(_token); uint balance = token.balanceOf(selfAddress); token.transfer(admin, balance); } /** * @notice Freeze token circulation - splitProfits internal * @dev Ensures that one doesn't transfer his total balance mid-split to an account later in the split queue in order to receive twice the monthly profits */ function assetFreeze() internal { isFrozen = true; } /** * @notice Re-enable token circulation - splitProfits internal */ function assetThaw() internal { isFrozen = false; } /** * @notice Freeze token circulation * @dev To be used only in extreme circumstances. */ function emergencyFreeze() isAdmin external { isFrozen = true; } /** * @notice Re-enable token circulation * @dev To be used only in extreme circumstances */ function emergencyThaw() isAdmin external { isFrozen = false; } /** * @notice Disable the splitting function * @dev To be used in case the system is upgraded to a node.js operated profit reward system via the alterBankBalance function. Ensures scalability in case userbase gets too big. */ function emergencySplitToggle() isAdmin external { uint temp = 0; temp -= 1; if (relativeDateSave == temp) { relativeDateSave = now; } else { relativeDateSave = temp; } } /** * @notice Add the address to the user list * @dev Used for the splitting function to take it into account * @param _user User to add to database */ function addUser(address _user) internal { if (!isAdded[_user]) { users.push(_user); monthlyLimit[_user] = 1000000000000; isAdded[_user] = true; } } /** * @notice Split the monthly profits of the Casino to the users * @dev The formula that calculates the profit a user is owed can be seen on the white paper. The actualProfitSplit variable stores the actual values that are distributed to the users to prevent rounding errors from burning tokens. Since gas requirements will spike the more users use our platform, a loop-state-save is implemented to ensure scalability. */ function splitProfits() external { uint i; if (!isFrozen) { require(now >= relativeDateSave); assetFreeze(); require(balances[selfAddress] > 30000000000000); relativeDateSave = now + 30 days; currentProfits = ((balances[selfAddress]-30000000000000)/10)*7; amountInCirculation = safeSub(400000000000000, balances[selfAddress]) + IOUSupply; currentIteration = 0; actualProfitSplit = 0; } else { for (i = currentIteration; i < users.length; i++) { monthlyLimit[users[i]] = 1000000000000; if (msg.gas < 250000) { currentIteration = i; break; } if (!eligibleForDividence(users[i])) { moneySpent[users[i]] = 0; checkSplitEnd(i); continue; } moneySpent[users[i]] = 0; actualProfitSplit += ((balances[users[i]]+allowed[selfAddress][users[i]])*currentProfits)/amountInCirculation; Transfer(selfAddress, users[i], ((balances[users[i]]+allowed[selfAddress][users[i]])*currentProfits)/amountInCirculation); balances[users[i]] += ((balances[users[i]]+allowed[selfAddress][users[i]])*currentProfits)/amountInCirculation; checkSplitEnd(i); } } } /** * @notice Change variables on split end * @param i The current index of the split loop. */ function checkSplitEnd(uint256 i) internal { if (i == users.length-1) { assetThaw(); balances[0x66AE070A8501E816CA95ac99c4E15C7e132fd289] = balances[0x66AE070A8501E816CA95ac99c4E15C7e132fd289] + currentProfits/20; balances[selfAddress] = balances[selfAddress] - actualProfitSplit - currentProfits/20; } } /** * @notice Rise or lower user bank balance - Backend Function * @dev This allows adjustment of the balance a user has within the Casino to represent earnings and losses. * @param _toAlter The address whose Casino balance to alter * @param _amount The amount to alter it by */ function alterBankBalance(address _toAlter, uint256 _amount) internal { if (_amount > allowed[selfAddress][_toAlter]) { IOUSupply += (_amount - allowed[selfAddress][_toAlter]); moneySpent[_toAlter] += (_amount - allowed[selfAddress][_toAlter]); allowed[selfAddress][_toAlter] = _amount; Approval(selfAddress, _toAlter, allowed[selfAddress][_toAlter]); } else { IOUSupply -= (allowed[selfAddress][_toAlter] - _amount); moneySpent[_toAlter] += (allowed[selfAddress][_toAlter] - _amount); allowed[selfAddress][_toAlter] = _amount; Approval(selfAddress, _toAlter, allowed[selfAddress][_toAlter]); } } /** * @notice Freeze user during platform use - Backend Function * @dev Prevents against the ERC-20 race attack on the Casino */ function platformLogin() userNotBanned(msg.sender) external { //loggedUser[msg.sender] = true; cooldown[msg.sender] = 0; cooldown[msg.sender] -= 1; } /** * @notice De-Freeze user - Backend Function * @dev Used when a user logs out or loses connection with the DApp */ function platformLogout(address _toLogout, uint256 _newBalance) external isAdmin { //loggedUser[msg.sender] = false; cooldown[_toLogout] = now + 30 minutes; alterBankBalance(_toLogout,_newBalance); } /** * @notice Check if user is logged internal * @dev Used to ensure that the user is logged in throughout * the whole casino session * @param _toCheck The user address to check */ function checkLogin(address _toCheck) view external returns (bool) { uint256 check = 0; check -= 1; return (cooldown[_toCheck] == check); } /** * @notice Ban a user * @dev Used in extreme circumstances where the users break the law * @param _user The user to ban */ function banUser(address _user) external isAdmin { bannedUser[_user] = true; cooldown[_user] = now + 30 minutes; } /** * @notice Unban a user * @dev Used in extreme circumstances where the users have redeemed * @param _user The user to unban */ function unbanUser(address _user) external isAdmin { bannedUser[_user] = false; } /** * @notice Check if a user is banned * @dev Used by the back-end to give a message to the user * @param _user The user to check */ function checkBan(address _user) external view returns (bool) { return bannedUser[_user]; } /** * @notice Purchase WBC Tokens for Self - ICO */ function() payable external { totalFunds = totalFunds + msg.value; address etherTransfer = 0x66AE070A8501E816CA95ac99c4E15C7e132fd289; require(msg.value > 0); require(msg.sender != etherTransfer); require(totalFunds/1 ether < 2000); addUser(msg.sender); uint256 tokenAmount = msg.value/100000000; balances[selfAddress] = balances[selfAddress] - tokenAmount; balances[msg.sender] = balances[msg.sender] + tokenAmount; Transfer(selfAddress, msg.sender, tokenAmount); etherTransfer.transfer(msg.value); } /** * @notice Advertising Token Distribution * @dev Ensures the user has at least 0.1 Ether on his * account before distributing 20 WBC */ function claimBonus() external { require(msg.sender.balance/(1000 finney) >= 1 && !claimedBonus[msg.sender]); claimedBonus[msg.sender] = true; allowed[selfAddress][msg.sender] = allowed[selfAddress][msg.sender] + 200000000; IOUSupply += 200000000; addUser(msg.sender); Approval(selfAddress, msg.sender, allowed[selfAddress][msg.sender]); } }
_spender The address you wish to authorize _value The amount of tokens you wish to authorize/
function approve(address _spender, uint256 _value) external { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); 30 minute cooldown removed for easier participation in }
2,506,581
./partial_match/1/0xb683785915BCB0FfFbcdbAc07f9339fd1243ba43/sources/FanToken223Token_15.sol
do not need to to anything with that token address?if (token == 0) { attila addition
function supportsToken(address token) public override view returns (bool) { return false; } return false;
11,025,039
// 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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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 SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import './interfaces/IMetaSwapDeposit.sol'; import './interfaces/ISwap.sol'; interface IERC20Mintable is IERC20 { function mint(address to, uint256 amount) external; function mintMultiple( address to, uint256 amount, address feeAddress, uint256 feeAmount ) external; } contract SynapseBridge is Initializable, AccessControlUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; bytes32 public constant NODEGROUP_ROLE = keccak256('NODEGROUP_ROLE'); mapping(address => uint256) private fees; uint256 private ethFees; uint256 public startBlockNumber; function initialize() public initializer { startBlockNumber = block.number; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); __AccessControl_init(); } event TokenDeposit( address indexed to, uint256 chainId, IERC20 token, uint256 amount ); event TokenRedeem(address indexed to, uint256 chainId, IERC20 token, uint256 amount); event TokenWithdraw(address indexed to, IERC20 token, uint256 amount, uint256 fee); event TokenMint( address indexed to, IERC20Mintable token, uint256 amount, uint256 fee ); event TokenDepositAndSwap( address indexed to, uint256 chainId, IERC20 token, uint256 amount, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 minDy, uint256 deadline ); event TokenMintAndSwap( address indexed to, IERC20Mintable token, uint256 amount, uint256 fee, bool swapSuccess ); event TokenRedeemAndSwap( address indexed to, uint256 chainId, IERC20 token, uint256 amount, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 minDy, uint256 deadline ); event TokenRedeemAndRemove( address indexed to, uint256 chainId, IERC20 token, uint256 amount, uint256 swapTokenAmount, uint8 swapTokenIndex, uint256 swapMinAmount, uint256 swapDeadline ); event TokenWithdrawAndRemove( address indexed to, IERC20 token, uint256 amount, uint256 fee, bool swapSuccess ); // VIEW FUNCTIONS ***/ function getFeeBalance(address tokenAddress) external view returns (uint256) { return fees[tokenAddress]; } function getETHFeeBalance() external view returns (uint256) { return ethFees; } // FEE FUNCTIONS ***/ /** * * @notice withdraw specified ERC20 token fees to a given address * * @param token ERC20 token in which fees acccumulated to transfer * * @param to Address to send the fees to */ function withdrawFees(IERC20 token, address to) external { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); if (fees[address(token)] != 0) { token.safeTransfer(to, fees[address(token)]); } } /** * * @notice withdraw gas token fees to a given address * * @param to Address to send the gas fees to */ function withdrawETHFees(address payable to) external { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); if (ethFees != 0) { to.transfer(ethFees); } } /** * @notice Relays to nodes to transfers the underlying chain gas token cross-chain * @param to address on other chain to bridge assets to * @param chainId which chain to bridge assets onto * @param amount Amount in native token decimals to transfer cross-chain pre-fees **/ function depositETH( address to, uint256 chainId, uint256 amount ) public payable { require(msg.value == amount, "Value doesn't match amount"); emit TokenDeposit(to, chainId, IERC20(address(0)), amount); } /** * @notice Relays to nodes to transfers an ERC20 token cross-chain * @param to address on other chain to bridge assets to * @param chainId which chain to bridge assets onto * @param token ERC20 compatible token to deposit into the bridge * @param amount Amount in native token decimals to transfer cross-chain pre-fees **/ function deposit( address to, uint256 chainId, IERC20 token, uint256 amount ) public { token.safeTransferFrom(msg.sender, address(this), amount); emit TokenDeposit(to, chainId, token, amount); } /** * @notice Relays to nodes that (typically) a wrapped synAsset ERC20 token has been burned and the underlying needs to be redeeemed on the native chain * @param to address on other chain to redeem underlying assets to * @param chainId which underlying chain to bridge assets onto * @param token ERC20 compatible token to deposit into the bridge * @param amount Amount in native token decimals to transfer cross-chain pre-fees **/ function redeem( address to, uint256 chainId, ERC20Burnable token, uint256 amount ) public { token.burnFrom(msg.sender, amount); emit TokenRedeem(to, chainId, token, amount); } /** * @notice Function to be called by the node group to withdraw the underlying assets from the contract * @param to address on chain to send underlying assets to * @param token ERC20 compatible token to withdraw from the bridge * @param amount Amount in native token decimals to withdraw * @param fee Amount in native token decimals to save to the contract as fees **/ function withdraw( address to, IERC20 token, uint256 amount, uint256 fee ) public { require(hasRole(NODEGROUP_ROLE, msg.sender), 'Caller is not a node group'); fees[address(token)] = fees[address(token)].add(fee); token.safeTransfer(to, amount); emit TokenWithdraw(to, token, amount, fee); } /** * @notice Function to be called by the node group to withdraw the underlying gas asset from the contract * @param to address on chain to send gas asset to * @param amount Amount in gas token decimals to withdraw (after subtracting fee already) * @param fee Amount in gas token decimals to save to the contract as fees **/ function withdrawETH( address payable to, uint256 amount, uint256 fee ) public { require(hasRole(NODEGROUP_ROLE, msg.sender), 'Caller is not a node group'); ethFees = ethFees.add(fee); to.transfer(amount); emit TokenWithdraw(to, IERC20(address(0)), amount, fee); } /** * @notice Nodes call this function to mint a SynERC20 (or any asset that the bridge is given minter access to). This is called by the nodes after a TokenDeposit event is emitted. * @dev This means the SynapseBridge.sol contract must have minter access to the token attempting to be minted * @param to address on other chain to redeem underlying assets to * @param token ERC20 compatible token to deposit into the bridge * @param amount Amount in native token decimals to transfer cross-chain post-fees * @param fee Amount in native token decimals to save to the contract as fees **/ function mint( address to, IERC20Mintable token, uint256 amount, uint256 fee ) public { require(hasRole(NODEGROUP_ROLE, msg.sender), 'Caller is not a node group'); fees[address(token)] = fees[address(token)].add(fee); token.mint(address(this), amount.add(fee)); IERC20(token).safeTransfer(to, amount); emit TokenMint(to, token, amount, fee); } /** * @notice Relays to nodes to both transfer an ERC20 token cross-chain, and then have the nodes execute a swap through a liquidity pool on behalf of the user. * @param to address on other chain to bridge assets to * @param chainId which chain to bridge assets onto * @param token ERC20 compatible token to deposit into the bridge * @param amount Amount in native token decimals to transfer cross-chain pre-fees * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param minDy the min amount the user would like to receive, or revert to only minting the SynERC20 token crosschain. * @param deadline latest timestamp to accept this transaction **/ function depositAndSwap( address to, uint256 chainId, IERC20 token, uint256 amount, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 minDy, uint256 deadline ) public { token.safeTransferFrom(msg.sender, address(this), amount); emit TokenDepositAndSwap( to, chainId, token, amount, tokenIndexFrom, tokenIndexTo, minDy, deadline ); } /** * @notice Relays to nodes that (typically) a wrapped synAsset ERC20 token has been burned and the underlying needs to be redeeemed on the native chain. This function indicates to the nodes that they should attempt to redeem the LP token for the underlying assets (E.g "swap" out of the LP token) * @param to address on other chain to redeem underlying assets to * @param chainId which underlying chain to bridge assets onto * @param token ERC20 compatible token to deposit into the bridge * @param amount Amount in native token decimals to transfer cross-chain pre-fees * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param minDy the min amount the user would like to receive, or revert to only minting the SynERC20 token crosschain. * @param deadline latest timestamp to accept this transaction **/ function redeemAndSwap( address to, uint256 chainId, ERC20Burnable token, uint256 amount, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 minDy, uint256 deadline ) public { token.burnFrom(msg.sender, amount); emit TokenRedeemAndSwap( to, chainId, token, amount, tokenIndexFrom, tokenIndexTo, minDy, deadline ); } /** * @notice Relays to nodes that (typically) a wrapped synAsset ERC20 token has been burned and the underlying needs to be redeeemed on the native chain. This function indicates to the nodes that they should attempt to redeem the LP token for the underlying assets (E.g "swap" out of the LP token) * @param to address on other chain to redeem underlying assets to * @param chainId which underlying chain to bridge assets onto * @param token ERC20 compatible token to deposit into the bridge * @param amount Amount in native token decimals to transfer cross-chain pre-fees * @param swapTokenAmount Amount of (typically) LP token to pass to the nodes to attempt to removeLiquidity() with to redeem for the underlying assets of the LP token * @param swapTokenIndex Specifies which of the underlying LP assets the nodes should attempt to redeem for * @param swapMinAmount Specifies the minimum amount of the underlying asset needed for the nodes to execute the redeem/swap * @param swapDeadline Specificies the deadline that the nodes are allowed to try to redeem/swap the LP token **/ function redeemAndRemove( address to, uint256 chainId, ERC20Burnable token, uint256 amount, uint256 swapTokenAmount, uint8 swapTokenIndex, uint256 swapMinAmount, uint256 swapDeadline ) public { token.burnFrom(msg.sender, amount); emit TokenRedeemAndRemove( to, chainId, token, amount, swapTokenAmount, swapTokenIndex, swapMinAmount, swapDeadline ); } /** * @notice Nodes call this function to mint a SynERC20 (or any asset that the bridge is given minter access to), and then attempt to swap the SynERC20 into the desired destination asset. This is called by the nodes after a TokenDepositAndSwap event is emitted. * @dev This means the BridgeDeposit.sol contract must have minter access to the token attempting to be minted * @param to address on other chain to redeem underlying assets to * @param token ERC20 compatible token to deposit into the bridge * @param amount Amount in native token decimals to transfer cross-chain post-fees * @param fee Amount in native token decimals to save to the contract as fees * @param pool Destination chain's pool to use to swap SynERC20 -> Asset. The nodes determine this by using PoolConfig.sol. * @param tokenIndexFrom Index of the SynERC20 asset in the pool * @param tokenIndexTo Index of the desired final asset * @param minDy Minumum amount (in final asset decimals) that must be swapped for, otherwise the user will receive the SynERC20. * @param deadline Epoch time of the deadline that the swap is allowed to be executed. **/ function mintAndSwap( address to, IERC20Mintable token, uint256 amount, uint256 fee, IMetaSwapDeposit pool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 minDy, uint256 deadline ) public { require(hasRole(NODEGROUP_ROLE, msg.sender), 'Caller is not a node group'); fees[address(token)] = fees[address(token)].add(fee); // first check to make sure more will be given than min amount required uint256 expectedOutput = IMetaSwapDeposit(pool).calculateSwap( tokenIndexFrom, tokenIndexTo, amount ); if (expectedOutput >= minDy) { // proceed with swap token.mint(address(this), amount.add(fee)); token.approve(address(pool), amount); try IMetaSwapDeposit(pool).swap( tokenIndexFrom, tokenIndexTo, amount, minDy, deadline ) returns (uint256 finalSwappedAmount) { // Swap succeeded, transfer swapped asset IERC20 swappedTokenTo = IMetaSwapDeposit(pool).getToken(tokenIndexTo); swappedTokenTo.safeTransfer(to, finalSwappedAmount); emit TokenMintAndSwap(to, token, amount, fee, true); } catch { IERC20(token).safeTransfer(to, amount); emit TokenMintAndSwap(to, token, amount, fee, false); } } else { token.mint(address(this), amount.add(fee)); IERC20(token).safeTransfer(to, amount); emit TokenMintAndSwap(to, token, amount, fee, false); } } /** * @notice Function to be called by the node group to withdraw the underlying assets from the contract * @param to address on chain to send underlying assets to * @param token ERC20 compatible token to withdraw from the bridge * @param amount Amount in native token decimals to withdraw * @param fee Amount in native token decimals to save to the contract as fees * @param pool Destination chain's pool to use to swap SynERC20 -> Asset. The nodes determine this by using PoolConfig.sol. * @param swapTokenAmount Amount of (typically) LP token to attempt to removeLiquidity() with to redeem for the underlying assets of the LP token * @param swapTokenIndex Specifies which of the underlying LP assets the nodes should attempt to redeem for * @param swapMinAmount Specifies the minimum amount of the underlying asset needed for the nodes to execute the redeem/swap * @param swapDeadline Specificies the deadline that the nodes are allowed to try to redeem/swap the LP token **/ function withdrawAndRemove( address to, IERC20 token, uint256 amount, uint256 fee, ISwap pool, uint256 swapTokenAmount, uint8 swapTokenIndex, uint256 swapMinAmount, uint256 swapDeadline ) public { require(hasRole(NODEGROUP_ROLE, msg.sender), 'Caller is not a node group'); fees[address(token)] = fees[address(token)].add(fee); // first check to make sure more will be given than min amount required uint256 expectedOutput = ISwap(pool).calculateRemoveLiquidityOneToken( swapTokenAmount, swapTokenIndex ); if (expectedOutput >= swapMinAmount) { token.safeApprove(address(pool), swapTokenAmount); try ISwap(pool).removeLiquidityOneToken( swapTokenAmount, swapTokenIndex, swapMinAmount, swapDeadline ) returns (uint256 finalSwappedAmount) { // Swap succeeded, transfer swapped asset IERC20 swappedTokenTo = ISwap(pool).getToken(swapTokenIndex); swappedTokenTo.safeTransfer(to, finalSwappedAmount); emit TokenWithdrawAndRemove(to, token, amount, fee, true); } catch { IERC20(token).safeTransfer(to, amount); emit TokenWithdrawAndRemove(to, token, amount, fee, false); } } else { token.safeTransfer(to, amount); emit TokenWithdrawAndRemove(to, token, amount, fee, false); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; /** * @title IMetaSwapDeposit interface * @notice Interface for the meta swap contract. * @dev implement this interface to develop a a factory-patterned ECDSA node management contract **/ interface IMetaSwapDeposit { // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function getToken(uint256 index) external view returns (IERC20); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); }
IMetaSwapDeposit interface Interface for the meta swap contract. implement this interface to develop a a factory-patterned ECDSA node management contract/ min return calculation functions
interface IMetaSwapDeposit { function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function getToken(uint256 index) external view returns (IERC20); }
98,772
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol 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); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/GeneralTokenVesting.sol pragma solidity ^0.6.12; /** * @title GeneralTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a vesting period. */ contract GeneralTokenVesting { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // duration of four years, are safe to use. using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased( IERC20 token, address beneficiary, address recipient, uint256 amount ); event VestStarted(IERC20 token, address beneficiary, uint256 amount); struct Vest { uint256 _totalTokens; uint256 _releasedTokens; uint256 _start; uint256 _duration; } //data mapping for token contract mapping(IERC20 => mapping(address => Vest)) public tokenVest; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @dev transfers erc20 token to vesting contract to allow the vesting contract to release * tokens at the end of the vesting schedule. * @param beneficiary addresses of the beneficiaries to whom vested tokens are transferred * @param tokensToVest amounts of tokens for the beneficiaries * @param vestDuration duration in seconds of the period in which the tokens will vest * @param tokenAddress address of the token to be vested */ function startVest( address beneficiary, uint256 tokensToVest, uint256 vestDuration, IERC20 tokenAddress ) public { require(vestDuration > 0, "GeneralTokenVesting: duration is 0"); require( beneficiary != address(0), "GeneralTokenVesting: beneficiary is the zero address" ); require( address(tokenAddress) != address(0), "GeneralTokenVesting: token is the zero address" ); require(tokensToVest != 0, "GeneralTokenVesting: amount is zero"); require( getTotalTokens(tokenAddress, beneficiary) == 0, "GeneralTokenVesting: Vest already created for this token => beneficiary" ); uint256 beforeBalance = tokenAddress.balanceOf(address(this)); tokenAddress.safeTransferFrom(msg.sender, address(this), tokensToVest); uint256 afterBalance = tokenAddress.balanceOf(address(this)); uint256 resultBalance = afterBalance.sub(beforeBalance); require(resultBalance != 0, "GeneralTokenVesting: amount is zero"); Vest memory newVest = Vest(resultBalance, 0, block.timestamp, vestDuration); tokenVest[tokenAddress][beneficiary] = newVest; emit VestStarted(tokenAddress, beneficiary, resultBalance); } /** * @return the start time of the token vesting. */ function getStart(IERC20 token, address beneficiary) public view returns (uint256) { return tokenVest[token][beneficiary]._start; } /** * @return the total tokens of the token vesting. */ function getTotalTokens(IERC20 token, address beneficiary) public view returns (uint256) { return tokenVest[token][beneficiary]._totalTokens; } /** * @return the duration of the token vesting. */ function getDuration(IERC20 token, address beneficiary) public view returns (uint256) { return tokenVest[token][beneficiary]._duration; } /** * @return the amount of the tokens released. */ function getReleasedTokens(IERC20 token, address beneficiary) public view returns (uint256) { return tokenVest[token][beneficiary]._releasedTokens; } /** * @return the amount of tokens which can be claimed by a beneficiary. */ function getReleasableAmount(IERC20 token, address beneficiary) public view returns (uint256) { return totalVestedAmount(token, beneficiary).sub( getReleasedTokens(token, beneficiary) ); } /** * @notice Transfers vested tokens to beneficiary. * @param beneficiary beneficiary to receive the funds * @param token address of the token released * Private used by release/releaseTo functions */ function _release( IERC20 token, address beneficiary, address recipient ) private { uint256 unreleased = getReleasableAmount(token, beneficiary); require(unreleased > 0, "GeneralTokenVesting: no tokens are due"); tokenVest[token][beneficiary]._releasedTokens = tokenVest[token][ beneficiary ] ._releasedTokens .add(unreleased); token.safeTransfer(recipient, unreleased); emit TokensReleased(token, beneficiary, recipient, unreleased); } /** * @notice Transfers vested tokens to beneficiary. * @param beneficiary beneficiary to receive the funds * @param token address of the token released */ function release(IERC20 token, address beneficiary) public { _release(token, beneficiary, beneficiary); } /** * @notice Transfers beneficiary's tokens to a new recipient. * Beneficiary must be msg.sender * @param recipient recipient to receive the beneficiary's funds * @param token address of the token released */ function releaseTo(IERC20 token, address recipient) public { _release(token, msg.sender, recipient); } /** * @dev Calculates the amount that has already vested. * @param beneficiary beneficiary address to check * @param token address of the token vested */ function totalVestedAmount(IERC20 token, address beneficiary) public view returns (uint256) { uint256 _startTime = getStart(token, beneficiary); uint256 _durationTime = getDuration(token, beneficiary); if (block.timestamp < _startTime) { return 0; } else if (block.timestamp >= _startTime.add(_durationTime)) { return getTotalTokens(token, beneficiary); } else { return getTotalTokens(token, beneficiary) .mul(block.timestamp.sub(_startTime)) .div(_durationTime); } } }
return the start time of the token vesting./
function getStart(IERC20 token, address beneficiary) public view returns (uint256) { return tokenVest[token][beneficiary]._start; }
13,394,954
./partial_match/1/0x93C5cF832AD6Be0a7BF5d70B05FBc50864982B46/sources/src/interfaces/IExecutionStrategy.sol
Execution Strategy Interface
interface IExecutionStrategy is IExecutionStrategyErrors { function execute( Proposal memory proposal, uint256 votesFor, uint256 votesAgainst, uint256 votesAbstain, bytes memory payload ) external; function getProposalStatus( Proposal memory proposal, uint256 votesFor, uint256 votesAgainst, uint256 votesAbstain ) external view returns (ProposalStatus); function getStrategyType() external view returns (string memory); import { IndexedStrategy, Proposal, ProposalStatus } from "../types.sol"; import { IExecutionStrategyErrors } from "./execution-strategies/IExecutionStrategyErrors.sol"; }
3,942,584
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IGaussianRNG { function getGaussianRandomNumbers(uint256 salt, uint256 n) external view returns (uint256, int256[] memory); function reproduceGaussianRandomNumbers(uint256 seed, uint256 n) external view returns (int256[] memory); function countOnes(uint256 n) external pure returns (uint256); } ///@author Simon Tian ///@title A novel on-chain Gaussian random number generator. contract GaussianRNG is IGaussianRNG { /// A Gaussian random number generator /// @param salt A user provided number to create a seed, this can be from an /// off-chain or another on-chain reliable source of randomness, to avoid /// being manipulated by miners. /// @param n The number of random numbers to be generated, ideally < 1000 /// @return seed The seed for this sequence of numbers, which can be used /// in another function for reproducing the same sequence of numbers. /// @return nums Desired sequence of Gaussian random numbers function getGaussianRandomNumbers(uint256 salt, uint256 n) public view override returns(uint256, int256[] memory) { uint256 seed = uint256(keccak256(abi.encodePacked(salt + block.timestamp))); return (seed, _GaussianRNG(seed, n)); } /// To reproduce Gaussian random numbers with a given seed /// @param seed Seed value for a sequence of random numbers /// @param n The number of random numbers to be generated /// @return sequence of random numbers /// @notice This function is used for recreating a sequence of numbers given /// seed generated in the previous function. function reproduceGaussianRandomNumbers(uint256 seed, uint256 n) public pure override returns(int256[] memory) { return _GaussianRNG(seed, n); } /// An internal function generating Gaussian random numbers /// @param seed Seed value for a sequence of random numbers /// @param n The number of random numbers to be generated /// @return sequence of random numbers function _GaussianRNG(uint256 seed, uint256 n) internal pure returns (int256[] memory) { uint256 _num = uint256(keccak256(abi.encodePacked(seed))); int256[] memory results = new int256[](n); for (uint256 i = 0; i < n; i++) { uint256 result = _countOnes(_num); results[i] = int256(result * 125) - 16000; _num = uint256(keccak256(abi.encodePacked(_num))); } return results; } /// A public function for counting number of 1s in the binary representation /// of a hashed value produced by the keccak256 hashing algorithm. /// @param n The number to be checked. /// @return count The number of 1's. function countOnes(uint256 n) public pure override returns (uint256) { return _countOnes(n); } /// An internal function in assembly to count number of 1's /// https://www.geeksforgeeks.org/count-set-bits-in-an-integer/ /// @param n The number to be checked. /// @return count The number of 1s. function _countOnes(uint256 n) internal pure returns (uint256 count) { assembly { for { } gt(n, 0) { } { n := and(n, sub(n, 1)) count := add(count, 1) } } } }
To reproduce Gaussian random numbers with a given seed seed Seed value for a sequence of random numbers n The number of random numbers to be generated return sequence of random numbers This function is used for recreating a sequence of numbers given seed generated in the previous function.
function reproduceGaussianRandomNumbers(uint256 seed, uint256 n) public pure override returns(int256[] memory) { return _GaussianRNG(seed, n); }
969,538
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract Pool is Initializable { string public constant name = "ETHPool"; bool private initialized; bool private stopped; address private owner; uint256 private rewardTime; uint256 private rewardAmount; uint256 private totalDeposited; DepositData[] private depositData; mapping(address => uint256) public balanceOf; struct DepositData { address user; uint256 amount; uint256 time; bool getReward; } event Deposit(address indexed user, uint256 amount, uint256 time); event Reward(uint256 amount, uint256 time); event Withdraw(address indexed user, uint256 amount, uint256 profits); /// @dev initialize contract function initialize() public initializer { require(!initialized, "already initialized"); initialized = true; stopped = false; owner = msg.sender; } modifier isNotStopped() { require(stopped == false, "stopped contract"); _; } modifier onlyOwner() { require(owner == msg.sender, "not owner"); _; } modifier onlyUser() { require(owner != msg.sender, "not user"); _; } /// @dev deposit eth to the pool function deposit() external payable isNotStopped onlyUser { // deposit amount should be greater than zero require(msg.value > 0, "can't be 0"); // add the deposit amount to the total and record the deposit amount totalDeposited += msg.value; depositData.push(DepositData({ user: msg.sender, amount: msg.value, time: block.timestamp, getReward: false })); // trigger deposit event emit Deposit(msg.sender, msg.value, block.timestamp); } /// @dev deposits reward eth to the pool function reward() external payable onlyOwner { // reward amount should be greater than zero require(msg.value > 0, "can't be 0"); // update rewards data rewardTime = block.timestamp; rewardAmount = msg.value; // trigger reward event emit Reward(msg.value, block.timestamp); } /// @dev withdraws balance from the pool function withdraw() external isNotStopped onlyUser { uint256 depositLength = depositData.length; uint256 depositAmount; uint256 totalAmount; DepositData memory bufData; for (uint256 i = 0; i < depositLength; i++) { bufData = depositData[i]; // skip if current user is not msg.sender or user has already been rewarded if (bufData.user != msg.sender || bufData.getReward) continue; // break the loop if deposit time is greater than reward time if (bufData.time > rewardTime) break; // add amount to total amount and set rewarded flag depositAmount += bufData.amount; depositData[i].getReward = true; } // deposit amount should be greater than zero require(depositAmount > 0, "nothing deposited"); // calculate user's profit totalAmount = depositAmount + (rewardAmount * depositAmount) / totalDeposited; // transfer eth to the user payable(msg.sender).transfer(totalAmount); // trigger withdraw event emit Withdraw(msg.sender, depositAmount, totalAmount); } /// @dev return all deposit history function depositHistory() external view isNotStopped returns(DepositData[] memory) { return depositData; } /// @dev return contract version function version() external virtual pure returns(string memory) { return "1.0.0"; } /// @dev toggle stopped status function toggleStopped() external onlyOwner { stopped = !stopped; } /// @dev get reward data function getRewardData() external view isNotStopped returns(uint256 time, uint256 amount) { return (rewardTime, rewardAmount); } }
initialize contract
function initialize() public initializer { require(!initialized, "already initialized"); initialized = true; stopped = false; owner = msg.sender; }
12,873,778
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @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: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @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/AddressUtils.sol pragma solidity ^0.4.24; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.4.24; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/interfaces/IBridgeValidators.sol pragma solidity 0.4.24; interface IBridgeValidators { function isValidator(address _validator) external view returns (bool); function requiredSignatures() external view returns (uint256); function owner() external view returns (address); } // File: contracts/upgradeable_contracts/ValidatorStorage.sol pragma solidity 0.4.24; contract ValidatorStorage { bytes32 internal constant VALIDATOR_CONTRACT = 0x5a74bb7e202fb8e4bf311841c7d64ec19df195fee77d7e7ae749b27921b6ddfe; // keccak256(abi.encodePacked("validatorContract")) } // File: contracts/upgradeable_contracts/Validatable.sol pragma solidity 0.4.24; contract Validatable is EternalStorage, ValidatorStorage { function validatorContract() public view returns (IBridgeValidators) { return IBridgeValidators(addressStorage[VALIDATOR_CONTRACT]); } modifier onlyValidator() { require(validatorContract().isValidator(msg.sender)); /* solcov ignore next */ _; } function requiredSignatures() public view returns (uint256) { return validatorContract().requiredSignatures(); } } // File: contracts/libraries/Message.sol pragma solidity 0.4.24; library Message { function addressArrayContains(address[] array, address value) internal pure returns (bool) { for (uint256 i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; } // layout of message :: bytes: // offset 0: 32 bytes :: uint256 - message length // offset 32: 20 bytes :: address - recipient address // offset 52: 32 bytes :: uint256 - value // offset 84: 32 bytes :: bytes32 - transaction hash // offset 116: 20 bytes :: address - contract address to prevent double spending // mload always reads 32 bytes. // so we can and have to start reading recipient at offset 20 instead of 32. // if we were to read at 32 the address would contain part of value and be corrupted. // when reading from offset 20 mload will read 12 bytes (most of them zeros) followed // by the 20 recipient address bytes and correctly convert it into an address. // this saves some storage/gas over the alternative solution // which is padding address to 32 bytes and reading recipient at offset 32. // for more details see discussion in: // https://github.com/paritytech/parity-bridge/issues/61 function parseMessage(bytes message) internal pure returns (address recipient, uint256 amount, bytes32 txHash, address contractAddress) { require(isMessageValid(message)); assembly { recipient := mload(add(message, 20)) amount := mload(add(message, 52)) txHash := mload(add(message, 84)) contractAddress := mload(add(message, 104)) } } function isMessageValid(bytes _msg) internal pure returns (bool) { return _msg.length == requiredMessageLength(); } function requiredMessageLength() internal pure returns (uint256) { return 104; } function recoverAddressFromSignedMessage(bytes signature, bytes message, bool isAMBMessage) internal pure returns (address) { require(signature.length == 65); bytes32 r; bytes32 s; bytes1 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := mload(add(signature, 0x60)) } require(uint8(v) == 27 || uint8(v) == 28); require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0); return ecrecover(hashMessage(message, isAMBMessage), uint8(v), r, s); } function hashMessage(bytes message, bool isAMBMessage) internal pure returns (bytes32) { bytes memory prefix = "\x19Ethereum Signed Message:\n"; if (isAMBMessage) { return keccak256(abi.encodePacked(prefix, uintToString(message.length), message)); } else { string memory msgLength = "104"; return keccak256(abi.encodePacked(prefix, msgLength, message)); } } /** * @dev Validates provided signatures, only first requiredSignatures() number * of signatures are going to be validated, these signatures should be from different validators. * @param _message bytes message used to generate signatures * @param _signatures bytes blob with signatures to be validated. * First byte X is a number of signatures in a blob, * next X bytes are v components of signatures, * next 32 * X bytes are r components of signatures, * next 32 * X bytes are s components of signatures. * @param _validatorContract contract, which conforms to the IBridgeValidators interface, * where info about current validators and required signatures is stored. * @param isAMBMessage true if _message is an AMB message with arbitrary length. */ function hasEnoughValidSignatures( bytes _message, bytes _signatures, IBridgeValidators _validatorContract, bool isAMBMessage ) internal view { require(isAMBMessage || isMessageValid(_message)); uint256 requiredSignatures = _validatorContract.requiredSignatures(); uint256 amount; assembly { amount := and(mload(add(_signatures, 1)), 0xff) } require(amount >= requiredSignatures); bytes32 hash = hashMessage(_message, isAMBMessage); address[] memory encounteredAddresses = new address[](requiredSignatures); for (uint256 i = 0; i < requiredSignatures; i++) { uint8 v; bytes32 r; bytes32 s; uint256 posr = 33 + amount + 32 * i; uint256 poss = posr + 32 * amount; assembly { v := mload(add(_signatures, add(2, i))) r := mload(add(_signatures, posr)) s := mload(add(_signatures, poss)) } address recoveredAddress = ecrecover(hash, v, r, s); require(_validatorContract.isValidator(recoveredAddress)); require(!addressArrayContains(encounteredAddresses, recoveredAddress)); encounteredAddresses[i] = recoveredAddress; } } function uintToString(uint256 i) internal pure returns (string) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = bytes1(48 + (i % 10)); i /= 10; } return string(bstr); } } // File: contracts/upgradeable_contracts/MessageRelay.sol pragma solidity 0.4.24; contract MessageRelay is EternalStorage { function relayedMessages(bytes32 _txHash) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))]; } function setRelayedMessages(bytes32 _txHash, bool _status) internal { boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))] = _status; } } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.4.24; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.4.24; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner()); /* solcov ignore next */ _; } } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.4.24; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/upgradeable_contracts/InitializableBridge.sol pragma solidity 0.4.24; contract InitializableBridge is Initializable { bytes32 internal constant DEPLOYED_AT_BLOCK = 0xb120ceec05576ad0c710bc6e85f1768535e27554458f05dcbb5c65b8c7a749b0; // keccak256(abi.encodePacked("deployedAtBlock")) function deployedAtBlock() external view returns (uint256) { return uintStorage[DEPLOYED_AT_BLOCK]; } } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.4.24; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @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 OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); /* solcov ignore next */ _; } /** * @dev Throws if called by any account other than contract itself or owner. */ modifier onlyRelevantSender() { // proxy owner if used through proxy, address(0) otherwise require( !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); /* solcov ignore next */ _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[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) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/upgradeable_contracts/Sacrifice.sol pragma solidity 0.4.24; contract Sacrifice { constructor(address _recipient) public payable { selfdestruct(_recipient); } } // File: contracts/libraries/Address.sol pragma solidity 0.4.24; /** * @title Address * @dev Helper methods for Address type. */ library Address { /** * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract * @param _receiver address that will receive the native tokens * @param _value the amount of native tokens to send */ function safeSendValue(address _receiver, uint256 _value) internal { if (!_receiver.send(_value)) { (new Sacrifice).value(_value)(_receiver); } } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol 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; } } // File: contracts/interfaces/ERC677.sol pragma solidity 0.4.24; contract ERC677 is ERC20 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall(address, uint256, bytes) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) public returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool); } contract LegacyERC20 { function transfer(address _spender, uint256 _value) public; // returns (bool); function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool); } // File: contracts/libraries/SafeERC20.sol pragma solidity 0.4.24; /** * @title SafeERC20 * @dev Helper methods for safe token transfers. * Functions perform additional checks to be sure that token transfer really happened. */ library SafeERC20 { using SafeMath for uint256; /** * @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _to address of the receiver * @param _value amount of tokens to send */ function safeTransfer(address _token, address _to, uint256 _value) internal { LegacyERC20(_token).transfer(_to, _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } /** * @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _from address of the sender * @param _value amount of tokens to send */ function safeTransferFrom(address _token, address _from, uint256 _value) internal { LegacyERC20(_token).transferFrom(_from, address(this), _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } } // File: contracts/upgradeable_contracts/Claimable.sol pragma solidity 0.4.24; /** * @title Claimable * @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations. */ contract Claimable { using SafeERC20 for address; /** * Throws if a given address is equal to address(0) */ modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimValues(address _token, address _to) internal validAddress(_to) { if (_token == address(0)) { claimNativeCoins(_to); } else { claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function claimNativeCoins(address _to) internal { uint256 value = address(this).balance; Address.safeSendValue(_to, value); } /** * @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function claimErc20Tokens(address _token, address _to) internal { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); _token.safeTransfer(_to, balance); } } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.4.24; contract VersionableBridge { function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (6, 1, 0); } /* solcov ignore next */ function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/DecimalShiftBridge.sol pragma solidity 0.4.24; contract DecimalShiftBridge is EternalStorage { using SafeMath for uint256; bytes32 internal constant DECIMAL_SHIFT = 0x1e8ecaafaddea96ed9ac6d2642dcdfe1bebe58a930b1085842d8fc122b371ee5; // keccak256(abi.encodePacked("decimalShift")) /** * @dev Internal function for setting the decimal shift for bridge operations. * Decimal shift can be positive, negative, or equal to zero. * It has the following meaning: N tokens in the foreign chain are equivalent to N * pow(10, shift) tokens on the home side. * @param _shift new value of decimal shift. */ function _setDecimalShift(int256 _shift) internal { // since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values require(_shift > -77 && _shift < 77); uintStorage[DECIMAL_SHIFT] = uint256(_shift); } /** * @dev Returns the value of foreign-to-home decimal shift. * @return decimal shift. */ function decimalShift() public view returns (int256) { return int256(uintStorage[DECIMAL_SHIFT]); } /** * @dev Converts the amount of home tokens into the equivalent amount of foreign tokens. * @param _value amount of home tokens. * @return equivalent amount of foreign tokens. */ function _unshiftValue(uint256 _value) internal view returns (uint256) { return _shiftUint(_value, -decimalShift()); } /** * @dev Converts the amount of foreign tokens into the equivalent amount of home tokens. * @param _value amount of foreign tokens. * @return equivalent amount of home tokens. */ function _shiftValue(uint256 _value) internal view returns (uint256) { return _shiftUint(_value, decimalShift()); } /** * @dev Calculates _value * pow(10, _shift). * @param _value amount of tokens. * @param _shift decimal shift to apply. * @return shifted value. */ function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) { if (_shift == 0) { return _value; } if (_shift > 0) { return _value.mul(10**uint256(_shift)); } return _value.div(10**uint256(-_shift)); } } // File: contracts/upgradeable_contracts/BasicBridge.sol pragma solidity 0.4.24; contract BasicBridge is InitializableBridge, Validatable, Ownable, Upgradeable, Claimable, VersionableBridge, DecimalShiftBridge { event GasPriceChanged(uint256 gasPrice); event RequiredBlockConfirmationChanged(uint256 requiredBlockConfirmations); bytes32 internal constant GAS_PRICE = 0x55b3774520b5993024893d303890baa4e84b1244a43c60034d1ced2d3cf2b04b; // keccak256(abi.encodePacked("gasPrice")) bytes32 internal constant REQUIRED_BLOCK_CONFIRMATIONS = 0x916daedf6915000ff68ced2f0b6773fe6f2582237f92c3c95bb4d79407230071; // keccak256(abi.encodePacked("requiredBlockConfirmations")) /** * @dev Public setter for fallback gas price value. Only bridge owner can call this method. * @param _gasPrice new value for the gas price. */ function setGasPrice(uint256 _gasPrice) external onlyOwner { _setGasPrice(_gasPrice); } function gasPrice() external view returns (uint256) { return uintStorage[GAS_PRICE]; } function setRequiredBlockConfirmations(uint256 _blockConfirmations) external onlyOwner { _setRequiredBlockConfirmations(_blockConfirmations); } function _setRequiredBlockConfirmations(uint256 _blockConfirmations) internal { require(_blockConfirmations > 0); uintStorage[REQUIRED_BLOCK_CONFIRMATIONS] = _blockConfirmations; emit RequiredBlockConfirmationChanged(_blockConfirmations); } function requiredBlockConfirmations() external view returns (uint256) { return uintStorage[REQUIRED_BLOCK_CONFIRMATIONS]; } /** * @dev Internal function for updating fallback gas price value. * @param _gasPrice new value for the gas price, zero gas price is allowed. */ function _setGasPrice(uint256 _gasPrice) internal { uintStorage[GAS_PRICE] = _gasPrice; emit GasPriceChanged(_gasPrice); } } // File: contracts/upgradeable_contracts/BasicTokenBridge.sol pragma solidity 0.4.24; contract BasicTokenBridge is EternalStorage, Ownable, DecimalShiftBridge { using SafeMath for uint256; event DailyLimitChanged(uint256 newLimit); event ExecutionDailyLimitChanged(uint256 newLimit); bytes32 internal constant MIN_PER_TX = 0xbbb088c505d18e049d114c7c91f11724e69c55ad6c5397e2b929e68b41fa05d1; // keccak256(abi.encodePacked("minPerTx")) bytes32 internal constant MAX_PER_TX = 0x0f8803acad17c63ee38bf2de71e1888bc7a079a6f73658e274b08018bea4e29c; // keccak256(abi.encodePacked("maxPerTx")) bytes32 internal constant DAILY_LIMIT = 0x4a6a899679f26b73530d8cf1001e83b6f7702e04b6fdb98f3c62dc7e47e041a5; // keccak256(abi.encodePacked("dailyLimit")) bytes32 internal constant EXECUTION_MAX_PER_TX = 0xc0ed44c192c86d1cc1ba51340b032c2766b4a2b0041031de13c46dd7104888d5; // keccak256(abi.encodePacked("executionMaxPerTx")) bytes32 internal constant EXECUTION_DAILY_LIMIT = 0x21dbcab260e413c20dc13c28b7db95e2b423d1135f42bb8b7d5214a92270d237; // keccak256(abi.encodePacked("executionDailyLimit")) function totalSpentPerDay(uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))]; } function totalExecutedPerDay(uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))]; } function dailyLimit() public view returns (uint256) { return uintStorage[DAILY_LIMIT]; } function executionDailyLimit() public view returns (uint256) { return uintStorage[EXECUTION_DAILY_LIMIT]; } function maxPerTx() public view returns (uint256) { return uintStorage[MAX_PER_TX]; } function executionMaxPerTx() public view returns (uint256) { return uintStorage[EXECUTION_MAX_PER_TX]; } function minPerTx() public view returns (uint256) { return uintStorage[MIN_PER_TX]; } function withinLimit(uint256 _amount) public view returns (bool) { uint256 nextLimit = totalSpentPerDay(getCurrentDay()).add(_amount); return dailyLimit() >= nextLimit && _amount <= maxPerTx() && _amount >= minPerTx(); } function withinExecutionLimit(uint256 _amount) public view returns (bool) { uint256 nextLimit = totalExecutedPerDay(getCurrentDay()).add(_amount); return executionDailyLimit() >= nextLimit && _amount <= executionMaxPerTx(); } function getCurrentDay() public view returns (uint256) { return now / 1 days; } function addTotalSpentPerDay(uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))] = totalSpentPerDay(_day).add(_value); } function addTotalExecutedPerDay(uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))] = totalExecutedPerDay(_day).add(_value); } function setDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit > maxPerTx() || _dailyLimit == 0); uintStorage[DAILY_LIMIT] = _dailyLimit; emit DailyLimitChanged(_dailyLimit); } function setExecutionDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit > executionMaxPerTx() || _dailyLimit == 0); uintStorage[EXECUTION_DAILY_LIMIT] = _dailyLimit; emit ExecutionDailyLimitChanged(_dailyLimit); } function setExecutionMaxPerTx(uint256 _maxPerTx) external onlyOwner { require(_maxPerTx < executionDailyLimit()); uintStorage[EXECUTION_MAX_PER_TX] = _maxPerTx; } function setMaxPerTx(uint256 _maxPerTx) external onlyOwner { require(_maxPerTx == 0 || (_maxPerTx > minPerTx() && _maxPerTx < dailyLimit())); uintStorage[MAX_PER_TX] = _maxPerTx; } function setMinPerTx(uint256 _minPerTx) external onlyOwner { require(_minPerTx > 0 && _minPerTx < dailyLimit() && _minPerTx < maxPerTx()); uintStorage[MIN_PER_TX] = _minPerTx; } /** * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters. * @return minimum of maxPerTx parameter and remaining daily quota. */ function maxAvailablePerTx() public view returns (uint256) { uint256 _maxPerTx = maxPerTx(); uint256 _dailyLimit = dailyLimit(); uint256 _spent = totalSpentPerDay(getCurrentDay()); uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0; return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily; } function _setLimits(uint256[3] _limits) internal { require( _limits[2] > 0 && // minPerTx > 0 _limits[1] > _limits[2] && // maxPerTx > minPerTx _limits[0] > _limits[1] // dailyLimit > maxPerTx ); uintStorage[DAILY_LIMIT] = _limits[0]; uintStorage[MAX_PER_TX] = _limits[1]; uintStorage[MIN_PER_TX] = _limits[2]; emit DailyLimitChanged(_limits[0]); } function _setExecutionLimits(uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[EXECUTION_DAILY_LIMIT] = _limits[0]; uintStorage[EXECUTION_MAX_PER_TX] = _limits[1]; emit ExecutionDailyLimitChanged(_limits[0]); } } // File: contracts/upgradeable_contracts/BasicForeignBridge.sol pragma solidity 0.4.24; contract BasicForeignBridge is EternalStorage, Validatable, BasicBridge, BasicTokenBridge, MessageRelay { /// triggered when relay of deposit from HomeBridge is complete event RelayedMessage(address recipient, uint256 value, bytes32 transactionHash); event UserRequestForAffirmation(address recipient, uint256 value); /** * @dev Validates provided signatures and relays a given message * @param message bytes to be relayed * @param signatures bytes blob with signatures to be validated */ function executeSignatures(bytes message, bytes signatures) external { Message.hasEnoughValidSignatures(message, signatures, validatorContract(), false); address recipient; uint256 amount; bytes32 txHash; address contractAddress; (recipient, amount, txHash, contractAddress) = Message.parseMessage(message); if (withinExecutionLimit(amount)) { require(contractAddress == address(this)); require(!relayedMessages(txHash)); setRelayedMessages(txHash, true); require(onExecuteMessage(recipient, amount, txHash)); emit RelayedMessage(recipient, amount, txHash); } else { onFailedMessage(recipient, amount, txHash); } } /** * @dev Internal function for updating fallback gas price value. * @param _gasPrice new value for the gas price, zero gas price is not allowed. */ function _setGasPrice(uint256 _gasPrice) internal { require(_gasPrice > 0); super._setGasPrice(_gasPrice); } /* solcov ignore next */ function onExecuteMessage(address, uint256, bytes32) internal returns (bool); /* solcov ignore next */ function onFailedMessage(address, uint256, bytes32) internal; } // File: contracts/upgradeable_contracts/ERC20Bridge.sol pragma solidity 0.4.24; contract ERC20Bridge is BasicForeignBridge { bytes32 internal constant ERC20_TOKEN = 0x15d63b18dbc21bf4438b7972d80076747e1d93c4f87552fe498c90cbde51665e; // keccak256(abi.encodePacked("erc20token")) function erc20token() public view returns (ERC20) { return ERC20(addressStorage[ERC20_TOKEN]); } function setErc20token(address _token) internal { require(AddressUtils.isContract(_token)); addressStorage[ERC20_TOKEN] = _token; } function relayTokens(address _receiver, uint256 _amount) external { require(_receiver != address(0)); require(_receiver != address(this)); require(_amount > 0); require(withinLimit(_amount)); addTotalSpentPerDay(getCurrentDay(), _amount); erc20token().transferFrom(msg.sender, address(this), _amount); emit UserRequestForAffirmation(_receiver, _amount); } } // File: contracts/upgradeable_contracts/OtherSideBridgeStorage.sol pragma solidity 0.4.24; contract OtherSideBridgeStorage is EternalStorage { bytes32 internal constant BRIDGE_CONTRACT = 0x71483949fe7a14d16644d63320f24d10cf1d60abecc30cc677a340e82b699dd2; // keccak256(abi.encodePacked("bridgeOnOtherSide")) function _setBridgeContractOnOtherSide(address _bridgeContract) internal { require(_bridgeContract != address(0)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } function bridgeContractOnOtherSide() internal view returns (address) { return addressStorage[BRIDGE_CONTRACT]; } } // File: contracts/upgradeable_contracts/erc20_to_native/ForeignBridgeErcToNative.sol pragma solidity 0.4.24; contract ForeignBridgeErcToNative is ERC20Bridge, OtherSideBridgeStorage { function initialize( address _validatorContract, address _erc20token, uint256 _requiredBlockConfirmations, uint256 _gasPrice, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _homeDailyLimitHomeMaxPerTxArray, //[ 0 = _homeDailyLimit, 1 = _homeMaxPerTx ] address _owner, int256 _decimalShift, address _bridgeOnOtherSide ) external onlyRelevantSender returns (bool) { require(!isInitialized()); require(AddressUtils.isContract(_validatorContract)); addressStorage[VALIDATOR_CONTRACT] = _validatorContract; setErc20token(_erc20token); uintStorage[DEPLOYED_AT_BLOCK] = block.number; _setRequiredBlockConfirmations(_requiredBlockConfirmations); _setGasPrice(_gasPrice); _setLimits(_dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(_homeDailyLimitHomeMaxPerTxArray); _setDecimalShift(_decimalShift); _setOwner(_owner); _setBridgeContractOnOtherSide(_bridgeOnOtherSide); setInitialize(); return isInitialized(); } function getBridgeMode() external pure returns (bytes4 _data) { return 0x18762d46; // bytes4(keccak256(abi.encodePacked("erc-to-native-core"))) } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Since bridged tokens are locked at this contract, it is not allowed to claim them with the use of claimTokens function require(_token != address(erc20token())); claimValues(_token, _to); } function onExecuteMessage( address _recipient, uint256 _amount, bytes32 /*_txHash*/ ) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), _amount); return erc20token().transfer(_recipient, _unshiftValue(_amount)); } function onFailedMessage(address, uint256, bytes32) internal { revert(); } function relayTokens(address _receiver, uint256 _amount) external { require(_receiver != bridgeContractOnOtherSide()); require(_receiver != address(0)); require(_receiver != address(this)); require(_amount > 0); require(withinLimit(_amount)); addTotalSpentPerDay(getCurrentDay(), _amount); erc20token().transferFrom(msg.sender, address(this), _amount); emit UserRequestForAffirmation(_receiver, _amount); } } // File: contracts/interfaces/IInterestReceiver.sol pragma solidity 0.4.24; interface IInterestReceiver { function onInterestReceived(address _token) external; } // File: contracts/upgradeable_contracts/erc20_to_native/InterestConnector.sol pragma solidity 0.4.24; /** * @title InterestConnector * @dev This contract gives an abstract way of receiving interest on locked tokens. */ contract InterestConnector is Ownable, ERC20Bridge { event PaidInterest(address indexed token, address to, uint256 value); /** * @dev Throws if interest is bearing not enabled. * @param token address, for which interest should be enabled. */ modifier interestEnabled(address token) { require(isInterestEnabled(token)); /* solcov ignore next */ _; } /** * @dev Ensures that caller is an EOA. * Functions with such modifier cannot be called from other contract (as well as from GSN-like approaches) */ modifier onlyEOA { // solhint-disable-next-line avoid-tx-origin require(msg.sender == tx.origin); /* solcov ignore next */ _; } /** * @dev Tells if interest earning was enabled for particular token. * @return true, if interest bearing is enabled. */ function isInterestEnabled(address _token) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("interestEnabled", _token))]; } /** * @dev Initializes interest receiving functionality. * Only owner can call this method. * @param _token address of the token for interest earning. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. * @param _minInterestPaid minimum amount of interest that can be paid in a single call. */ function initializeInterest( address _token, uint256 _minCashThreshold, uint256 _minInterestPaid, address _interestReceiver ) external onlyOwner { require(_isInterestSupported(_token)); require(!isInterestEnabled(_token)); _setInterestEnabled(_token, true); _setMinCashThreshold(_token, _minCashThreshold); _setMinInterestPaid(_token, _minInterestPaid); _setInterestReceiver(_token, _interestReceiver); } /** * @dev Sets minimum amount of tokens that cannot be invested. * Only owner can call this method. * @param _token address of the token contract. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. */ function setMinCashThreshold(address _token, uint256 _minCashThreshold) external onlyOwner { _setMinCashThreshold(_token, _minCashThreshold); } /** * @dev Tells minimum amount of tokens that are not being invested. * @param _token address of the invested token contract. * @return amount of tokens. */ function minCashThreshold(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minCashThreshold", _token))]; } /** * @dev Sets lower limit for the paid interest amount. * Only owner can call this method. * @param _token address of the token contract. * @param _minInterestPaid minimum amount of interest paid in a single call. */ function setMinInterestPaid(address _token, uint256 _minInterestPaid) external onlyOwner { _setMinInterestPaid(_token, _minInterestPaid); } /** * @dev Tells minimum amount of paid interest in a single call. * @param _token address of the invested token contract. * @return paid interest minimum limit. */ function minInterestPaid(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minInterestPaid", _token))]; } /** * @dev Internal function that disables interest for locked funds. * Only owner can call this method. * @param _token of token to disable interest for. */ function disableInterest(address _token) external onlyOwner { _withdraw(_token, uint256(-1)); _setInterestEnabled(_token, false); } /** * @dev Tells configured address of the interest receiver. * @param _token address of the invested token contract. * @return address of the interest receiver. */ function interestReceiver(address _token) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("interestReceiver", _token))]; } /** * Updates the interest receiver address. * Only owner can call this method. * @param _token address of the invested token contract. * @param _receiver new receiver address. */ function setInterestReceiver(address _token, address _receiver) external onlyOwner { _setInterestReceiver(_token, _receiver); } /** * @dev Pays collected interest for the specific underlying token. * Requires interest for the given token to be enabled. * @param _token address of the token contract. */ function payInterest(address _token) external onlyEOA interestEnabled(_token) { uint256 interest = interestAmount(_token); require(interest >= minInterestPaid(_token)); uint256 redeemed = _safeWithdrawTokens(_token, interest); _transferInterest(_token, redeemed); } /** * @dev Tells the amount of underlying tokens that are currently invested. * @param _token address of the token contract. * @return amount of underlying tokens. */ function investedAmount(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("investedAmount", _token))]; } /** * @dev Invests all excess tokens. * Requires interest for the given token to be enabled. * @param _token address of the token contract considered. */ function invest(address _token) public interestEnabled(_token) { uint256 balance = _selfBalance(_token); uint256 minCash = minCashThreshold(_token); require(balance > minCash); uint256 amount = balance - minCash; _setInvestedAmount(_token, investedAmount(_token).add(amount)); _invest(_token, amount); } /** * @dev Internal function for transferring interest. * Calls a callback on the receiver, if it is a contract. * @param _token address of the underlying token contract. * @param _amount amount of collected tokens that should be sent. */ function _transferInterest(address _token, uint256 _amount) internal { address receiver = interestReceiver(_token); require(receiver != address(0)); ERC20(_token).transfer(receiver, _amount); if (AddressUtils.isContract(receiver)) { IInterestReceiver(receiver).onInterestReceived(_token); } emit PaidInterest(_token, receiver, _amount); } /** * @dev Internal function for setting interest enabled flag for some token. * @param _token address of the token contract. * @param _enabled true to enable interest earning, false to disable. */ function _setInterestEnabled(address _token, bool _enabled) internal { boolStorage[keccak256(abi.encodePacked("interestEnabled", _token))] = _enabled; } /** * @dev Internal function for setting the amount of underlying tokens that are currently invested. * @param _token address of the token contract. * @param _amount new amount of invested tokens. */ function _setInvestedAmount(address _token, uint256 _amount) internal { uintStorage[keccak256(abi.encodePacked("investedAmount", _token))] = _amount; } /** * @dev Internal function for withdrawing some amount of the invested tokens. * Reverts if given amount cannot be withdrawn. * @param _token address of the token contract withdrawn. * @param _amount amount of requested tokens to be withdrawn. */ function _withdraw(address _token, uint256 _amount) internal { if (_amount == 0) return; uint256 invested = investedAmount(_token); uint256 withdrawal = _amount > invested ? invested : _amount; uint256 redeemed = _safeWithdrawTokens(_token, withdrawal); _setInvestedAmount(_token, invested > redeemed ? invested - redeemed : 0); } /** * @dev Internal function for safe withdrawal of invested tokens. * Reverts if given amount cannot be withdrawn. * Additionally verifies that at least _amount of tokens were withdrawn. * @param _token address of the token contract withdrawn. * @param _amount amount of requested tokens to be withdrawn. */ function _safeWithdrawTokens(address _token, uint256 _amount) private returns (uint256) { uint256 balance = _selfBalance(_token); _withdrawTokens(_token, _amount); uint256 redeemed = _selfBalance(_token) - balance; require(redeemed >= _amount); return redeemed; } /** * @dev Internal function for setting minimum amount of tokens that cannot be invested. * @param _token address of the token contract. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. */ function _setMinCashThreshold(address _token, uint256 _minCashThreshold) internal { uintStorage[keccak256(abi.encodePacked("minCashThreshold", _token))] = _minCashThreshold; } /** * @dev Internal function for setting lower limit for paid interest amount. * @param _token address of the token contract. * @param _minInterestPaid minimum amount of interest paid in a single call. */ function _setMinInterestPaid(address _token, uint256 _minInterestPaid) internal { uintStorage[keccak256(abi.encodePacked("minInterestPaid", _token))] = _minInterestPaid; } /** * @dev Internal function for setting interest receiver address. * @param _token address of the invested token contract. * @param _receiver address of the interest receiver. */ function _setInterestReceiver(address _token, address _receiver) internal { require(_receiver != address(this)); addressStorage[keccak256(abi.encodePacked("interestReceiver", _token))] = _receiver; } /** * @dev Tells this contract balance of some specific token contract * @param _token address of the token contract. * @return contract balance. */ function _selfBalance(address _token) internal view returns (uint256) { return ERC20(_token).balanceOf(address(this)); } function _isInterestSupported(address _token) internal pure returns (bool); function _invest(address _token, uint256 _amount) internal; function _withdrawTokens(address _token, uint256 _amount) internal; function interestAmount(address _token) public view returns (uint256); } // File: contracts/interfaces/ICToken.sol pragma solidity 0.4.24; interface ICToken { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function balanceOf(address account) external view returns (uint256); function balanceOfUnderlying(address account) external view returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 borrowAmount) external returns (uint256); } // File: contracts/interfaces/IComptroller.sol pragma solidity 0.4.24; interface IComptroller { function claimComp(address[] holders, address[] cTokens, bool borrowers, bool suppliers) external; } // File: contracts/upgradeable_contracts/erc20_to_native/CompoundConnector.sol pragma solidity 0.4.24; /** * @title CompoundConnector * @dev This contract allows to partially invest locked Dai tokens into Compound protocol. */ contract CompoundConnector is InterestConnector { uint256 internal constant SUCCESS = 0; /** * @dev Tells the address of the DAI token in the Ethereum Mainnet. */ function daiToken() public pure returns (ERC20) { return ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); } /** * @dev Tells the address of the cDAI token in the Ethereum Mainnet. */ function cDaiToken() public pure returns (ICToken) { return ICToken(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); } /** * @dev Tells the address of the Comptroller contract in the Ethereum Mainnet. */ function comptroller() public pure returns (IComptroller) { return IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); } /** * @dev Tells the address of the COMP token in the Ethereum Mainnet. */ function compToken() public pure returns (ERC20) { return ERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); } /** * @dev Tells the current earned interest amount. * @param _token address of the underlying token contract. * @return total amount of interest that can be withdrawn now. */ function interestAmount(address _token) public view returns (uint256) { uint256 underlyingBalance = cDaiToken().balanceOfUnderlying(address(this)); // 1 DAI is reserved for possible truncation/round errors uint256 invested = investedAmount(_token) + 1 ether; return underlyingBalance > invested ? underlyingBalance - invested : 0; } /** * @dev Tells if interest earning is supported for the specific token contract. * @param _token address of the token contract. * @return true, if interest earning is supported. */ function _isInterestSupported(address _token) internal pure returns (bool) { return _token == address(daiToken()); } /** * @dev Invests the given amount of tokens to the Compound protocol. * Converts _amount of TOKENs into X cTOKENs. * @param _token address of the token contract. * @param _amount amount of tokens to invest. */ function _invest(address _token, uint256 _amount) internal { (_token); daiToken().approve(address(cDaiToken()), _amount); require(cDaiToken().mint(_amount) == SUCCESS); } /** * @dev Withdraws at least the given amount of tokens from the Compound protocol. * Converts X cTOKENs into _amount of TOKENs. * @param _token address of the token contract. * @param _amount minimal amount of tokens to withdraw. */ function _withdrawTokens(address _token, uint256 _amount) internal { (_token); require(cDaiToken().redeemUnderlying(_amount) == SUCCESS); } /** * @dev Claims Comp token and transfers it to the associated interest receiver. */ function claimCompAndPay() external onlyEOA { address[] memory holders = new address[](1); holders[0] = address(this); address[] memory markets = new address[](1); markets[0] = address(cDaiToken()); comptroller().claimComp(holders, markets, false, true); address comp = address(compToken()); uint256 interest = _selfBalance(comp); require(interest >= minInterestPaid(comp)); _transferInterest(comp, interest); } } // File: contracts/gsn/interfaces/IRelayRecipient.sol // SPDX-License-Identifier:MIT pragma solidity 0.4.24; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public view returns (bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view returns (address); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal view returns (bytes memory); function versionRecipient() external view returns (string memory); } // File: contracts/gsn/BaseRelayRecipient.sol // SPDX-License-Identifier:MIT // solhint-disable no-inline-assembly pragma solidity 0.4.24; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ contract BaseRelayRecipient is IRelayRecipient { /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view returns (address ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96, calldataload(sub(calldatasize, 20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // we copy the msg.data , except the last 20 bytes (and update the total length) assembly { let ptr := mload(0x40) // copy only size-20 bytes let size := sub(calldatasize, 20) // structure RLP data as <offset> <length> <bytes> mstore(ptr, 0x20) mstore(add(ptr, 32), size) calldatacopy(add(ptr, 64), 0, size) return(ptr, add(size, 64)) } } else { return msg.data; } } } // File: contracts/gsn/interfaces/IKnowForwarderAddress.sol // SPDX-License-Identifier:MIT pragma solidity 0.4.24; interface IKnowForwarderAddress { /** * return the forwarder we trust to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function getTrustedForwarder() external view returns (address); } // File: contracts/upgradeable_contracts/GSNForeignERC20Bridge.sol pragma solidity 0.4.24; contract GSNForeignERC20Bridge is BasicForeignBridge, ERC20Bridge, BaseRelayRecipient, IKnowForwarderAddress { bytes32 internal constant PAYMASTER = 0xfefcc139ed357999ed60c6a013947328d52e7d9751e93fd0274a2bfae5cbcb12; // keccak256(abi.encodePacked("paymaster")) bytes32 internal constant TRUSTED_FORWARDER = 0x222cb212229f0f9bcd249029717af6845ea3d3a84f22b54e5744ac25ef224c92; // keccak256(abi.encodePacked("trustedForwarder")) function versionRecipient() external view returns (string memory) { return "1.0.1"; } function getTrustedForwarder() external view returns (address) { return addressStorage[TRUSTED_FORWARDER]; } function setTrustedForwarder(address _trustedForwarder) public onlyOwner { addressStorage[TRUSTED_FORWARDER] = _trustedForwarder; } function isTrustedForwarder(address forwarder) public view returns (bool) { return forwarder == addressStorage[TRUSTED_FORWARDER]; } function setPayMaster(address _paymaster) public onlyOwner { addressStorage[PAYMASTER] = _paymaster; } /** * @param message same as in `executeSignatures` * @param signatures same as in `executeSignatures` * @param maxTokensFee maximum amount of foreign tokens that user allows to take * as a commission */ function executeSignaturesGSN(bytes message, bytes signatures, uint256 maxTokensFee) external { // Allow only forwarder calls require(isTrustedForwarder(msg.sender), "invalid forwarder"); Message.hasEnoughValidSignatures(message, signatures, validatorContract(), false); address recipient; uint256 amount; bytes32 txHash; address contractAddress; (recipient, amount, txHash, contractAddress) = Message.parseMessage(message); if (withinExecutionLimit(amount)) { require(maxTokensFee <= amount); require(contractAddress == address(this)); require(!relayedMessages(txHash)); setRelayedMessages(txHash, true); require(onExecuteMessageGSN(recipient, amount, maxTokensFee)); emit RelayedMessage(recipient, amount, txHash); } else { onFailedMessage(recipient, amount, txHash); } } function onExecuteMessageGSN(address recipient, uint256 amount, uint256 fee) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), amount); // Send maxTokensFee to paymaster ERC20 token = erc20token(); bool first = token.transfer(addressStorage[PAYMASTER], fee); bool second = token.transfer(recipient, amount - fee); return first && second; } } // File: contracts/upgradeable_contracts/erc20_to_native/XDaiForeignBridge.sol pragma solidity 0.4.24; contract XDaiForeignBridge is ForeignBridgeErcToNative, CompoundConnector, GSNForeignERC20Bridge { function initialize( address _validatorContract, address _erc20token, uint256 _requiredBlockConfirmations, uint256 _gasPrice, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _homeDailyLimitHomeMaxPerTxArray, //[ 0 = _homeDailyLimit, 1 = _homeMaxPerTx ] address _owner, int256 _decimalShift, address _bridgeOnOtherSide ) external onlyRelevantSender returns (bool) { require(!isInitialized()); require(AddressUtils.isContract(_validatorContract)); require(_erc20token == address(daiToken())); require(_decimalShift == 0); addressStorage[VALIDATOR_CONTRACT] = _validatorContract; uintStorage[DEPLOYED_AT_BLOCK] = block.number; _setRequiredBlockConfirmations(_requiredBlockConfirmations); _setGasPrice(_gasPrice); _setLimits(_dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(_homeDailyLimitHomeMaxPerTxArray); _setOwner(_owner); _setBridgeContractOnOtherSide(_bridgeOnOtherSide); setInitialize(); return isInitialized(); } function erc20token() public view returns (ERC20) { return daiToken(); } // selector 6a641d80 function migrateTo_6_1_0(address _interestReceiver) external { bytes32 upgradeStorage = 0x6a641d806674d4ce5e98c8fdab48e66c563660255f099d81d45fa2fe8ed9cc1d; // keccak256(abi.encodePacked('migrateTo_6_1_0(address)')) require(!boolStorage[upgradeStorage]); address dai = address(daiToken()); address comp = address(compToken()); _setInterestEnabled(dai, true); _setMinCashThreshold(dai, 1000000 ether); _setMinInterestPaid(dai, 1000 ether); _setInterestReceiver(dai, _interestReceiver); _setMinInterestPaid(comp, 1 ether); _setInterestReceiver(comp, _interestReceiver); invest(dai); boolStorage[upgradeStorage] = true; } function investDai() external { invest(address(daiToken())); } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Since bridged tokens are locked at this contract, it is not allowed to claim them with the use of claimTokens function address bridgedToken = address(daiToken()); require(_token != address(bridgedToken)); require(_token != address(cDaiToken()) || !isInterestEnabled(bridgedToken)); require(_token != address(compToken()) || !isInterestEnabled(bridgedToken)); claimValues(_token, _to); } function onExecuteMessage( address _recipient, uint256 _amount, bytes32 /*_txHash*/ ) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), _amount); ERC20 token = daiToken(); ensureEnoughTokens(token, _amount); return token.transfer(_recipient, _amount); } function onExecuteMessageGSN(address recipient, uint256 amount, uint256 fee) internal returns (bool) { ensureEnoughTokens(daiToken(), amount); return super.onExecuteMessageGSN(recipient, amount, fee); } function ensureEnoughTokens(ERC20 token, uint256 amount) internal { uint256 currentBalance = token.balanceOf(address(this)); if (currentBalance < amount) { uint256 withdrawAmount = (amount - currentBalance).add(minCashThreshold(address(token))); _withdraw(address(token), withdrawAmount); } } }
Internal function for withdrawing some amount of the invested tokens. Reverts if given amount cannot be withdrawn. _token address of the token contract withdrawn. _amount amount of requested tokens to be withdrawn./
function _withdraw(address _token, uint256 _amount) internal { if (_amount == 0) return; uint256 invested = investedAmount(_token); uint256 withdrawal = _amount > invested ? invested : _amount; uint256 redeemed = _safeWithdrawTokens(_token, withdrawal); _setInvestedAmount(_token, invested > redeemed ? invested - redeemed : 0); }
1,093,418
pragma solidity ^0.4.23; contract fileSale { uint constant depth = 14; uint constant length = 2; uint constant n = 16384; enum stage {created, initialized, accepted, keyRevealed, finished} stage public phase = stage.created; uint public timeout; address sender; address receiver; uint price = 100; // in wei bytes32 keyCommit ; bytes32 ciphertextRoot ; bytes32 fileRoot ; bytes32 public key; // function modifier to only allow calling the function in the right phase only from the correct party modifier allowed(address p, stage s) { require(phase == s); require(now < timeout); require(msg.sender == p); _; } // go to next phase function nextStage() internal { phase = stage(uint(phase) + 1); timeout = now + 10 minutes; } // constructor is initialize function function ininitialize (address _receiver, uint _price, bytes32 _keyCommit, bytes32 _ciphertextRoot, bytes32 _fileRoot) public { require(phase == stage.created); receiver = _receiver; sender = msg.sender; price = _price; keyCommit = _keyCommit; ciphertextRoot = _ciphertextRoot; fileRoot = _fileRoot; nextStage(); } // function accept function accept () allowed(receiver, stage.initialized) payable public { require (msg.value >= price); nextStage(); } // function revealKey (key) function revealKey (bytes32 _key) allowed(sender, stage.accepted) public { require(keyCommit == keccak256(_key)); key = _key; nextStage(); } // function complain about wrong hash of file function noComplain () allowed(receiver, stage.keyRevealed) public { sender.call.value(price); phase = stage.created; } // function complain about wrong hash of file function complainAboutRoot (bytes32 _Zm, bytes32[depth] _proofZm) allowed( receiver, stage.keyRevealed) public { require (vrfy(2*(n-1), _Zm, _proofZm)); if (cryptSmall(2*(n-1), _Zm) != fileRoot){ receiver.call.value(price); phase = stage.created; } } // function complain about wrong hash of two inputs function complainAboutLeaf (uint _indexOut, uint _indexIn, bytes32 _Zout, bytes32[length] _Zin1, bytes32[length] _Zin2, bytes32[depth] _proofZout, bytes32[depth] _proofZin) allowed( receiver, stage.keyRevealed) public { require (vrfy(_indexOut, _Zout, _proofZout)); bytes32 Xout = cryptSmall(_indexOut, _Zout); require (vrfy(_indexIn, keccak256(_Zin1), _proofZin)); require (_proofZin[0] == keccak256(_Zin2)); if (Xout != keccak256(cryptLarge(_indexIn, _Zin1), cryptLarge(_indexIn+1, _Zin2))) { receiver.call.value(price); phase = stage.created; } } // function complain about wrong hash of two inputs function complainAboutNode (uint _indexOut, uint _indexIn, bytes32 _Zout, bytes32 _Zin1, bytes32 _Zin2, bytes32[depth] _proofZout, bytes32[depth] _proofZin) allowed(receiver, stage.keyRevealed) public { require (vrfy(_indexOut, _Zout, _proofZout)); bytes32 Xout = cryptSmall(_indexOut, _Zout); require (vrfy(_indexIn, _Zin1, _proofZin)); require (_proofZin[0] == _Zin2); if (Xout != keccak256(cryptSmall(_indexIn, _Zin1), cryptSmall(_indexIn+1, _Zin2))) { receiver.call.value(price); phase = stage.created; } } // refund function is called in case some party did not contribute in time function refund () public { require (now > timeout); if (phase == stage.accepted) { receiver.call.value(price); phase = stage.created; } else if (phase >= stage.keyRevealed) { sender.call.value(price); phase = stage.created; } } // function to both encrypt and decrypt text chunks with key k function cryptLarge (uint _index, bytes32[length] _ciphertext) public view returns (bytes32[length]){ _index = _index*length; for (uint i = 0; i < length; i++){ _ciphertext[i] = keccak256(_index, key) ^ _ciphertext[i]; _index++; } return _ciphertext; } // function to decrypt hashes of the merkle tree function cryptSmall (uint _index, bytes32 _ciphertext) public view returns (bytes32){ return keccak256(_index, key) ^ _ciphertext; } // function to verify Merkle Tree proofs function vrfy(uint _index, bytes32 _value, bytes32[depth] _proof) public view returns (bool){ for (uint i = 0; i < 3; i++){ if ((_index & 1<<i)>>i == 1) _value = keccak256(_proof[3 -i], _value); else _value = keccak256(_value, _proof[3 -i]); } return (_value == ciphertextRoot); } }
function to decrypt hashes of the merkle tree
function cryptSmall (uint _index, bytes32 _ciphertext) public view returns (bytes32){ return keccak256(_index, key) ^ _ciphertext; }
13,133,870
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "../credit/CreditSystem.sol"; import "../interfaces/IKToken.sol"; import "../token/KToken.sol"; import "../interfaces/ILendingPool.sol"; import "./LendingPoolStorage.sol"; import "../libraries/ReserveLogic.sol"; import "./DataTypes.sol"; import "../libraries/ValidationLogic.sol"; /** * @dev kyoko ERC20 lending pool */ contract KyokoLendingPool is ILendingPool, LendingPoolStorage, AccessControlEnumerableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using ReserveLogic for DataTypes.ReserveData; using SafeMathUpgradeable for uint256; bytes32 public constant LENDING_POOL_ADMIN = keccak256("LENDING_POOL_ADMIN"); uint256 public constant LENDINGPOOL_REVISION = 0x0; modifier whenNotPaused() { _whenNotPaused(); _; } function _whenNotPaused() internal view { require(!_paused, "LP_IS_PAUSED"); } CreditSystem public creditContract; /** * @dev only the lending pool admin can operate. */ modifier onlyLendingPoolAdmin() { require( hasRole(LENDING_POOL_ADMIN, _msgSender()), "Only the lending pool admin has permission to do this operation" ); _; } /** * @dev initialize lending pool with credit system */ function initialize(address _creditContract) public initializer { _grantRole(DEFAULT_ADMIN_ROLE, _msgSender()); creditContract = CreditSystem(_creditContract); } /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDT and gets in return 100 kUSDT * @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 **/ function deposit( address asset, uint256 amount, address onBehalfOf ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address kToken = reserve.kTokenAddress; reserve.updateState(); reserve.updateInterestRates(asset, kToken, amount, 0); IERC20Upgradeable(asset).safeTransferFrom(msg.sender, kToken, amount); IKToken(kToken).mint(onBehalfOf, amount, reserve.liquidityIndex); emit Deposit(asset, msg.sender, onBehalfOf, amount); } /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent kTokens owned * E.g. User has 100 kUSDT, calls withdraw() and receives 100 USDT, burning the 100 kUSDT * @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 kToken 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 kToken = reserve.kTokenAddress; uint256 userBalance = IKToken(kToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves ); reserve.updateState(); reserve.updateInterestRates(asset, kToken, 0, amountToWithdraw); IKToken(kToken).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 had enough credit line, or he was given enough allowance by a credit delegator on the * corresponding debt token * - E.g. User borrows 100 USDT passing as `onBehalfOf` his own address, receiving the 100 USDT in his wallet * and 100 variable debt tokens * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @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 credit line, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, address onBehalfOf ) external override whenNotPaused { require(amount > 0, "BORROW_AMOUNT_LESS_THAN_ZERO"); DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, reserve.kTokenAddress, true ) ); } /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDT, burning 100 variable 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` * @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, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; uint256 variableDebt = IERC20Upgradeable( reserve.variableDebtTokenAddress ).balanceOf(onBehalfOf); ValidationLogic.validateRepay( reserve, amount, onBehalfOf, variableDebt ); uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); address kToken = reserve.kTokenAddress; reserve.updateInterestRates(asset, kToken, paybackAmount, 0); IERC20Upgradeable(asset).safeTransferFrom( msg.sender, kToken, paybackAmount ); IKToken(kToken).handleRepayment(msg.sender, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } /** * @dev Initializes a reserve, activating it, assigning an kToken and debt tokens and an * interest rate strategy * - Only callable by the LendingPoolAdmin role * @param asset The address of the underlying asset of the reserve * @param kTokenAddress The address of the kToken that will be assigned to the reserve * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve * @param interestRateStrategyAddress The address of the interest rate strategy contract * @param reserveDecimals The decimals of the underlying asset of the reserve * @param reserveFactor The factor of the underlying asset of the reserve **/ function initReserve( address asset, address kTokenAddress, address variableDebtAddress, address interestRateStrategyAddress, uint8 reserveDecimals, uint16 reserveFactor ) external override onlyLendingPoolAdmin { require(AddressUpgradeable.isContract(asset), "NOT_CONTRACT"); _reserves[asset].init( kTokenAddress, variableDebtAddress, interestRateStrategyAddress ); _addReserveToList(asset, reserveDecimals, reserveFactor); emit InitReserve(asset, kTokenAddress, variableDebtAddress, interestRateStrategyAddress, reserveDecimals, reserveFactor); } function _addReserveToList( address asset, uint8 reserveDecimals, uint16 reserveFactor ) internal { uint256 reservesCount = _reservesCount; bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; if (!reserveAlreadyAdded) { _reserves[asset].id = uint8(reservesCount); _reserves[asset].decimals = uint8(reserveDecimals); _reserves[asset].factor = uint16(reserveFactor); _reservesList[reservesCount] = asset; _reservesCount = reservesCount + 1; } } /** * @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(); } function paused() external view override returns (bool) { return _paused; } /** * @dev Set the _pause state of a reserve * - Only callable by the LendingPoolAdmin role * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external override onlyLendingPoolAdmin { _paused = val; if (_paused) { emit Paused(); } else { emit Unpaused(); } } struct ExecuteBorrowParams { address asset; address user; address onBehalfOf; uint256 amount; address kTokenAddress; bool releaseUnderlying; } function _executeBorrow(ExecuteBorrowParams memory vars) internal { DataTypes.ReserveData storage reserve = _reserves[vars.asset]; ( uint256 totalDebtInWEI, uint256 availableBorrowsInWEI ) = getUserAccountData(vars.user); ValidationLogic.validateBorrow( availableBorrowsInWEI, reserve, vars.amount ); reserve.updateState(); IVariableDebtToken(reserve.variableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); reserve.updateInterestRates( vars.asset, vars.kTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IKToken(vars.kTokenAddress).transferUnderlyingTo( vars.user, vars.amount ); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, reserve.currentVariableBorrowRate ); } /** * @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 totalDebtInWEI the total debt in WEI of the user * @return availableBorrowsInWEI the borrowing power left of the user **/ function getUserAccountData(address user) public view override returns (uint256 totalDebtInWEI, uint256 availableBorrowsInWEI) { totalDebtInWEI = GenericLogic.calculateUserAccountData( user, _reserves, _reservesList, _reservesCount ); uint256 creditLine = creditContract.getG2GCreditLine(user); availableBorrowsInWEI = totalDebtInWEI >= creditLine ? 0 : creditLine.sub(totalDebtInWEI); } /** * @dev Updates the address of the interest rate strategy contract * - Only callable by the LendingPoolAdmin role * @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 onlyLendingPoolAdmin { _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; } /** * @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 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 Sets the reserve factor of the reserve * @param asset The address of the underlying asset in reserve * @param reserveFactor The reserve factor **/ function setReserveFactor(address asset, uint16 reserveFactor) external onlyLendingPoolAdmin { DataTypes.ReserveData storage reserve = _reserves[asset]; reserve.setReserveFactor(reserveFactor); emit ReserveFactorChanged(asset, reserveFactor); } /** * @dev Sets the active state of the reserve * @param asset The address of the underlying asset in reserve * @param active The active state **/ function setActive(address asset, bool active) external onlyLendingPoolAdmin { DataTypes.ReserveData storage reserve = _reserves[asset]; reserve.setActive(active); emit ReserveActiveChanged(asset, active); } /** * @dev Gets the active state of the reserve * @param asset The address of the underlying asset in reserve * @return The active state **/ function getActive(address asset) external view override returns (bool) { DataTypes.ReserveData storage reserve = _reserves[asset]; return reserve.getActive(); } /** * @dev Sets the credit system address of the lending pool * @param _creditContract The address of the underlying asset in reserve * - Only callable by the LendingPoolAdmin role **/ function setCreditStrategy(address _creditContract) external override onlyLendingPoolAdmin { creditContract = CreditSystem(_creditContract); emit CreditStrategyChanged(_creditContract); } /** * @dev Gets the credit system address of the lending pool **/ function getCreditStrategy() external view override returns (address) { return address(creditContract); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/IKToken.sol"; import "../interfaces/ILendingPool.sol"; import "../libraries/KyokoMath.sol"; import "./IncentivizedERC20.sol"; /** * @dev if the user deposit token, then will mint corresponding KToken. * @dev it is similar to a certificate of deposit. */ contract KToken is Initializable, IncentivizedERC20, IKToken { using KyokoMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; 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 KTOKEN_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; modifier onlyLendingPool() { require( _msgSender() == address(_pool), "CT_CALLER_MUST_BE_LENDING_POOL" ); _; } /** * @dev Initializes the kToken * @param pool The address of the lending pool where this kToken will be used * @param treasury The address of the Kyoko treasury, receiving the fees on this kToken * @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT) * @param kTokenDecimals The decimals of the kToken, same as the underlying asset's * @param kTokenName The name of the kToken * @param kTokenSymbol The symbol of the kToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, uint8 kTokenDecimals, string calldata kTokenName, string calldata kTokenSymbol, bytes calldata params ) external override initializer { IncentivizedERC20.initialize(kTokenName, kTokenSymbol, kTokenDecimals); // Do not forget this call! uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(kTokenName)), keccak256(EIP712_REVISION), chainId, address(this) ) ); _setName(kTokenName); _setSymbol(kTokenSymbol); _setDecimals(kTokenDecimals); _pool = pool; _treasury = treasury; _underlyingAsset = underlyingAsset; emit Initialized( underlyingAsset, address(pool), treasury, kTokenDecimals, kTokenName, kTokenSymbol, params ); } /** * @dev Burns kTokens 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 kTokens, 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, "CT_INVALID_BURN_AMOUNT"); _burn(user, amountScaled); IERC20Upgradeable(_underlyingAsset).safeTransfer( receiverOfUnderlying, amount ); emit Transfer(user, address(0), amount); emit Burn(user, receiverOfUnderlying, amount, index); } /** * @dev Mints `amount` kTokens 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, "CT_INVALID_MINT_AMOUNT"); _mint(user, amountScaled); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalance == 0; } /** * @dev Mints kTokens 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 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, IERC20Upgradeable) 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 kToken * 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, IERC20Upgradeable) 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 Kyoko treasury, receiving the fees on this kToken **/ function RESERVE_TREASURY_ADDRESS() public view returns (address) { return _treasury; } /** * @dev Returns the address of the underlying asset of this kToken (E.g. USDT for kUSDT) **/ function UNDERLYING_ASSET_ADDRESS() public view override returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this kToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() * @param target The recipient of the kTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address target, uint256 amount) external override onlyLendingPool returns (uint256) { IERC20Upgradeable(_underlyingAsset).safeTransfer(target, amount); return amount; } /** * @dev Invoked to execute actions on the kToken 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 kTokens between two users. Validates the transfer * (ie checks for valid credit line 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: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; /** * @title ERC20 * @notice Basic ERC20 implementation **/ abstract contract IncentivizedERC20 is ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { using SafeMathUpgradeable 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; function initialize( string memory name, string memory symbol, uint8 decimals ) public initializer { _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]; } /** * @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); } 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); } 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" ); } 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: MIT pragma solidity 0.8.7; import "../lendingpool/DataTypes.sol"; import "../credit/CreditSystem.sol"; import "./KyokoMath.sol"; import "./PercentageMath.sol"; import "./ReserveLogic.sol"; import "./GenericLogic.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; /** * @title ReserveLogic library * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMathUpgradeable for uint256; using KyokoMath for uint256; using PercentageMath for uint256; 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 = reserve.getActive(); require(amount != 0, "VL_INVALID_AMOUNT"); require(isActive, "VL_NO_ACTIVE_RESERVE"); } /** * @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 */ function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData ) external view { require(amount != 0, "VL_INVALID_AMOUNT"); require(amount <= userBalance, "VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE"); bool isActive = reservesData[reserveAddress].getActive(); require(isActive, "VL_NO_ACTIVE_RESERVE"); } struct ValidateBorrowLocalVars { uint256 userBorrowBalance; uint256 availableLiquidity; bool isActive; } /** * @dev Validates a borrow action * @param availableBorrowsInWEI available borrows in WEI * @param reserve The reserve state from which the user is borrowing * @param amount The amount to be borrowed */ function validateBorrow( uint256 availableBorrowsInWEI, DataTypes.ReserveData storage reserve, uint256 amount ) external view { ValidateBorrowLocalVars memory vars; require(availableBorrowsInWEI > 0, "available credit line not enough"); uint256 decimals_ = 1 ether; uint256 borrowsAmountInWEI = amount.div(10**reserve.decimals).mul(uint256(decimals_)); require(borrowsAmountInWEI <= availableBorrowsInWEI, "borrows exceed credit line"); vars.isActive = reserve.getActive(); require(vars.isActive, "VL_NO_ACTIVE_RESERVE"); require(amount > 0, "VL_INVALID_AMOUNT"); } /** * @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 type(uint256).min * @param onBehalfOf The address of the user msg.sender is repaying for * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveData storage reserve, uint256 amountSent, address onBehalfOf, uint256 variableDebt ) external view { bool isActive = reserve.getActive(); require(isActive, "VL_NO_ACTIVE_RESERVE"); require(amountSent > 0, "VL_INVALID_AMOUNT"); require(variableDebt > 0, "VL_NO_DEBT_OF_SELECTED_TYPE"); require( amountSent != type(uint256).max || msg.sender == onBehalfOf, "VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF" ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../lendingpool/DataTypes.sol"; import "../interfaces/IVariableDebtToken.sol"; import "../interfaces/IReserveInterestRateStrategy.sol"; import "./MathUtils.sol"; import "./KyokoMath.sol"; import "./PercentageMath.sol"; import "../interfaces/IKToken.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; /** * @title ReserveLogic library * @notice Implements the logic to update the reserves state */ library ReserveLogic { using SafeMathUpgradeable for uint256; using KyokoMath for uint256; using PercentageMath for uint256; /** * @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 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 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; using ReserveLogic for DataTypes.ReserveData; /** * @dev Initializes a reserve * @param reserve The reserve object * @param kTokenAddress The address of the overlying ktoken contract * @param variableDebtTokenAddress The address of the variable debt token * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function init( DataTypes.ReserveData storage reserve, address kTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress ) external { require(reserve.kTokenAddress == address(0), "the reserve already initialized"); reserve.isActive = true; reserve.liquidityIndex = uint128(KyokoMath.ray()); reserve.variableBorrowIndex = uint128(KyokoMath.ray()); reserve.kTokenAddress = kTokenAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress; } /** * @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 ); } /** * @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 * @param timestamp The last operate time of reserve **/ 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) { // 1 + ratePerSecond * (delta_t / seconds in a year) uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex <= type(uint128).max, "RL_LIQUIDITY_INDEX_OVERFLOW"); reserve.liquidityIndex = uint128(newLiquidityIndex); //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, "RL_VARIABLE_BORROW_INDEX_OVERFLOW" ); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); return (newLiquidityIndex, newVariableBorrowIndex); } struct MintToTreasuryLocalVars { uint256 currentVariableDebt; uint256 previousVariableDebt; uint256 totalDebtAccrued; uint256 amountToMint; uint16 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 ) internal { MintToTreasuryLocalVars memory vars; vars.reserveFactor = getReserveFactor(reserve); if (vars.reserveFactor == 0) { return; } //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); //debt accrued is the sum of the current debt minus the sum of the debt at the last update vars.totalDebtAccrued = vars .currentVariableDebt .sub(vars.previousVariableDebt); vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); if (vars.amountToMint != 0) { IKToken(reserve.kTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } } struct UpdateInterestRatesLocalVars { uint256 availableLiquidity; uint256 newLiquidityRate; uint256 newVariableRate; 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 kTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { UpdateInterestRatesLocalVars memory vars; //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.newVariableRate ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, kTokenAddress, liquidityAdded, liquidityTaken, vars.totalVariableDebt, getReserveFactor(reserve) ); require(vars.newLiquidityRate <= type(uint128).max, "RL_LIQUIDITY_RATE_OVERFLOW"); require(vars.newVariableRate <= type(uint128).max, "RL_VARIABLE_BORROW_RATE_OVERFLOW"); reserve.currentLiquidityRate = uint128(vars.newLiquidityRate); reserve.currentVariableBorrowRate = uint128(vars.newVariableRate); emit ReserveDataUpdated( reserveAddress, vars.newLiquidityRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex ); } /** * @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 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 Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveData storage self, bool active) internal { self.isActive = active; } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveData storage self) internal view returns (bool) { return self.isActive; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveData storage self, uint16 reserveFactor) internal { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, "RC_INVALID_RESERVE_FACTOR"); self.factor = reserveFactor; } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveData storage self) internal view returns (uint16) { return self.factor; } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimal(DataTypes.ReserveData storage self) internal view returns (uint8) { return self.decimals; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title PercentageMath library * @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, "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, "MATH_DIVISION_BY_ZERO"); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, "MATH_MULTIPLICATION_OVERFLOW" ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "./KyokoMath.sol"; library MathUtils { using SafeMathUpgradeable for uint256; using KyokoMath 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(KyokoMath.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 KyokoMath.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 KyokoMath.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: MIT pragma solidity 0.8.7; library KyokoMath { 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, "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, "MATH_DIVISION_BY_ZERO"); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, "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, "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, "MATH_DIVISION_BY_ZERO"); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, "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, "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, "MATH_MULTIPLICATION_OVERFLOW"); return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../lendingpool/DataTypes.sol"; import "./KyokoMath.sol"; import "./PercentageMath.sol"; import "./ReserveLogic.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; library GenericLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMathUpgradeable for uint256; using KyokoMath for uint256; using PercentageMath for uint256; struct CalculateUserAccountDataVars { uint256 decimals; uint256 tokenUnit; uint256 compoundedBorrowBalance; uint256 totalDebtInWEI; uint256 i; address currentReserveAddress; } /** * @dev Calculates the user total Debt in WEI across the reserves. * @param user The address of the user * @param reservesData Data of all the reserves * @param reserves The list of the available reserves * @param reservesCount the count of reserves * @return The total debt of the user in WEI **/ function calculateUserAccountData( address user, mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reserves, uint256 reservesCount ) internal view returns (uint256) { CalculateUserAccountDataVars memory vars; for (vars.i = 0; vars.i < reservesCount; vars.i++) { vars.currentReserveAddress = reserves[vars.i]; DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress]; vars.decimals = currentReserve.getDecimal(); uint256 decimals_ = 1 ether; vars.tokenUnit = uint256(decimals_).div(10**vars.decimals); uint256 currentReserveBorrows = IERC20Upgradeable(currentReserve.variableDebtTokenAddress).balanceOf(user); if (currentReserveBorrows > 0) { vars.totalDebtInWEI = vars.totalDebtInWEI.add( uint256(1).mul(currentReserveBorrows).mul(vars.tokenUnit) ); } } return vars.totalDebtInWEI; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./DataTypes.sol"; import "../libraries/ReserveLogic.sol"; contract LendingPoolStorage { using ReserveLogic for DataTypes.ReserveData; mapping(address => DataTypes.ReserveData) internal _reserves; //the list of the available reserves, structured as a mapping for gas savings reasons mapping(uint256 => address) _reservesList; uint256 internal _reservesCount; bool internal _paused; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; library DataTypes { struct ReserveData { //this current state of the asset; bool isActive; //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 last update time of the reserve uint40 lastUpdateTimestamp; //address of the ktoken address kTokenAddress; //address of the debt token address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; // Reserve factor uint16 factor; uint8 decimals; //the id of the reserve.Represents the position in the list of the active reserves. uint8 id; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./IScaledBalanceToken.sol"; import "./IInitializableDebtToken.sol"; 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; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; 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: MIT pragma solidity 0.8.7; interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( uint256 availableLiquidity, uint256 totalVariableDebt, uint256 reserveFactor ) external view returns ( uint256, uint256 ); function calculateInterestRates( address reserve, address kToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalVariableDebt, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../lendingpool/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 kTokens * @param amount The amount deposited **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of kTokens * @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() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRate The numeric rate at which the user has borrowed **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRate ); /** * @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 initReserve() **/ event InitReserve( address asset, address kTokenAddress, address variableDebtAddress, address interestRateStrategyAddress, uint8 reserveDecimals, uint16 reserveFactor ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @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 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 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @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 a reserve active state is updated * @param asset The address of the underlying asset of the reserve * @param active The new reserve active state **/ event ReserveActiveChanged(address indexed asset, bool active); /** * @dev Emitted when credit system is updated * @param creditContract The address of the new credit system **/ event CreditStrategyChanged(address creditContract); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying kTokens. * - E.g. User deposits 100 USDT and gets in return 100 kUSDT * @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 kTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of kTokens * is a different wallet **/ function deposit( address asset, uint256 amount, address onBehalfOf ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent kTokens owned * E.g. User has 100 kUSDT, calls withdraw() and receives 100 USDT, burning the 100 aUSDT * @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 kToken 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 had a credit line, or he was given enough allowance by a credit delegator on the * corresponding debt token * - E.g. User borrows 100 USDT passing as `onBehalfOf` his own address, receiving the 100 USDT in his wallet * and 100 variable debt tokens * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @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 credit, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDT, 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` * @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, address onBehalfOf ) external returns (uint256); /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalDebtInWEI the total debt in WEI of the user * @return availableBorrowsInWEI the borrowing power left of the user **/ function getUserAccountData(address user) external view returns (uint256 totalDebtInWEI, uint256 availableBorrowsInWEI); function initReserve( address reserve, address kTokenAddress, address variableDebtAddress, address interestRateStrategyAddress, uint8 reserveDecimals, uint16 reserveFactor ) external; function setReserveInterestRateStrategyAddress( address reserve, address rateStrategyAddress ) external; /** * @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 getReservesList() external view returns (address[] memory); function setPause(bool val) external; function paused() external view returns (bool); function getActive(address asset) external view returns (bool); function setCreditStrategy(address creditContract) external; function getCreditStrategy() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "./IScaledBalanceToken.sol"; import "./IInitializableKToken.sol"; interface IKToken is IERC20Upgradeable, IScaledBalanceToken, IInitializableKToken { /** * @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` kTokens 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 kTokens are burned * @param from The owner of the kTokens, 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 kTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the kTokens, 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 kTokens 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 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 kToken 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 underlying asset of this kToken (E.g. USDT for kUSDT) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./ILendingPool.sol"; interface IInitializableKToken { /** * @dev Emitted when an kToken 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 kTokenDecimals the decimals of the underlying * @param kTokenName the name of the kToken * @param kTokenSymbol the symbol of the kToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, uint8 kTokenDecimals, string kTokenName, string kTokenSymbol, bytes params ); /** * @dev Initializes the kToken * @param pool The address of the lending pool where this kToken will be used * @param treasury The address of the Kyoko treasury, receiving the fees on this kToken * @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT) * @param kTokenDecimals The decimals of the kToken, same as the underlying asset's * @param kTokenName The name of the kToken * @param kTokenSymbol The symbol of the kToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, uint8 kTokenDecimals, string calldata kTokenName, string calldata kTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./ILendingPool.sol"; 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 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, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this kToken will be used * @param underlyingAsset The address of the underlying asset of this kToken (E.g. USDT for kUSDT) * @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, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; /** * @dev this contract represents the credit line in the whitelist. * @dev the guild's credit line amount * @dev the decimals is 1e18. */ contract CreditSystem is AccessControlEnumerableUpgradeable { using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /// the role manage total credit manager bytes32 public constant ROLE_CREDIT_MANAGER = keccak256("ROLE_CREDIT_MANAGER"); uint8 public constant G2G_MASK = 0x0E; uint8 public constant CCAL_MASK = 0x0D; uint8 constant IS_G2G_START_BIT_POSITION = 0; uint8 constant IS_CCAL_START_BIT_POSITION = 1; struct CreditInfo { //ERC20 credit line uint256 g2gCreditLine; //ccal module credit line uint256 ccalCreditLine; //bit 0: g2g isActive flag(0==false, 1==true) //bit 1: ccal isActive flag(0==false, 1==true) uint8 flag; } // the credit line mapping(address => CreditInfo) whiteList; //g2g whiteList Set EnumerableSetUpgradeable.AddressSet private g2gWhiteSet; //ccal whiteList Set EnumerableSetUpgradeable.AddressSet private ccalWhiteSet; event SetG2GCreditLine(address user, uint256 amount); event SetCCALCreditLine(address user, uint256 amount); // event SetPaused(address user, bool flag); event SetG2GActive(address user, bool active); event SetCCALActive(address user, bool active); event RemoveG2GCredit(address user); event RemoveCCALCredit(address user); modifier onlyCreditManager() { require( hasRole(ROLE_CREDIT_MANAGER, _msgSender()), "only the manager has permission to perform this operation." ); _; } // constructor() { // _grantRole(DEFAULT_ADMIN_ROLE, _msgSender()); // } function initialize() public initializer { __AccessControlEnumerable_init(); _grantRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * set the address's g2g module credit line * @dev user the guild in the whiteList * @dev amount the guild credit line amount * @dev 1U = 1e18 */ function setG2GCreditLine(address user, uint256 amount) public onlyCreditManager { whiteList[user].g2gCreditLine = amount; setG2GActive(user, amount > 0); emit SetG2GCreditLine(user, amount); } /** * @dev set the address's g2g module credit active status */ function setG2GActive(address user, bool active) public onlyCreditManager { //set user flag setG2GFlag(user, active); //set user white set if (active) { uint256 userG2GCreditLine = getG2GCreditLine(user); userG2GCreditLine > 0 ? g2gWhiteSet.add(user) : g2gWhiteSet.remove(user); } else { g2gWhiteSet.remove(user); } emit SetG2GActive(user, active); } function setG2GFlag(address user, bool active) private { uint8 flag = whiteList[user].flag; flag = (flag & G2G_MASK) | (uint8(active ? 1 : 0) << IS_G2G_START_BIT_POSITION); whiteList[user].flag = flag; } /** * set the address's ccal module credit line * @dev user the guild in the whiteList * @dev amount the guild credit line amount * @dev 1U = 1e18 */ function setCCALCreditLine(address user, uint256 amount) public onlyCreditManager { whiteList[user].ccalCreditLine = amount; setCCALActive(user, amount > 0); emit SetCCALCreditLine(user, amount); } /** * @dev set the address's ccal module credit active status */ function setCCALActive(address user, bool active) public onlyCreditManager { //set user flag setCCALFlag(user, active); //set user white set if (active) { uint256 userCCALCreditLine = getCCALCreditLine(user); userCCALCreditLine > 0 ? ccalWhiteSet.add(user) : ccalWhiteSet.remove(user); } else { ccalWhiteSet.remove(user); } emit SetCCALActive(user, active); } function setCCALFlag(address user, bool active) private { uint8 flag = whiteList[user].flag; flag = (flag & CCAL_MASK) | (uint8(active ? 1 : 0) << IS_CCAL_START_BIT_POSITION); whiteList[user].flag = flag; } /** * remove the address's g2g module credit line */ function removeG2GCredit(address user) public onlyCreditManager { whiteList[user].g2gCreditLine = 0; setG2GActive(user, false); emit RemoveG2GCredit(user); } /** * remove the address's ccal module credit line */ function removeCCALCredit(address user) public onlyCreditManager { whiteList[user].ccalCreditLine = 0; setCCALActive(user, false); emit RemoveCCALCredit(user); } /** * @dev query the user credit line * @param user the address which to query * @return G2G credit line */ function getG2GCreditLine(address user) public view returns (uint256) { CreditInfo memory credit = whiteList[user]; return credit.g2gCreditLine; } /** * @dev query the user credit line * @param user the address which to query * @return CCAL credit line */ function getCCALCreditLine(address user) public view returns (uint256) { CreditInfo memory credit = whiteList[user]; return credit.ccalCreditLine; } /** * @dev query the white list addresses in G2G */ function getG2GWhiteList() public view returns (address[] memory) { return g2gWhiteSet.values(); } /** * @dev query the white list addresses in CCAL */ function getCCALWhiteList() public view returns (address[] memory) { return ccalWhiteSet.values(); } /** * @dev query the address state */ function getState(address user) public view returns (bool, bool) { uint8 activeFlag = whiteList[user].flag; return ( activeFlag & ~G2G_MASK != 0, activeFlag & ~CCAL_MASK != 0 ); } } // 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 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 // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library 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 // 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal 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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal 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; } // 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 AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable 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(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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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 "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `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 {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^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 {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal 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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @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; }
Calculates the balance of the user: principal balance + interest generated by the principal user The user whose balance is calculated return The balance of the user/
function balanceOf(address user) public view override(IncentivizedERC20, IERC20Upgradeable) returns (uint256) { return super.balanceOf(user).rayMul( _pool.getReserveNormalizedIncome(_underlyingAsset) ); }
11,855,631
// 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); } } } }
Revert this contract to normal from vesting state Requirements: - Only owner of this contract can call this function - This contract is in vesting state/ Re-deposit all token to Harvest Finance Vault contract and re-stake all fToken to Harvest Finance Stake contract
function revertVesting() public onlyOwner { require(isVesting, "Not in vesting state"); uint256 _amount = token.balanceOf(address(this)); if (_amount > 0) { hfVault.deposit(_amount); hfStake.stake(hfVault.balanceOf(address(this))); } isVesting = false; }
1,447,347
//Address: 0x03e69cb57d951d9b123145f5e458153c19f57c88 //Contract name: GangMultisig //Balance: 0 Ether //Verification Date: 5/21/2018 //Transacion Count: 7 // CODE STARTS HERE pragma solidity ^0.4.22; /** *@title abstract TokenContract *@dev token contract to call multisig functions */ contract TokenContract{ function mint(address _to, uint256 _amount) public; function finishMinting () public; function setupMultisig (address _address) public; } /** *@title contract GangMultisig *@dev using multisig access to call another contract functions */ contract GangMultisig { /** *@dev token contract variable, contains token address *can use abstract contract functions */ TokenContract public token; //@dev Variable to check multisig functions life time. //change it before deploy in main network uint public lifeTime = 86400; // seconds; //@dev constructor constructor (address _token, uint _needApprovesToConfirm, address[] _owners) public{ require (_needApprovesToConfirm > 1 && _needApprovesToConfirm <= _owners.length); //@dev setup GangTokenContract by contract address token = TokenContract(_token); addInitialOwners(_owners); needApprovesToConfirm = _needApprovesToConfirm; /** *@dev Call function setupMultisig in token contract *This function can be call once. */ token.setupMultisig(address(this)); ownersCount = _owners.length; } /** *@dev internal function, called in constructor *Add initial owners in mapping 'owners' */ function addInitialOwners (address[] _owners) internal { for (uint i = 0; i < _owners.length; i++){ //@dev check for duplicate owner addresses require(!owners[_owners[i]]); owners[_owners[i]] = true; } } //@dev variable to check is minting finished; bool public mintingFinished = false; //@dev Mapping which contains all active owners. mapping (address => bool) public owners; //@dev Owner can add new proposal 1 time at each lifeTime cycle mapping (address => uint32) public lastOwnersAction; modifier canCreate() { require (lastOwnersAction[msg.sender] + lifeTime < now); lastOwnersAction[msg.sender] = uint32(now); _; } //@dev Modifier to check is message sender contains in mapping 'owners'. modifier onlyOwners() { require (owners[msg.sender]); _; } //@dev current owners count uint public ownersCount; //@dev current approves need to confirm for any function. Can't be less than 2. uint public needApprovesToConfirm; //Start Minting Tokens struct SetNewMint { address spender; uint value; uint8 confirms; bool isExecute; address initiator; bool isCanceled; uint32 creationTimestamp; address[] confirmators; } //@dev Variable which contains all information about current SetNewMint request SetNewMint public setNewMint; event NewMintRequestSetup(address indexed initiator, address indexed spender, uint value); event NewMintRequestUpdate(address indexed owner, uint8 indexed confirms, bool isExecute); event NewMintRequestCanceled(); /** * @dev Set new mint request, can be call only by owner * @param _spender address The address which you want to mint to * @param _value uint256 the amount of tokens to be minted */ function setNewMintRequest (address _spender, uint _value) public onlyOwners canCreate { require (setNewMint.creationTimestamp + lifeTime < uint32(now) || setNewMint.isExecute || setNewMint.isCanceled); require (!mintingFinished); address[] memory addr; setNewMint = SetNewMint(_spender, _value, 1, false, msg.sender, false, uint32(now), addr); setNewMint.confirmators.push(msg.sender); emit NewMintRequestSetup(msg.sender, _spender, _value); } /** * @dev Approve mint request, can be call only by owner * which don't call this mint request before. */ function approveNewMintRequest () public onlyOwners { require (!setNewMint.isExecute && !setNewMint.isCanceled); require (setNewMint.creationTimestamp + lifeTime >= uint32(now)); require (!mintingFinished); for (uint i = 0; i < setNewMint.confirmators.length; i++){ require(setNewMint.confirmators[i] != msg.sender); } setNewMint.confirms++; setNewMint.confirmators.push(msg.sender); if(setNewMint.confirms >= needApprovesToConfirm){ setNewMint.isExecute = true; token.mint(setNewMint.spender, setNewMint.value); } emit NewMintRequestUpdate(msg.sender, setNewMint.confirms, setNewMint.isExecute); } /** * @dev Cancel mint request, can be call only by owner * which created this mint request. */ function cancelMintRequest () public { require (msg.sender == setNewMint.initiator); require (!setNewMint.isCanceled && !setNewMint.isExecute); setNewMint.isCanceled = true; emit NewMintRequestCanceled(); } //Finish Minting Tokens //Start finishMinting functions struct FinishMintingStruct { uint8 confirms; bool isExecute; address initiator; bool isCanceled; uint32 creationTimestamp; address[] confirmators; } //@dev Variable which contains all information about current finishMintingStruct request FinishMintingStruct public finishMintingStruct; event FinishMintingRequestSetup(address indexed initiator); event FinishMintingRequestUpdate(address indexed owner, uint8 indexed confirms, bool isExecute); event FinishMintingRequestCanceled(); event FinishMintingApproveCanceled(address owner); /** * @dev New finish minting request, can be call only by owner */ function finishMintingRequestSetup () public onlyOwners canCreate{ require ((finishMintingStruct.creationTimestamp + lifeTime < uint32(now) || finishMintingStruct.isCanceled) && !finishMintingStruct.isExecute); require (!mintingFinished); address[] memory addr; finishMintingStruct = FinishMintingStruct(1, false, msg.sender, false, uint32(now), addr); finishMintingStruct.confirmators.push(msg.sender); emit FinishMintingRequestSetup(msg.sender); } /** * @dev Approve finish minting request, can be call only by owner * which don't call this finish minting request before. */ function ApproveFinishMintingRequest () public onlyOwners { require (!finishMintingStruct.isCanceled && !finishMintingStruct.isExecute); require (finishMintingStruct.creationTimestamp + lifeTime >= uint32(now)); require (!mintingFinished); for (uint i = 0; i < finishMintingStruct.confirmators.length; i++){ require(finishMintingStruct.confirmators[i] != msg.sender); } finishMintingStruct.confirmators.push(msg.sender); finishMintingStruct.confirms++; if(finishMintingStruct.confirms >= needApprovesToConfirm){ token.finishMinting(); finishMintingStruct.isExecute = true; mintingFinished = true; } emit FinishMintingRequestUpdate(msg.sender, finishMintingStruct.confirms, finishMintingStruct.isExecute); } /** * @dev Cancel finish minting request, can be call only by owner * which created this finish minting request. */ function cancelFinishMintingRequest () public { require (msg.sender == finishMintingStruct.initiator); require (!finishMintingStruct.isCanceled); finishMintingStruct.isCanceled = true; emit FinishMintingRequestCanceled(); } //Finish finishMinting functions //Start change approves count struct SetNewApproves { uint count; uint8 confirms; bool isExecute; address initiator; bool isCanceled; uint32 creationTimestamp; address[] confirmators; } //@dev Variable which contains all information about current setNewApproves request SetNewApproves public setNewApproves; event NewNeedApprovesToConfirmRequestSetup(address indexed initiator, uint count); event NewNeedApprovesToConfirmRequestUpdate(address indexed owner, uint8 indexed confirms, bool isExecute); event NewNeedApprovesToConfirmRequestCanceled(); /** * @dev Function to change 'needApprovesToConfirm' variable, can be call only by owner * @param _count uint256 New need approves to confirm will needed */ function setNewOwnersCountToApprove (uint _count) public onlyOwners canCreate { require (setNewApproves.creationTimestamp + lifeTime < uint32(now) || setNewApproves.isExecute || setNewApproves.isCanceled); require (_count > 1); address[] memory addr; setNewApproves = SetNewApproves(_count, 1, false, msg.sender,false, uint32(now), addr); setNewApproves.confirmators.push(msg.sender); emit NewNeedApprovesToConfirmRequestSetup(msg.sender, _count); } /** * @dev Approve new owners count request, can be call only by owner * which don't call this new owners count request before. */ function approveNewOwnersCount () public onlyOwners { require (setNewApproves.count <= ownersCount); require (setNewApproves.creationTimestamp + lifeTime >= uint32(now)); for (uint i = 0; i < setNewApproves.confirmators.length; i++){ require(setNewApproves.confirmators[i] != msg.sender); } require (!setNewApproves.isExecute && !setNewApproves.isCanceled); setNewApproves.confirms++; setNewApproves.confirmators.push(msg.sender); if(setNewApproves.confirms >= needApprovesToConfirm){ setNewApproves.isExecute = true; needApprovesToConfirm = setNewApproves.count; } emit NewNeedApprovesToConfirmRequestUpdate(msg.sender, setNewApproves.confirms, setNewApproves.isExecute); } /** * @dev Cancel new owners count request, can be call only by owner * which created this owners count request. */ function cancelNewOwnersCountRequest () public { require (msg.sender == setNewApproves.initiator); require (!setNewApproves.isCanceled && !setNewApproves.isExecute); setNewApproves.isCanceled = true; emit NewNeedApprovesToConfirmRequestCanceled(); } //Finish change approves count //Start add new owner struct NewOwner { address newOwner; uint8 confirms; bool isExecute; address initiator; bool isCanceled; uint32 creationTimestamp; address[] confirmators; } NewOwner public addOwner; //@dev Variable which contains all information about current addOwner request event AddOwnerRequestSetup(address indexed initiator, address newOwner); event AddOwnerRequestUpdate(address indexed owner, uint8 indexed confirms, bool isExecute); event AddOwnerRequestCanceled(); /** * @dev Function to add new owner in mapping 'owners', can be call only by owner * @param _newOwner address new potentially owner */ function setAddOwnerRequest (address _newOwner) public onlyOwners canCreate { require (addOwner.creationTimestamp + lifeTime < uint32(now) || addOwner.isExecute || addOwner.isCanceled); address[] memory addr; addOwner = NewOwner(_newOwner, 1, false, msg.sender, false, uint32(now), addr); addOwner.confirmators.push(msg.sender); emit AddOwnerRequestSetup(msg.sender, _newOwner); } /** * @dev Approve new owner request, can be call only by owner * which don't call this new owner request before. */ function approveAddOwnerRequest () public onlyOwners { require (!addOwner.isExecute && !addOwner.isCanceled); require (addOwner.creationTimestamp + lifeTime >= uint32(now)); /** *@dev new owner shoudn't be in owners mapping */ require (!owners[addOwner.newOwner]); for (uint i = 0; i < addOwner.confirmators.length; i++){ require(addOwner.confirmators[i] != msg.sender); } addOwner.confirms++; addOwner.confirmators.push(msg.sender); if(addOwner.confirms >= needApprovesToConfirm){ addOwner.isExecute = true; owners[addOwner.newOwner] = true; ownersCount++; } emit AddOwnerRequestUpdate(msg.sender, addOwner.confirms, addOwner.isExecute); } /** * @dev Cancel new owner request, can be call only by owner * which created this add owner request. */ function cancelAddOwnerRequest() public { require (msg.sender == addOwner.initiator); require (!addOwner.isCanceled && !addOwner.isExecute); addOwner.isCanceled = true; emit AddOwnerRequestCanceled(); } //Finish add new owner //Start remove owner NewOwner public removeOwners; //@dev Variable which contains all information about current removeOwners request event RemoveOwnerRequestSetup(address indexed initiator, address newOwner); event RemoveOwnerRequestUpdate(address indexed owner, uint8 indexed confirms, bool isExecute); event RemoveOwnerRequestCanceled(); /** * @dev Function to remove owner from mapping 'owners', can be call only by owner * @param _removeOwner address potentially owner to remove */ function removeOwnerRequest (address _removeOwner) public onlyOwners canCreate { require (removeOwners.creationTimestamp + lifeTime < uint32(now) || removeOwners.isExecute || removeOwners.isCanceled); address[] memory addr; removeOwners = NewOwner(_removeOwner, 1, false, msg.sender, false, uint32(now), addr); removeOwners.confirmators.push(msg.sender); emit RemoveOwnerRequestSetup(msg.sender, _removeOwner); } /** * @dev Approve remove owner request, can be call only by owner * which don't call this remove owner request before. */ function approveRemoveOwnerRequest () public onlyOwners { require (ownersCount - 1 >= needApprovesToConfirm && ownersCount > 2); require (owners[removeOwners.newOwner]); require (!removeOwners.isExecute && !removeOwners.isCanceled); require (removeOwners.creationTimestamp + lifeTime >= uint32(now)); for (uint i = 0; i < removeOwners.confirmators.length; i++){ require(removeOwners.confirmators[i] != msg.sender); } removeOwners.confirms++; removeOwners.confirmators.push(msg.sender); if(removeOwners.confirms >= needApprovesToConfirm){ removeOwners.isExecute = true; owners[removeOwners.newOwner] = false; ownersCount--; _removeOwnersAproves(removeOwners.newOwner); } emit RemoveOwnerRequestUpdate(msg.sender, removeOwners.confirms, removeOwners.isExecute); } /** * @dev Cancel remove owner request, can be call only by owner * which created this remove owner request. */ function cancelRemoveOwnerRequest () public { require (msg.sender == removeOwners.initiator); require (!removeOwners.isCanceled && !removeOwners.isExecute); removeOwners.isCanceled = true; emit RemoveOwnerRequestCanceled(); } //Finish remove owner //Start remove 2nd owner NewOwner public removeOwners2; //@dev Variable which contains all information about current removeOwners request event RemoveOwnerRequestSetup2(address indexed initiator, address newOwner); event RemoveOwnerRequestUpdate2(address indexed owner, uint8 indexed confirms, bool isExecute); event RemoveOwnerRequestCanceled2(); /** * @dev Function to remove owner from mapping 'owners', can be call only by owner * @param _removeOwner address potentially owner to remove */ function removeOwnerRequest2 (address _removeOwner) public onlyOwners canCreate { require (removeOwners2.creationTimestamp + lifeTime < uint32(now) || removeOwners2.isExecute || removeOwners2.isCanceled); address[] memory addr; removeOwners2 = NewOwner(_removeOwner, 1, false, msg.sender, false, uint32(now), addr); removeOwners2.confirmators.push(msg.sender); emit RemoveOwnerRequestSetup2(msg.sender, _removeOwner); } /** * @dev Approve remove owner request, can be call only by owner * which don't call this remove owner request before. */ function approveRemoveOwnerRequest2 () public onlyOwners { require (ownersCount - 1 >= needApprovesToConfirm && ownersCount > 2); require (owners[removeOwners2.newOwner]); require (!removeOwners2.isExecute && !removeOwners2.isCanceled); require (removeOwners2.creationTimestamp + lifeTime >= uint32(now)); for (uint i = 0; i < removeOwners2.confirmators.length; i++){ require(removeOwners2.confirmators[i] != msg.sender); } removeOwners2.confirms++; removeOwners2.confirmators.push(msg.sender); if(removeOwners2.confirms >= needApprovesToConfirm){ removeOwners2.isExecute = true; owners[removeOwners2.newOwner] = false; ownersCount--; _removeOwnersAproves(removeOwners2.newOwner); } emit RemoveOwnerRequestUpdate2(msg.sender, removeOwners2.confirms, removeOwners2.isExecute); } /** * @dev Cancel remove owner request, can be call only by owner * which created this remove owner request. */ function cancelRemoveOwnerRequest2 () public { require (msg.sender == removeOwners2.initiator); require (!removeOwners2.isCanceled && !removeOwners2.isExecute); removeOwners2.isCanceled = true; emit RemoveOwnerRequestCanceled2(); } //Finish remove 2nd owner /** * @dev internal function to check and revert all actions * by removed owner in this contract. * If _oldOwner created request then it will be canceled. * If _oldOwner approved request then his approve will canceled. */ function _removeOwnersAproves(address _oldOwner) internal{ //@dev check actions in setNewMint requests //@dev check for empty struct if (setNewMint.initiator != address(0)){ //@dev check, can this request be approved by someone, if no then no sense to change something if (setNewMint.creationTimestamp + lifeTime >= uint32(now) && !setNewMint.isExecute && !setNewMint.isCanceled){ if(setNewMint.initiator == _oldOwner){ setNewMint.isCanceled = true; emit NewMintRequestCanceled(); }else{ //@dev Trying to find _oldOwner in struct confirmators for (uint i = 0; i < setNewMint.confirmators.length; i++){ if (setNewMint.confirmators[i] == _oldOwner){ //@dev if _oldOwner confirmed this request he should be removed from confirmators setNewMint.confirmators[i] = address(0); setNewMint.confirms--; /** *@dev Struct can be confirmed each owner just once *so no sence to continue loop */ break; } } } } } /**@dev check actions in finishMintingStruct requests * check for empty struct */ if (finishMintingStruct.initiator != address(0)){ //@dev check, can this request be approved by someone, if no then no sense to change something if (finishMintingStruct.creationTimestamp + lifeTime >= uint32(now) && !finishMintingStruct.isExecute && !finishMintingStruct.isCanceled){ if(finishMintingStruct.initiator == _oldOwner){ finishMintingStruct.isCanceled = true; emit NewMintRequestCanceled(); }else{ //@dev Trying to find _oldOwner in struct confirmators for (i = 0; i < finishMintingStruct.confirmators.length; i++){ if (finishMintingStruct.confirmators[i] == _oldOwner){ //@dev if _oldOwner confirmed this request he should be removed from confirmators finishMintingStruct.confirmators[i] = address(0); finishMintingStruct.confirms--; /** *@dev Struct can be confirmed each owner just once *so no sence to continue loop */ break; } } } } } /**@dev check actions in setNewApproves requests * check for empty struct */ if (setNewApproves.initiator != address(0)){ //@dev check, can this request be approved by someone, if no then no sense to change something if (setNewApproves.creationTimestamp + lifeTime >= uint32(now) && !setNewApproves.isExecute && !setNewApproves.isCanceled){ if(setNewApproves.initiator == _oldOwner){ setNewApproves.isCanceled = true; emit NewNeedApprovesToConfirmRequestCanceled(); }else{ //@dev Trying to find _oldOwner in struct confirmators for (i = 0; i < setNewApproves.confirmators.length; i++){ if (setNewApproves.confirmators[i] == _oldOwner){ //@dev if _oldOwner confirmed this request he should be removed from confirmators setNewApproves.confirmators[i] = address(0); setNewApproves.confirms--; /** *@dev Struct can be confirmed each owner just once *so no sence to continue loop */ break; } } } } } /** *@dev check actions in addOwner requests *check for empty struct */ if (addOwner.initiator != address(0)){ //@dev check, can this request be approved by someone, if no then no sense to change something if (addOwner.creationTimestamp + lifeTime >= uint32(now) && !addOwner.isExecute && !addOwner.isCanceled){ if(addOwner.initiator == _oldOwner){ addOwner.isCanceled = true; emit AddOwnerRequestCanceled(); }else{ //@dev Trying to find _oldOwner in struct confirmators for (i = 0; i < addOwner.confirmators.length; i++){ if (addOwner.confirmators[i] == _oldOwner){ //@dev if _oldOwner confirmed this request he should be removed from confirmators addOwner.confirmators[i] = address(0); addOwner.confirms--; /** *@dev Struct can be confirmed each owner just once *so no sence to continue loop */ break; } } } } } /**@dev check actions in removeOwners requests *@dev check for empty struct */ if (removeOwners.initiator != address(0)){ //@dev check, can this request be approved by someone, if no then no sense to change something if (removeOwners.creationTimestamp + lifeTime >= uint32(now) && !removeOwners.isExecute && !removeOwners.isCanceled){ if(removeOwners.initiator == _oldOwner){ removeOwners.isCanceled = true; emit RemoveOwnerRequestCanceled(); }else{ //@dev Trying to find _oldOwner in struct confirmators for (i = 0; i < removeOwners.confirmators.length; i++){ if (removeOwners.confirmators[i] == _oldOwner){ //@dev if _oldOwner confirmed this request he should be removed from confirmators removeOwners.confirmators[i] = address(0); removeOwners.confirms--; /** *@dev Struct can be confirmed each owner just once *so no sence to continue loop */ break; } } } } } } }
Approve mint request, can be call only by owner which don't call this mint request before./
function approveNewMintRequest () public onlyOwners { require (!setNewMint.isExecute && !setNewMint.isCanceled); require (setNewMint.creationTimestamp + lifeTime >= uint32(now)); require (!mintingFinished); for (uint i = 0; i < setNewMint.confirmators.length; i++){ require(setNewMint.confirmators[i] != msg.sender); } setNewMint.confirms++; setNewMint.confirmators.push(msg.sender); if(setNewMint.confirms >= needApprovesToConfirm){ setNewMint.isExecute = true; token.mint(setNewMint.spender, setNewMint.value); } emit NewMintRequestUpdate(msg.sender, setNewMint.confirms, setNewMint.isExecute); }
1,769,947
pragma solidity ^0.4.24; import "../access/roles/ListerRole.sol"; import "../access/roles/UnlisterRole.sol"; /** * @title AddressList * * @dev Contract for maintaining a list of addresses, e.g. for a blacklist or whitelist. * This contract inherits the Lister contract to use RBAC for administering accounts that can add to the list. * This contract inherits the Unlister contract to use RBAC for administering accounts that can remove from the list. */ contract AddressList is ListerRole, UnlisterRole { /** Whether or not this contract has been initialized. */ bool private _initialized; /** Name of this AddressList, used as a display attribute only. */ string private _name; /** Mapping of each address to whether or not they're on the list. */ mapping (address => bool) private _onList; /** Event emitted whenever an address is added to the list. */ event AddressAdded(address indexed account); /** Event emitted whenever an address is removed from the list. */ event AddressRemoved(address indexed account); /** * @dev Initialize function used in place of a constructor. * This is required over a normal due to the constructor caveat when using proxy contracts. * * @param name The name of the address list */ function initialize(string name) external { // Assert that the contract hasn't already been initialized require(!_initialized); // Provide the account initializing the contract with access to the owner role super._addOwner(msg.sender); // Set the name of the list _name = name; // Set the initialized state to true so the contract cannot be initialized again _initialized = true; } /** * @return True if the contract has been initialized, otherwise false */ function initialized() external view returns (bool) { return _initialized; } /** * @return The name of the AddressList */ function name() external view returns (string) { return _name; } /** * @dev Query whether the the given `account` is on this list or not. * * @param account The account address being queried * @return True if the account is on the list, otherwise false */ function onList(address account) external view returns (bool) { return _onList[account]; } /** * @dev Update the name of the list. * Callable by an account with the listerAdmin role. * * @param newName The new display name of the list */ function updateName(string newName) external onlyListerAdmin { _name = newName; } /** * @dev Add the given `account` to the list. * Callable by an account with the lister role. * * @param account Account to add to the list */ function addAddress(address account) external onlyLister { _addAddress(account); } /** * @dev Remove the given `account` from the list. * Callable by an account with the unlister role. * * @param account Account to remove from the list */ function removeAddress(address account) external onlyUnlister { _removeAddress(account); } /** * @dev Replace the `previousAccount` in the list with the `newAccount`. * Callable by an account with both the lister role and unlister role. * * @param previousAccount Account to remove from the list * @param newAccount Account to add to the list */ function replaceAddress(address previousAccount, address newAccount) external onlyLister onlyUnlister { _removeAddress(previousAccount); _addAddress(newAccount); } /** * @dev Internal function that adds the given `account` to the `_onList` mapping. * Emits an AddressAdded event. * * @param account The account being added to the list */ function _addAddress(address account) internal { // Throw if the account is already on the list require(!_onList[account]); _onList[account] = true; emit AddressAdded(account); } /** * @dev Internal function that removes the given `account` from the `_onList` mapping. * Emits an AddressRemoved event. * * @param account The account being removed from the list */ function _removeAddress(address account) internal { // Throw if the account is not on the list require(_onList[account]); _onList[account] = false; emit AddressRemoved(account); } }
Whether or not this contract has been initialized. / Name of this AddressList, used as a display attribute only. / Mapping of each address to whether or not they're on the list. / Event emitted whenever an address is added to the list. / Event emitted whenever an address is removed from the list. / Initialize function used in place of a constructor. This is required over a normal due to the constructor caveat when using proxy contracts. name The name of the address list/ Assert that the contract hasn't already been initialized Provide the account initializing the contract with access to the owner role Set the name of the list Set the initialized state to true so the contract cannot be initialized again
function initialize(string name) external { require(!_initialized); super._addOwner(msg.sender); _name = name; _initialized = true; }
6,386,720
// SPDX-License-Identifier: Apache-2.0 // from https://github.com/ConsenSys/Project-Alchemy/blob/master/contracts/BLAKE2b/BLAKE2b.sol pragma solidity ^0.7.0; contract Blake2bConsenSys { uint64[8] public IV = [ 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179 ]; uint64 constant MASK_0 = 0xFF00000000000000; uint64 constant MASK_1 = 0x00FF000000000000; uint64 constant MASK_2 = 0x0000FF0000000000; uint64 constant MASK_3 = 0x000000FF00000000; uint64 constant MASK_4 = 0x00000000FF000000; uint64 constant MASK_5 = 0x0000000000FF0000; uint64 constant MASK_6 = 0x000000000000FF00; uint64 constant MASK_7 = 0x00000000000000FF; uint64 constant SHIFT_0 = 0x0100000000000000; uint64 constant SHIFT_1 = 0x0000010000000000; uint64 constant SHIFT_2 = 0x0000000001000000; uint64 constant SHIFT_3 = 0x0000000000000100; struct Blake2bConsenSys_ctx { uint256[4] b; //input buffer uint64[8] h; //chained state uint128 t; //total bytes uint64 c; //Size of b uint256 outlen; //diigest output size } // Mixing Function function G( uint64[16] memory v, uint256 a, uint256 b, uint256 c, uint256 d, uint64 x, uint64 y ) public pure { // Dereference to decrease memory reads uint64 va = v[a]; uint64 vb = v[b]; uint64 vc = v[c]; uint64 vd = v[d]; //Optimised mixing function assembly { // v[a] := (v[a] + v[b] + x) mod 2**64 va := addmod(add(va, vb), x, 0x10000000000000000) //v[d] := (v[d] ^ v[a]) >>> 32 vd := xor(div(xor(vd, va), 0x100000000), mulmod(xor(vd, va), 0x100000000, 0x10000000000000000)) //v[c] := (v[c] + v[d]) mod 2**64 vc := addmod(vc, vd, 0x10000000000000000) //v[b] := (v[b] ^ v[c]) >>> 24 vb := xor(div(xor(vb, vc), 0x1000000), mulmod(xor(vb, vc), 0x10000000000, 0x10000000000000000)) // v[a] := (v[a] + v[b] + y) mod 2**64 va := addmod(add(va, vb), y, 0x10000000000000000) //v[d] := (v[d] ^ v[a]) >>> 16 vd := xor(div(xor(vd, va), 0x10000), mulmod(xor(vd, va), 0x1000000000000, 0x10000000000000000)) //v[c] := (v[c] + v[d]) mod 2**64 vc := addmod(vc, vd, 0x10000000000000000) // v[b] := (v[b] ^ v[c]) >>> 63 vb := xor(div(xor(vb, vc), 0x8000000000000000), mulmod(xor(vb, vc), 0x2, 0x10000000000000000)) } v[a] = va; v[b] = vb; v[c] = vc; v[d] = vd; } function compress(Blake2bConsenSys_ctx memory ctx, bool last) internal view { //TODO: Look into storing these as uint256[4] uint64[16] memory v; uint64[16] memory m; for (uint256 i = 0; i < 8; i++) { v[i] = ctx.h[i]; // v[:8] = h[:8] v[i + 8] = IV[i]; // v[8:] = IV } // v[12] = v[12] ^ uint64(ctx.t % 2**64); //Lower word of t v[13] = v[13] ^ uint64(ctx.t / 2**64); if (last) v[14] = ~v[14]; //Finalization flag uint64 mi; //Temporary stack variable to decrease memory ops uint256 b; // Input buffer for (uint256 i = 0; i < 16; i++) { //Operate 16 words at a time uint256 k = i % 4; //Current buffer word mi = 0; if (k == 0) { b = ctx.b[i / 4]; //Load relevant input into buffer } //Extract relevent input from buffer assembly { mi := and(div(b, exp(2, mul(64, sub(3, k)))), 0xFFFFFFFFFFFFFFFF) } //Flip endianness m[i] = getWords(mi); } //Mix m G(v, 0, 4, 8, 12, m[0], m[1]); G(v, 1, 5, 9, 13, m[2], m[3]); G(v, 2, 6, 10, 14, m[4], m[5]); G(v, 3, 7, 11, 15, m[6], m[7]); G(v, 0, 5, 10, 15, m[8], m[9]); G(v, 1, 6, 11, 12, m[10], m[11]); G(v, 2, 7, 8, 13, m[12], m[13]); G(v, 3, 4, 9, 14, m[14], m[15]); G(v, 0, 4, 8, 12, m[14], m[10]); G(v, 1, 5, 9, 13, m[4], m[8]); G(v, 2, 6, 10, 14, m[9], m[15]); G(v, 3, 7, 11, 15, m[13], m[6]); G(v, 0, 5, 10, 15, m[1], m[12]); G(v, 1, 6, 11, 12, m[0], m[2]); G(v, 2, 7, 8, 13, m[11], m[7]); G(v, 3, 4, 9, 14, m[5], m[3]); G(v, 0, 4, 8, 12, m[11], m[8]); G(v, 1, 5, 9, 13, m[12], m[0]); G(v, 2, 6, 10, 14, m[5], m[2]); G(v, 3, 7, 11, 15, m[15], m[13]); G(v, 0, 5, 10, 15, m[10], m[14]); G(v, 1, 6, 11, 12, m[3], m[6]); G(v, 2, 7, 8, 13, m[7], m[1]); G(v, 3, 4, 9, 14, m[9], m[4]); G(v, 0, 4, 8, 12, m[7], m[9]); G(v, 1, 5, 9, 13, m[3], m[1]); G(v, 2, 6, 10, 14, m[13], m[12]); G(v, 3, 7, 11, 15, m[11], m[14]); G(v, 0, 5, 10, 15, m[2], m[6]); G(v, 1, 6, 11, 12, m[5], m[10]); G(v, 2, 7, 8, 13, m[4], m[0]); G(v, 3, 4, 9, 14, m[15], m[8]); G(v, 0, 4, 8, 12, m[9], m[0]); G(v, 1, 5, 9, 13, m[5], m[7]); G(v, 2, 6, 10, 14, m[2], m[4]); G(v, 3, 7, 11, 15, m[10], m[15]); G(v, 0, 5, 10, 15, m[14], m[1]); G(v, 1, 6, 11, 12, m[11], m[12]); G(v, 2, 7, 8, 13, m[6], m[8]); G(v, 3, 4, 9, 14, m[3], m[13]); G(v, 0, 4, 8, 12, m[2], m[12]); G(v, 1, 5, 9, 13, m[6], m[10]); G(v, 2, 6, 10, 14, m[0], m[11]); G(v, 3, 7, 11, 15, m[8], m[3]); G(v, 0, 5, 10, 15, m[4], m[13]); G(v, 1, 6, 11, 12, m[7], m[5]); G(v, 2, 7, 8, 13, m[15], m[14]); G(v, 3, 4, 9, 14, m[1], m[9]); G(v, 0, 4, 8, 12, m[12], m[5]); G(v, 1, 5, 9, 13, m[1], m[15]); G(v, 2, 6, 10, 14, m[14], m[13]); G(v, 3, 7, 11, 15, m[4], m[10]); G(v, 0, 5, 10, 15, m[0], m[7]); G(v, 1, 6, 11, 12, m[6], m[3]); G(v, 2, 7, 8, 13, m[9], m[2]); G(v, 3, 4, 9, 14, m[8], m[11]); G(v, 0, 4, 8, 12, m[13], m[11]); G(v, 1, 5, 9, 13, m[7], m[14]); G(v, 2, 6, 10, 14, m[12], m[1]); G(v, 3, 7, 11, 15, m[3], m[9]); G(v, 0, 5, 10, 15, m[5], m[0]); G(v, 1, 6, 11, 12, m[15], m[4]); G(v, 2, 7, 8, 13, m[8], m[6]); G(v, 3, 4, 9, 14, m[2], m[10]); G(v, 0, 4, 8, 12, m[6], m[15]); G(v, 1, 5, 9, 13, m[14], m[9]); G(v, 2, 6, 10, 14, m[11], m[3]); G(v, 3, 7, 11, 15, m[0], m[8]); G(v, 0, 5, 10, 15, m[12], m[2]); G(v, 1, 6, 11, 12, m[13], m[7]); G(v, 2, 7, 8, 13, m[1], m[4]); G(v, 3, 4, 9, 14, m[10], m[5]); G(v, 0, 4, 8, 12, m[10], m[2]); G(v, 1, 5, 9, 13, m[8], m[4]); G(v, 2, 6, 10, 14, m[7], m[6]); G(v, 3, 7, 11, 15, m[1], m[5]); G(v, 0, 5, 10, 15, m[15], m[11]); G(v, 1, 6, 11, 12, m[9], m[14]); G(v, 2, 7, 8, 13, m[3], m[12]); G(v, 3, 4, 9, 14, m[13], m[0]); G(v, 0, 4, 8, 12, m[0], m[1]); G(v, 1, 5, 9, 13, m[2], m[3]); G(v, 2, 6, 10, 14, m[4], m[5]); G(v, 3, 7, 11, 15, m[6], m[7]); G(v, 0, 5, 10, 15, m[8], m[9]); G(v, 1, 6, 11, 12, m[10], m[11]); G(v, 2, 7, 8, 13, m[12], m[13]); G(v, 3, 4, 9, 14, m[14], m[15]); G(v, 0, 4, 8, 12, m[14], m[10]); G(v, 1, 5, 9, 13, m[4], m[8]); G(v, 2, 6, 10, 14, m[9], m[15]); G(v, 3, 7, 11, 15, m[13], m[6]); G(v, 0, 5, 10, 15, m[1], m[12]); G(v, 1, 6, 11, 12, m[0], m[2]); G(v, 2, 7, 8, 13, m[11], m[7]); G(v, 3, 4, 9, 14, m[5], m[3]); //XOR current state with both halves of v for (uint256 i = 0; i < 8; ++i) { ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 8]; } } function init( Blake2bConsenSys_ctx memory ctx, uint64 outlen, bytes memory key, uint64[2] memory salt, uint64[2] memory person ) internal view { if (outlen == 0 || outlen > 64 || key.length > 64) revert(); //Initialize chained-state to IV for (uint256 j = 0; j < 8; j++) { ctx.h[j] = IV[j]; } // Set up parameter block ctx.h[0] = ctx.h[0] ^ 0x01010000 ^ shift_left(uint64(key.length), 8) ^ outlen; ctx.h[4] = ctx.h[4] ^ salt[0]; ctx.h[5] = ctx.h[5] ^ salt[1]; ctx.h[6] = ctx.h[6] ^ person[0]; ctx.h[7] = ctx.h[7] ^ person[1]; ctx.outlen = outlen; //Run hash once with key as input if (key.length > 0) { update(ctx, key); ctx.c = 128; } } function update(Blake2bConsenSys_ctx memory ctx, bytes memory input) internal view { for (uint256 i = 0; i < input.length; i++) { //If buffer is full, update byte counters and compress if (ctx.c == 128) { ctx.t += ctx.c; compress(ctx, false); ctx.c = 0; } //Update temporary counter c uint256 c = ctx.c++; // b -> ctx.b uint256[4] memory b = ctx.b; uint8 a = uint8(input[i]); // ctx.b[c] = a assembly { mstore8(add(b, c), a) } } } function finalize(Blake2bConsenSys_ctx memory ctx, uint64[8] memory out) internal view { // Add any uncounted bytes ctx.t += ctx.c; // Compress with finalization flag compress(ctx, true); //Flip little to big endian and store in output buffer for (uint256 i = 0; i < ctx.outlen / 8; i++) { out[i] = getWords(ctx.h[i]); } //Properly pad output if it doesn't fill a full word if (ctx.outlen < 64) { out[ctx.outlen / 8] = shift_right(getWords(ctx.h[ctx.outlen / 8]), 64 - 8 * (ctx.outlen % 8)); } } //Helper function for full hash function function blake2b( bytes memory input, bytes memory key, bytes memory salt, bytes memory personalization, uint64 outlen ) public view returns (uint64[8] memory) { Blake2bConsenSys_ctx memory ctx; uint64[8] memory out; init(ctx, outlen, key, formatInput(salt), formatInput(personalization)); update(ctx, input); finalize(ctx, out); return out; } function blake2b( bytes memory input, bytes memory key, uint64 outlen ) public view returns (uint64[8] memory) { return blake2b(input, key, "", "", outlen); } // Utility functions //Flips endianness of words function getWords(uint64 a) public pure returns (uint64 b) { return ((a & MASK_0) / SHIFT_0) ^ ((a & MASK_1) / SHIFT_1) ^ ((a & MASK_2) / SHIFT_2) ^ ((a & MASK_3) / SHIFT_3) ^ ((a & MASK_4) * SHIFT_3) ^ ((a & MASK_5) * SHIFT_2) ^ ((a & MASK_6) * SHIFT_1) ^ ((a & MASK_7) * SHIFT_0); } function shift_right(uint64 a, uint256 shift) public pure returns (uint64 b) { return uint64(a / 2**shift); } function shift_left(uint64 a, uint256 shift) public pure returns (uint64) { return uint64((a * 2**shift) % (2**64)); } //bytes -> uint64[2] function formatInput(bytes memory input) public pure returns (uint64[2] memory output) { for (uint256 i = 0; i < input.length; i++) { output[i / 8] = output[i / 8] ^ shift_left(uint64(uint8(input[i])), 64 - 8 * ((i % 8) + 1)); } output[0] = getWords(output[0]); output[1] = getWords(output[1]); } function formatOutput(uint64[8] memory input) public pure returns (bytes32[2] memory) { bytes32[2] memory result; for (uint256 i = 0; i < 8; i++) { result[i / 4] = result[i / 4] ^ bytes32(input[i] * 2**(64 * (3 - (i % 4)))); } return result; } }
Add any uncounted bytes Compress with finalization flagFlip little to big endian and store in output bufferProperly pad output if it doesn't fill a full word
function finalize(Blake2bConsenSys_ctx memory ctx, uint64[8] memory out) internal view { ctx.t += ctx.c; compress(ctx, true); for (uint256 i = 0; i < ctx.outlen / 8; i++) { out[i] = getWords(ctx.h[i]); } if (ctx.outlen < 64) { out[ctx.outlen / 8] = shift_right(getWords(ctx.h[ctx.outlen / 8]), 64 - 8 * (ctx.outlen % 8)); } }
13,017,358