file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// 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; } } // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @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; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Context} from "Context.sol"; import {Initializable} from "Initializable.sol"; /** * @title UpgradeableClaimable * @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. Since * this contract combines Claimable and UpgradableOwnable contracts, ownership * can be later change via 2 step method {transferOwnership} and {claimOwnership} * * 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 UpgradeableClaimable is Initializable, Context { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting a custom initial owner of choice. * @param __owner Initial owner of contract to be set. */ function initialize(address __owner) internal initializer { _owner = __owner; emit OwnershipTransferred(address(0), __owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view returns (address) { return _pendingOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner, "Ownable: caller is not the pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; _pendingOwner = address(0); } } // 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; /** * @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; import "IERC20.sol"; import "SafeMath.sol"; import "Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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.10; import {Address} from "Address.sol"; import {Context} from "Context.sol"; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {Initializable} from "Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, 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. */ function __ERC20_initialize(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public virtual view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero") ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function updateNameAndSymbol(string memory __name, string memory __symbol) internal { _name = __name; _symbol = __symbol; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface ITrueLender2 { // @dev calculate overall value of the pools function value(ITrueFiPool2 pool) external view returns (uint256); // @dev distribute a basket of tokens for exiting user function distribute( address recipient, uint256 numerator, uint256 denominator ) external; function transferAllLoanTokens(ILoanToken2 loan, address recipient) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface IERC20WithDecimals is IERC20 { function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20WithDecimals} from "IERC20WithDecimals.sol"; /** * @dev Oracle that converts any token to and from TRU * Used for liquidations and valuing of liquidated TRU in the pool */ interface ITrueFiPoolOracle { // token address function token() external view returns (IERC20WithDecimals); // amount of tokens 1 TRU is worth function truToToken(uint256 truAmount) external view returns (uint256); // amount of TRU 1 token is worth function tokenToTru(uint256 tokenAmount) external view returns (uint256); // USD price of token with 18 decimals function tokenToUsd(uint256 tokenAmount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; pragma experimental ABIEncoderV2; interface I1Inch3 { struct SwapDescription { address srcToken; address dstToken; address srcReceiver; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; } function swap( address caller, SwapDescription calldata desc, bytes calldata data ) external returns ( uint256 returnAmount, uint256 gasLeft, uint256 chiSpent ); function unoswap( address srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata /* pools */ ) external payable returns (uint256 returnAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface IDeficiencyToken is IERC20 { function loan() external view returns (ILoanToken2); function burnFrom(address account, uint256 amount) external; function version() external pure returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IDeficiencyToken} from "IDeficiencyToken.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface ISAFU { function poolDeficit(address pool) external view returns (uint256); function deficiencyToken(ILoanToken2 loan) external view returns (IDeficiencyToken); function reclaim(ILoanToken2 loan, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ERC20, IERC20} from "UpgradeableERC20.sol"; import {ITrueLender2, ILoanToken2} from "ITrueLender2.sol"; import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol"; import {I1Inch3} from "I1Inch3.sol"; import {ISAFU} from "ISAFU.sol"; interface ITrueFiPool2 is IERC20 { function initialize( ERC20 _token, ITrueLender2 _lender, ISAFU safu, address __owner ) external; function singleBorrowerInitialize( ERC20 _token, ITrueLender2 _lender, ISAFU safu, address __owner, string memory borrowerName, string memory borrowerSymbol ) external; function token() external view returns (ERC20); function oracle() external view returns (ITrueFiPoolOracle); function poolValue() external view returns (uint256); /** * @dev Ratio of liquid assets in the pool after lending * @param afterAmountLent Amount of asset being lent */ function liquidRatio(uint256 afterAmountLent) external view returns (uint256); /** * @dev Join the pool by depositing tokens * @param amount amount of tokens to deposit */ function join(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount) external; /** * @dev pay borrowed money back to pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 currencyAmount) external; /** * @dev SAFU buys LoanTokens from the pool */ function liquidate(ILoanToken2 loan) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ERC20} from "UpgradeableERC20.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanToken2 is IERC20 { enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated} function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function pool() external view returns (ITrueFiPool2); function profit() external view returns (uint256); function status() external view returns (Status); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function settle() external; function enterDefault() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function repayInFull(address _sender) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function isRepaid() external view returns (bool); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function token() external view returns (ERC20); function version() external pure returns (uint8); } //interface IContractWithPool { // function pool() external view returns (ITrueFiPool2); //} // //// Had to be split because of multiple inheritance problem //interface ILoanToken2 is ILoanToken, IContractWithPool { // //} // SPDX-License-Identifier: MIT pragma solidity 0.6.10; interface IPoolFactory { function isPool(address pool) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface IStakingPool is IERC20 { function stakeSupply() external view returns (uint256); function withdraw(uint256 amount) external; function payFee(uint256 amount, uint256 endTime) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanFactory2 { function createLoanToken( ITrueFiPool2 _pool, uint256 _amount, uint256 _term ) external; function isLoanToken(address) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {UpgradeableClaimable} from "UpgradeableClaimable.sol"; import {IERC20} from "IERC20.sol"; import {SafeERC20} from "SafeERC20.sol"; import {ILoanToken2} from "ILoanToken2.sol"; import {IPoolFactory} from "IPoolFactory.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; import {IStakingPool} from "IStakingPool.sol"; import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol"; import {ILoanFactory2} from "ILoanFactory2.sol"; import {SafeMath} from "SafeMath.sol"; /** * @title Liquidator2 * @notice Liquidate LoanTokens with this Contract * @dev When a Loan becomes defaulted, Liquidator allows to * compensate pool participants, by transferring some of TRU to the pool */ contract Liquidator2 is UpgradeableClaimable { using SafeMath for uint256; using SafeERC20 for IERC20; // basis point for ratio uint256 private constant BASIS_RATIO = 10000; // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== IStakingPool public stkTru; IERC20 public tru; ILoanFactory2 public loanFactory; mapping(address => bool) public approvedTokens; // max share of tru to be taken from staking pool during liquidation // 1000 -> 10% uint256 public fetchMaxShare; // Address of SAFU fund, to which slashed tru is transferred after liquidation address public SAFU; // ======= STORAGE DECLARATION END ============ /** * @dev Emitted fetch max share is changed * @param newShare New share set */ event FetchMaxShareChanged(uint256 newShare); /** * @dev Emitted when whitelist status for a token changes * @param token Address of token * @param status New whitelist status */ event WhitelistStatusChanged(address token, bool status); /** * @dev Emitted when a loan gets liquidated * @param loan Loan that has been liquidated * @param defaultedValue Remaining loan debt to repay * @param withdrawnTru Amount of TRU transferred to compensate defaulted loan */ event Liquidated(ILoanToken2 loan, uint256 defaultedValue, uint256 withdrawnTru); /** * @dev Emitted when SAFU is changed * @param SAFU New SAFU address */ event AssuranceChanged(address SAFU); /** * @dev Initialize this contract */ function initialize( IStakingPool _stkTru, IERC20 _tru, ILoanFactory2 _loanFactory, address _SAFU ) public initializer { UpgradeableClaimable.initialize(msg.sender); stkTru = _stkTru; tru = _tru; loanFactory = _loanFactory; SAFU = _SAFU; fetchMaxShare = 1000; } /** * @dev Set a new SAFU address * @param _SAFU Address to be set as SAFU */ function setAssurance(address _SAFU) external onlyOwner { SAFU = _SAFU; emit AssuranceChanged(_SAFU); } /** * @dev Set new max fetch share * @param newShare New share to be set */ function setFetchMaxShare(uint256 newShare) external onlyOwner { require(newShare > 0, "Liquidator: Share cannot be set to 0"); require(newShare <= BASIS_RATIO, "Liquidator: Share cannot be larger than 10000"); fetchMaxShare = newShare; emit FetchMaxShareChanged(newShare); } /** * @dev Change whitelist status of a token for liquidations * @param token Address of token to change whitelist status * @param status New whitelist status for token */ function setTokenApproval(address token, bool status) external onlyOwner { approvedTokens[token] = status; emit WhitelistStatusChanged(token, status); } /** * @dev Liquidates a defaulted Loan, withdraws a portion of tru from staking pool * then transfers tru to TrueFiPool as compensation * @param loan Loan to be liquidated */ function liquidate(ILoanToken2 loan) external { require(msg.sender == SAFU, "Liquidator: Only SAFU contract can liquidate a loan"); require(loanFactory.isLoanToken(address(loan)), "Liquidator: Unknown loan"); require(loan.status() == ILoanToken2.Status.Defaulted, "Liquidator: Loan must be defaulted"); ITrueFiPool2 pool = ITrueFiPool2(loan.pool()); require(approvedTokens[address(pool.token())], "Liquidator: Token not approved for default protection"); uint256 defaultedValue = loan.debt().sub(loan.repaid()); uint256 withdrawnTru = getAmountToWithdraw(defaultedValue, ITrueFiPoolOracle(pool.oracle())); stkTru.withdraw(withdrawnTru); loan.liquidate(); tru.safeTransfer(SAFU, withdrawnTru); emit Liquidated(loan, defaultedValue, withdrawnTru); } /** * @dev Calculate amount of tru to be withdrawn from staking pool (not more than preset share) * @param deficit Amount of tusd lost on defaulted loan * @return amount of TRU to be withdrawn on liquidation */ function getAmountToWithdraw(uint256 deficit, ITrueFiPoolOracle oracle) internal view returns (uint256) { uint256 stakingPoolSupply = stkTru.stakeSupply(); uint256 maxWithdrawValue = stakingPoolSupply.mul(fetchMaxShare).div(BASIS_RATIO); uint256 deficitInTru = oracle.tokenToTru(deficit); return maxWithdrawValue > deficitInTru ? deficitInTru : maxWithdrawValue; } }
Emitted fetch max share is changed newShare New share set/ Emitted when whitelist status for a token changes token Address of token status New whitelist status/ Emitted when a loan gets liquidated loan Loan that has been liquidated defaultedValue Remaining loan debt to repay withdrawnTru Amount of TRU transferred to compensate defaulted loan/ Emitted when SAFU is changed SAFU New SAFU address/ Initialize this contract/
function swap( address caller, SwapDescription calldata desc, bytes calldata data ) external returns ( uint256 returnAmount, uint256 gasLeft, uint256 chiSpent ); function unoswap( address srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata /* pools */ ) external payable returns (uint256 returnAmount); } pragma solidity 0.6.10; } pragma solidity 0.6.10; } pragma solidity 0.6.10; } pragma solidity 0.6.10; } pragma solidity 0.6.10; } pragma solidity 0.6.10; } pragma solidity 0.6.10; } pragma solidity 0.6.10; ) public initializer { UpgradeableClaimable.initialize(msg.sender); stkTru = _stkTru; tru = _tru; loanFactory = _loanFactory; SAFU = _SAFU; fetchMaxShare = 1000; }
6,228,205
pragma solidity ^0.5.13; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "../common/FixidityLib.sol"; import "../common/Initializable.sol"; import "../common/UsingRegistry.sol"; import "../common/interfaces/ICeloVersionedContract.sol"; import "../common/libraries/ReentrancyGuard.sol"; import "../stability/interfaces/IStableToken.sol"; /** * @title Facilitates large exchanges between CELO stable tokens. */ contract GrandaMento is ICeloVersionedContract, Ownable, Initializable, UsingRegistry, ReentrancyGuard { using FixidityLib for FixidityLib.Fraction; using SafeMath for uint256; // Emitted when a new exchange proposal is created. event ExchangeProposalCreated( uint256 indexed proposalId, address indexed exchanger, string stableTokenRegistryId, uint256 sellAmount, uint256 buyAmount, bool sellCelo ); // Emitted when an exchange proposal is approved by the approver. event ExchangeProposalApproved(uint256 indexed proposalId); // Emitted when an exchange proposal is cancelled. event ExchangeProposalCancelled(uint256 indexed proposalId); // Emitted when an exchange proposal is executed. event ExchangeProposalExecuted(uint256 indexed proposalId); // Emitted when the approver is set. event ApproverSet(address approver); // Emitted when maxApprovalExchangeRateChange is set. event MaxApprovalExchangeRateChangeSet(uint256 maxApprovalExchangeRateChange); // Emitted when the spread is set. event SpreadSet(uint256 spread); // Emitted when the veto period in seconds is set. event VetoPeriodSecondsSet(uint256 vetoPeriodSeconds); // Emitted when the exchange limits for a stable token are set. event StableTokenExchangeLimitsSet( string stableTokenRegistryId, uint256 minExchangeAmount, uint256 maxExchangeAmount ); enum ExchangeProposalState { None, Proposed, Approved, Executed, Cancelled } struct ExchangeLimits { // The minimum amount of an asset that can be exchanged in a single proposal. uint256 minExchangeAmount; // The maximum amount of an asset that can be exchanged in a single proposal. uint256 maxExchangeAmount; } struct ExchangeProposal { // The exchanger/proposer of the exchange proposal. address payable exchanger; // The stable token involved in this proposal. This is stored rather than // the stable token's registry ID in case the contract address is changed // after a proposal is created, which could affect refunding or burning the // stable token. address stableToken; // The state of the exchange proposal. ExchangeProposalState state; // Whether the exchanger is selling CELO and buying stableToken. bool sellCelo; // The amount of the sell token being sold. If a stable token is being sold, // the amount of stable token in "units" is stored rather than the "value." // This is because stable tokens may experience demurrage/inflation, where // the amount of stable token "units" doesn't change with time, but the "value" // does. This is important to ensure the correct inflation-adjusted amount // of the stable token is transferred out of this contract when a deposit is // refunded or an exchange selling the stable token is executed. // See StableToken.sol for more details on what "units" vs "values" are. uint256 sellAmount; // The amount of the buy token being bought. For stable tokens, this is // kept track of as the value, not units. uint256 buyAmount; // The price of CELO quoted in stableToken at the time of the exchange proposal // creation. This is the price used to calculate the buyAmount. Used for a // safety check when an approval is being made that the price isn't wildly // different. Recalculating buyAmount is not sufficient because if a stable token // is being sold that has demurrage enabled, the original value when the stable // tokens were deposited cannot be calculated. uint256 celoStableTokenExchangeRate; // The veto period in seconds at the time the proposal was created. This is kept // track of on a per-proposal basis to lock-in the veto period for a proposal so // that changes to the contract's vetoPeriodSeconds do not affect existing // proposals. uint256 vetoPeriodSeconds; // The timestamp (`block.timestamp`) at which the exchange proposal was approved // in seconds. If the exchange proposal has not ever been approved, is 0. uint256 approvalTimestamp; } // The address with the authority to approve exchange proposals. address public approver; // The maximum allowed change in the CELO/stable token price when an exchange proposal // is being approved relative to the rate when the exchange proposal was created. FixidityLib.Fraction public maxApprovalExchangeRateChange; // The percent fee imposed upon an exchange execution. FixidityLib.Fraction public spread; // The period in seconds after an approval during which an exchange proposal can be vetoed. uint256 public vetoPeriodSeconds; // The minimum and maximum amount of the stable token that can be minted or // burned in a single exchange. Indexed by the stable token registry identifier string. mapping(string => ExchangeLimits) public stableTokenExchangeLimits; // State for all exchange proposals. Indexed by the exchange proposal ID. mapping(uint256 => ExchangeProposal) public exchangeProposals; // An array containing a superset of the IDs of exchange proposals that are currently // in the Proposed or Approved state. Intended to allow easy viewing of all active // exchange proposals. It's possible for a proposal ID in this array to no longer be // active, so filtering is required to find the true set of active proposal IDs. // A superset is kept because exchange proposal vetoes, intended to be done // by Governance, effectively go through a multi-day timelock. If the veto // call was required to provide the index in an array of activeProposalIds to // remove corresponding to the vetoed exchange proposal, the timelock could result // in the provided index being stale by the time the veto would be executed. // Alternative approaches exist, like maintaining a linkedlist of active proposal // IDs, but this approach was chosen for its low implementation complexity. uint256[] public activeProposalIdsSuperset; // Number of exchange proposals that have ever been created. Used for assigning // an exchange proposal ID to a new proposal. uint256 public exchangeProposalCount; /** * @notice Reverts if the sender is not the approver. */ modifier onlyApprover() { require(msg.sender == approver, "Sender must be approver"); _; } /** * @notice Sets initialized == true on implementation contracts. * @param test Set to true to skip implementation initialization. */ constructor(bool test) public Initializable(test) {} /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 1, 0, 0); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param _registry The address of the registry. * @param _approver The approver that has the ability to approve exchange proposals. * @param _maxApprovalExchangeRateChange The maximum allowed change in CELO price * between an exchange proposal's creation and approval. * @param _spread The spread charged on exchanges. * @param _vetoPeriodSeconds The length of the veto period in seconds. */ function initialize( address _registry, address _approver, uint256 _maxApprovalExchangeRateChange, uint256 _spread, uint256 _vetoPeriodSeconds ) external initializer { _transferOwnership(msg.sender); setRegistry(_registry); setApprover(_approver); setMaxApprovalExchangeRateChange(_maxApprovalExchangeRateChange); setSpread(_spread); setVetoPeriodSeconds(_vetoPeriodSeconds); } /** * @notice Creates a new exchange proposal and deposits the tokens being sold. * @dev Stable token value amounts are used for the sellAmount, not unit amounts. * @param stableTokenRegistryId The string registry ID for the stable token * involved in the exchange. * @param sellAmount The amount of the sell token being sold. * @param sellCelo Whether CELO is being sold. * @return The proposal identifier for the newly created exchange proposal. */ function createExchangeProposal( string calldata stableTokenRegistryId, uint256 sellAmount, bool sellCelo ) external nonReentrant returns (uint256) { address stableToken = registry.getAddressForStringOrDie(stableTokenRegistryId); // Gets the price of CELO quoted in stableToken. uint256 celoStableTokenExchangeRate = getOracleExchangeRate(stableToken).unwrap(); // Using the current oracle exchange rate, calculate what the buy amount is. // This takes the spread into consideration. uint256 buyAmount = getBuyAmount(celoStableTokenExchangeRate, sellAmount, sellCelo); // Create new scope to prevent a stack too deep error. { // Get the minimum and maximum amount of stable token than can be involved // in the exchange. This reverts if exchange limits for the stable token have // not been set. (uint256 minExchangeAmount, uint256 maxExchangeAmount) = getStableTokenExchangeLimits( stableTokenRegistryId ); // Ensure that the amount of stableToken being bought or sold is within // the configurable exchange limits. uint256 stableTokenExchangeAmount = sellCelo ? buyAmount : sellAmount; require( stableTokenExchangeAmount <= maxExchangeAmount && stableTokenExchangeAmount >= minExchangeAmount, "Stable token exchange amount not within limits" ); } // Deposit the assets being sold. IERC20 sellToken = sellCelo ? getGoldToken() : IERC20(stableToken); require( sellToken.transferFrom(msg.sender, address(this), sellAmount), "Transfer in of sell token failed" ); // Record the proposal. // Add 1 to the running proposal count, and use the updated proposal count as // the proposal ID. Proposal IDs intentionally start at 1. exchangeProposalCount = exchangeProposalCount.add(1); // For stable tokens, the amount is stored in units to deal with demurrage. uint256 storedSellAmount = sellCelo ? sellAmount : IStableToken(stableToken).valueToUnits(sellAmount); exchangeProposals[exchangeProposalCount] = ExchangeProposal({ exchanger: msg.sender, stableToken: stableToken, state: ExchangeProposalState.Proposed, sellCelo: sellCelo, sellAmount: storedSellAmount, buyAmount: buyAmount, celoStableTokenExchangeRate: celoStableTokenExchangeRate, vetoPeriodSeconds: vetoPeriodSeconds, approvalTimestamp: 0 // initial value when not approved yet }); // StableToken.unitsToValue (called within getSellTokenAndSellAmount) can // overflow for very large StableToken amounts. Call it here as a sanity // check, so that the overflow happens here, blocking proposal creation // rather than when attempting to execute the proposal, which would lock // funds in this contract. getSellTokenAndSellAmount(exchangeProposals[exchangeProposalCount]); // Push it into the array of active proposals. activeProposalIdsSuperset.push(exchangeProposalCount); // Even if stable tokens are being sold, the sellAmount emitted is the "value." emit ExchangeProposalCreated( exchangeProposalCount, msg.sender, stableTokenRegistryId, sellAmount, buyAmount, sellCelo ); return exchangeProposalCount; } /** * @notice Approves an existing exchange proposal. * @dev Sender must be the approver. Exchange proposal must be in the Proposed state. * @param proposalId The identifier of the proposal to approve. */ function approveExchangeProposal(uint256 proposalId) external nonReentrant onlyApprover { ExchangeProposal storage proposal = exchangeProposals[proposalId]; // Ensure the proposal is in the Proposed state. require(proposal.state == ExchangeProposalState.Proposed, "Proposal must be in Proposed state"); // Ensure the change in the current price of CELO quoted in the stable token // relative to the value when the proposal was created is within the allowed limit. FixidityLib.Fraction memory currentRate = getOracleExchangeRate(proposal.stableToken); FixidityLib.Fraction memory proposalRate = FixidityLib.wrap( proposal.celoStableTokenExchangeRate ); (FixidityLib.Fraction memory lesserRate, FixidityLib.Fraction memory greaterRate) = currentRate .lt(proposalRate) ? (currentRate, proposalRate) : (proposalRate, currentRate); FixidityLib.Fraction memory rateChange = greaterRate.subtract(lesserRate).divide(proposalRate); require( rateChange.lte(maxApprovalExchangeRateChange), "CELO exchange rate is too different from the proposed price" ); // Set the time the approval occurred and change the state. proposal.approvalTimestamp = block.timestamp; proposal.state = ExchangeProposalState.Approved; emit ExchangeProposalApproved(proposalId); } /** * @notice Cancels an exchange proposal. * @dev Only callable by the exchanger if the proposal is in the Proposed state * or the owner if the proposal is in the Approved state. * @param proposalId The identifier of the proposal to cancel. */ function cancelExchangeProposal(uint256 proposalId) external nonReentrant { ExchangeProposal storage proposal = exchangeProposals[proposalId]; // Require the appropriate state and sender. // This will also revert if a proposalId is given that does not correspond // to a previously created exchange proposal. if (proposal.state == ExchangeProposalState.Proposed) { require(proposal.exchanger == msg.sender, "Sender must be exchanger"); } else if (proposal.state == ExchangeProposalState.Approved) { require(isOwner(), "Sender must be owner"); } else { revert("Proposal must be in Proposed or Approved state"); } // Mark the proposal as cancelled. Do so prior to refunding as a measure against reentrancy. proposal.state = ExchangeProposalState.Cancelled; // Get the token and amount that will be refunded to the proposer. (IERC20 refundToken, uint256 refundAmount) = getSellTokenAndSellAmount(proposal); // Finally, transfer out the deposited funds. require( refundToken.transfer(proposal.exchanger, refundAmount), "Transfer out of refund token failed" ); emit ExchangeProposalCancelled(proposalId); } /** * @notice Executes an exchange proposal that's been approved and not vetoed. * @dev Callable by anyone. Reverts if the proposal is not in the Approved state * or proposal.vetoPeriodSeconds has not elapsed since approval. * @param proposalId The identifier of the proposal to execute. */ function executeExchangeProposal(uint256 proposalId) external nonReentrant { ExchangeProposal storage proposal = exchangeProposals[proposalId]; // Require that the proposal is in the Approved state. require(proposal.state == ExchangeProposalState.Approved, "Proposal must be in Approved state"); // Require that the veto period has elapsed since the approval time. require( proposal.approvalTimestamp.add(proposal.vetoPeriodSeconds) <= block.timestamp, "Veto period not elapsed" ); // Mark the proposal as executed. Do so prior to exchanging as a measure against reentrancy. proposal.state = ExchangeProposalState.Executed; // Perform the exchange. (IERC20 sellToken, uint256 sellAmount) = getSellTokenAndSellAmount(proposal); // If the exchange sells CELO, the CELO is sent to the Reserve from this contract // and stable token is minted to the exchanger. if (proposal.sellCelo) { // Send the CELO from this contract to the reserve. require( sellToken.transfer(address(getReserve()), sellAmount), "Transfer out of CELO to Reserve failed" ); // Mint stable token to the exchanger. require( IStableToken(proposal.stableToken).mint(proposal.exchanger, proposal.buyAmount), "Stable token mint failed" ); } else { // If the exchange is selling stable token, the stable token is burned from // this contract and CELO is transferred from the Reserve to the exchanger. // Burn the stable token from this contract. require(IStableToken(proposal.stableToken).burn(sellAmount), "Stable token burn failed"); // Transfer the CELO from the Reserve to the exchanger. require( getReserve().transferExchangeGold(proposal.exchanger, proposal.buyAmount), "Transfer out of CELO from Reserve failed" ); } emit ExchangeProposalExecuted(proposalId); } /** * @notice Gets the sell token and the sell amount for a proposal. * @dev For stable token sell amounts that are stored as units, the value * is returned. Ensures sell amount is not greater than this contract's balance. * @param proposal The proposal to get the sell token and sell amount for. * @return (the IERC20 sell token, the value sell amount). */ function getSellTokenAndSellAmount(ExchangeProposal memory proposal) private view returns (IERC20, uint256) { IERC20 sellToken; uint256 sellAmount; if (proposal.sellCelo) { sellToken = getGoldToken(); sellAmount = proposal.sellAmount; } else { address stableToken = proposal.stableToken; sellToken = IERC20(stableToken); // When selling stableToken, the sell amount is stored in units. // Units must be converted to value when refunding. sellAmount = IStableToken(stableToken).unitsToValue(proposal.sellAmount); } // In the event a precision issue from the unit <-> value calculations results // in sellAmount being greater than this contract's balance, set the sellAmount // to the entire balance. // This check should not be necessary for CELO, but is done so regardless // for extra certainty that cancelling an exchange proposal can never fail // if for some reason the CELO balance of this contract is less than the // recorded sell amount. uint256 totalBalance = sellToken.balanceOf(address(this)); if (totalBalance < sellAmount) { sellAmount = totalBalance; } return (sellToken, sellAmount); } /** * @notice Using the oracle price, charges the spread and calculates the amount of * the asset being bought. * @dev Stable token value amounts are used for the sellAmount, not unit amounts. * Assumes both CELO and the stable token have 18 decimals. * @param celoStableTokenExchangeRate The unwrapped fraction exchange rate of CELO * quoted in the stable token. * @param sellAmount The amount of the sell token being sold. * @param sellCelo Whether CELO is being sold. * @return The amount of the asset being bought. */ function getBuyAmount(uint256 celoStableTokenExchangeRate, uint256 sellAmount, bool sellCelo) public view returns (uint256) { FixidityLib.Fraction memory exchangeRate = FixidityLib.wrap(celoStableTokenExchangeRate); // If stableToken is being sold, instead use the price of stableToken // quoted in CELO. if (!sellCelo) { exchangeRate = exchangeRate.reciprocal(); } // The sell amount taking the spread into account, ie: // (1 - spread) * sellAmount FixidityLib.Fraction memory adjustedSellAmount = FixidityLib.fixed1().subtract(spread).multiply( FixidityLib.newFixed(sellAmount) ); // Calculate the buy amount: // exchangeRate * adjustedSellAmount return exchangeRate.multiply(adjustedSellAmount).fromFixed(); } /** * @notice Removes the proposal ID found at the provided index of activeProposalIdsSuperset * if the exchange proposal is not active. * @dev Anyone can call. Reverts if the exchange proposal is active. * @param index The index of the proposal ID to remove from activeProposalIdsSuperset. */ function removeFromActiveProposalIdsSuperset(uint256 index) external { require(index < activeProposalIdsSuperset.length, "Index out of bounds"); uint256 proposalId = activeProposalIdsSuperset[index]; // Require the exchange proposal to be inactive. require( exchangeProposals[proposalId].state != ExchangeProposalState.Proposed && exchangeProposals[proposalId].state != ExchangeProposalState.Approved, "Exchange proposal not inactive" ); // If not removing the last element, overwrite the index with the value of // the last element. uint256 lastIndex = activeProposalIdsSuperset.length.sub(1); if (index < lastIndex) { activeProposalIdsSuperset[index] = activeProposalIdsSuperset[lastIndex]; } // Delete the last element. activeProposalIdsSuperset.length--; } /** * @notice Gets the proposal identifiers of exchange proposals in the * Proposed or Approved state. Returns a version of activeProposalIdsSuperset * with inactive proposal IDs set as 0. * @dev Elements with a proposal ID of 0 should be filtered out by the consumer. * @return An array of active exchange proposals IDs. */ function getActiveProposalIds() external view returns (uint256[] memory) { // Solidity doesn't play well with dynamically sized memory arrays. // Instead, this array is created with the same length as activeProposalIdsSuperset, // and will replace elements that are inactive proposal IDs with the value 0. uint256[] memory activeProposalIds = new uint256[](activeProposalIdsSuperset.length); for (uint256 i = 0; i < activeProposalIdsSuperset.length; i = i.add(1)) { uint256 proposalId = activeProposalIdsSuperset[i]; if ( exchangeProposals[proposalId].state == ExchangeProposalState.Proposed || exchangeProposals[proposalId].state == ExchangeProposalState.Approved ) { activeProposalIds[i] = proposalId; } } return activeProposalIds; } /** * @notice Gets the oracle CELO price quoted in the stable token. * @dev Reverts if there is not a rate for the provided stable token. * @param stableToken The stable token to get the oracle price for. * @return The oracle CELO price quoted in the stable token. */ function getOracleExchangeRate(address stableToken) private view returns (FixidityLib.Fraction memory) { uint256 rateNumerator; uint256 rateDenominator; (rateNumerator, rateDenominator) = getSortedOracles().medianRate(stableToken); // When rateDenominator is 0, it means there are no rates known to SortedOracles. require(rateDenominator > 0, "No oracle rates present for token"); return FixidityLib.wrap(rateNumerator).divide(FixidityLib.wrap(rateDenominator)); } /** * @notice Gets the minimum and maximum amount of a stable token that can be * involved in a single exchange. * @dev Reverts if there is no explicit exchange limit for the stable token. * @param stableTokenRegistryId The string registry ID for the stable token. * @return (minimum exchange amount, maximum exchange amount). */ function getStableTokenExchangeLimits(string memory stableTokenRegistryId) public view returns (uint256, uint256) { ExchangeLimits memory exchangeLimits = stableTokenExchangeLimits[stableTokenRegistryId]; // Require the configurable stableToken max exchange amount to be > 0. // This covers the case where a stableToken has never been explicitly permitted. require( exchangeLimits.maxExchangeAmount > 0, "Max stable token exchange amount must be defined" ); return (exchangeLimits.minExchangeAmount, exchangeLimits.maxExchangeAmount); } /** * @notice Sets the approver. * @dev Sender must be owner. New approver is allowed to be address(0). * @param newApprover The new value for the approver. */ function setApprover(address newApprover) public onlyOwner { approver = newApprover; emit ApproverSet(newApprover); } /** * @notice Sets the maximum allowed change in the CELO/stable token price when * an exchange proposal is being approved relative to the price when the proposal * was created. * @dev Sender must be owner. * @param newMaxApprovalExchangeRateChange The new value for maxApprovalExchangeRateChange * to be wrapped. */ function setMaxApprovalExchangeRateChange(uint256 newMaxApprovalExchangeRateChange) public onlyOwner { maxApprovalExchangeRateChange = FixidityLib.wrap(newMaxApprovalExchangeRateChange); emit MaxApprovalExchangeRateChangeSet(newMaxApprovalExchangeRateChange); } /** * @notice Sets the spread. * @dev Sender must be owner. * @param newSpread The new value for the spread to be wrapped. Must be <= fixed 1. */ function setSpread(uint256 newSpread) public onlyOwner { require(newSpread <= FixidityLib.fixed1().unwrap(), "Spread must be smaller than 1"); spread = FixidityLib.wrap(newSpread); emit SpreadSet(newSpread); } /** * @notice Sets the minimum and maximum amount of the stable token an exchange can involve. * @dev Sender must be owner. Setting the maxExchangeAmount to 0 effectively disables new * exchange proposals for the token. * @param stableTokenRegistryId The registry ID string for the stable token to set limits for. * @param minExchangeAmount The new minimum exchange amount for the stable token. * @param maxExchangeAmount The new maximum exchange amount for the stable token. */ function setStableTokenExchangeLimits( string calldata stableTokenRegistryId, uint256 minExchangeAmount, uint256 maxExchangeAmount ) external onlyOwner { require( minExchangeAmount <= maxExchangeAmount, "Min exchange amount must not be greater than max" ); stableTokenExchangeLimits[stableTokenRegistryId] = ExchangeLimits({ minExchangeAmount: minExchangeAmount, maxExchangeAmount: maxExchangeAmount }); emit StableTokenExchangeLimitsSet(stableTokenRegistryId, minExchangeAmount, maxExchangeAmount); } /** * @notice Sets the veto period in seconds. * @dev Sender must be owner. * @param newVetoPeriodSeconds The new value for the veto period in seconds. */ function setVetoPeriodSeconds(uint256 newVetoPeriodSeconds) public onlyOwner { // Hardcode a max of 4 weeks. // A minimum is not enforced for flexibility. A case of interest is if // Governance were to be set as the `approver`, it would be desirable to // set the veto period to 0 seconds. require(newVetoPeriodSeconds <= 4 weeks, "Veto period cannot exceed 4 weeks"); vetoPeriodSeconds = newVetoPeriodSeconds; emit VetoPeriodSecondsSet(newVetoPeriodSeconds); } }
Sets the maximum allowed change in the CELO/stable token price when an exchange proposal is being approved relative to the price when the proposal was created. Sender must be owner. newMaxApprovalExchangeRateChange The new value for maxApprovalExchangeRateChange to be wrapped./
function setMaxApprovalExchangeRateChange(uint256 newMaxApprovalExchangeRateChange) public onlyOwner { maxApprovalExchangeRateChange = FixidityLib.wrap(newMaxApprovalExchangeRateChange); emit MaxApprovalExchangeRateChangeSet(newMaxApprovalExchangeRateChange); }
2,543,982
// SPDX-License-Identifier: Bprotocol Foundation (Bancor) LICENSE // File: solidity/contracts/token/interfaces/IERC20Token.sol pragma solidity 0.6.12; /* ERC20 Standard Token interface */ interface IERC20Token { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); } // File: solidity/contracts/utility/Utils.sol pragma solidity 0.6.12; /** * @dev Utilities & Common Modifiers */ contract Utils { // verifies that a value is greater than zero modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; } // error message binary size optimization function _greaterThanZero(uint256 _value) internal pure { require(_value > 0, "ERR_ZERO_VALUE"); } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { _validAddress(_address); _; } // error message binary size optimization function _validAddress(address _address) internal pure { require(_address != address(0), "ERR_INVALID_ADDRESS"); } // verifies that the address is different than this contract address modifier notThis(address _address) { _notThis(_address); _; } // error message binary size optimization function _notThis(address _address) internal view { require(_address != address(this), "ERR_ADDRESS_IS_SELF"); } } // File: solidity/contracts/utility/SafeMath.sol pragma solidity 0.6.12; /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x, "ERR_OVERFLOW"); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y, "ERR_UNDERFLOW"); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y, "ERR_OVERFLOW"); return z; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. * * @param _x dividend * @param _y divisor * * @return quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0, "ERR_DIVIDE_BY_ZERO"); uint256 c = _x / _y; return c; } } // File: solidity/contracts/token/ERC20Token.sol pragma solidity 0.6.12; /** * @dev ERC20 Standard Token implementation */ contract ERC20Token is IERC20Token, Utils { using SafeMath for uint256; string public override name; string public override symbol; uint8 public override decimals; uint256 public override totalSupply; mapping (address => uint256) public override balanceOf; mapping (address => mapping (address => uint256)) public override allowance; /** * @dev triggered when tokens are transferred between wallets * * @param _from source address * @param _to target address * @param _value transfer amount */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf * * @param _owner wallet that approves the allowance * @param _spender wallet that receives the allowance * @param _value allowance amount */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev initializes a new ERC20Token instance * * @param _name token name * @param _symbol token symbol * @param _decimals decimal points, for display purposes * @param _totalSupply total supply of token units */ constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply) public { // validate input require(bytes(_name).length > 0, "ERR_INVALID_NAME"); require(bytes(_symbol).length > 0, "ERR_INVALID_SYMBOL"); name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balanceOf[msg.sender] = _totalSupply; } /** * @dev transfers tokens to a given address * throws on any error rather then return a false flag to minimize user errors * * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public virtual override validAddress(_to) returns (bool) { balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev transfers tokens to a given address on behalf of another address * throws on any error rather then return a false flag to minimize user errors * * @param _from source address * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public virtual override validAddress(_from) validAddress(_to) returns (bool) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev allows another account/contract to transfers tokens on behalf of the caller * throws on any error rather then return a false flag to minimize user errors * * @param _spender approved address * @param _value allowance amount * * @return true if the approval was successful, false if it wasn't */ function approve(address _spender, uint256 _value) public virtual override validAddress(_spender) returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } } // File: solidity/contracts/utility/interfaces/IOwned.sol pragma solidity 0.6.12; /* Owned contract interface */ interface IOwned { // this function isn't since the compiler emits automatically generated getter functions as external function owner() external view returns (address); function transferOwnership(address _newOwner) external; function acceptOwnership() external; } // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol pragma solidity 0.6.12; /* Converter Anchor interface */ interface IConverterAnchor is IOwned { } // File: solidity/contracts/token/interfaces/IDSToken.sol pragma solidity 0.6.12; /* DSToken interface */ interface IDSToken is IConverterAnchor, IERC20Token { function issue(address _to, uint256 _amount) external; function destroy(address _from, uint256 _amount) external; } // File: solidity/contracts/utility/Owned.sol pragma solidity 0.6.12; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public override owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() internal view { require(msg.sender == owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public override ownerOnly { require(_newOwner != owner, "ERR_SAME_OWNER"); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() override public { require(msg.sender == newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: solidity/contracts/token/DSToken.sol pragma solidity 0.6.12; /** * @dev DSToken represents a token with dynamic supply. * The owner of the token can mint/burn tokens to/from any account. * */ contract DSToken is IDSToken, ERC20Token, Owned { using SafeMath for uint256; /** * @dev triggered when the total supply is increased * * @param _amount amount that gets added to the supply */ event Issuance(uint256 _amount); /** * @dev triggered when the total supply is decreased * * @param _amount amount that gets removed from the supply */ event Destruction(uint256 _amount); /** * @dev initializes a new DSToken instance * * @param _name token name * @param _symbol token short symbol, minimum 1 character * @param _decimals for display purposes only */ constructor(string memory _name, string memory _symbol, uint8 _decimals) public ERC20Token(_name, _symbol, _decimals, 0) { } /** * @dev increases the token supply and sends the new tokens to the given account * can only be called by the contract owner * * @param _to account to receive the new amount * @param _amount amount to increase the supply by */ function issue(address _to, uint256 _amount) public override ownerOnly validAddress(_to) notThis(_to) { totalSupply = totalSupply.add(_amount); balanceOf[_to] = balanceOf[_to].add(_amount); emit Issuance(_amount); emit Transfer(address(0), _to, _amount); } /** * @dev removes tokens from the given account and decreases the token supply * can only be called by the contract owner * * @param _from account to remove the amount from * @param _amount amount to decrease the supply by */ function destroy(address _from, uint256 _amount) public override ownerOnly { balanceOf[_from] = balanceOf[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); emit Transfer(_from, address(0), _amount); emit Destruction(_amount); } // ERC20 standard method overrides with some extra functionality /** * @dev send coins * throws on any error rather then return a false flag to minimize user errors * in addition to the standard checks, the function throws if transfers are disabled * * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public override(IERC20Token, ERC20Token) returns (bool) { return super.transfer(_to, _value); } /** * @dev an account/contract attempts to get the coins * throws on any error rather then return a false flag to minimize user errors * in addition to the standard checks, the function throws if transfers are disabled * * @param _from source address * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public override(IERC20Token, ERC20Token) returns (bool) { return super.transferFrom(_from, _to, _value); } }
an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors in addition to the standard checks, the function throws if transfers are disabled _from source address _to target address _value transfer amount return true if the transfer was successful, false if it wasn't/
function transferFrom(address _from, address _to, uint256 _value) public override(IERC20Token, ERC20Token) returns (bool) { return super.transferFrom(_from, _to, _value); }
1,352,351
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // Creators: locationtba.eth, 2pmflow.eth pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @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 internal 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 {} } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; // required to accept structs as function parameters import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "./ERC721A.sol"; ////////////////////////////////////////////////////// // // // We are Blackchain. // // [email protected] // // // ////////////////////////////////////////////////////// /** @title Renaissance Art NFT @author Jeffrey Lin, Justa Liang */ contract RenArt is ERC721A, Ownable, EIP712, PaymentSplitter { using Address for address; // Stage info (packed) struct StageInfo { bool publicStage; uint8 stageId; uint16 maxSupply; uint32 startTime; uint32 endTime; uint160 mintPrice; } StageInfo public stageInfo; // Maximum limit of tokens that can ever exist uint16 constant MAX_SUPPLY = 9500; // Maximum reserve uint16 constant MAX_RESERVE = 500; // Reserved uint256 private _reservedCount; // Maximum limit of mint amount per time in public stage uint8 constant MAX_MINT_PER_TIME = 2; // The base link that leads to the image / video of the token string private _baseTokenURI; struct MinterInfo { uint8 nonce; uint8 stageId; uint240 remain; } // Stage ID check mapping(address => MinterInfo) public whitelistInfo; // voucher for user to redeem struct NFTVoucher { address redeemer; // specify user to redeem this voucher uint8 stageId; // ID to check if voucher has been redeemed uint8 amount; // max amount to mint in stage uint8 nonce; // nonce to make different voucher uint72 price; // mint price } /// @dev Setup ERC721A, EIP712 and first stage info constructor( StageInfo memory _initStageInfo, string memory _initBaseURI, address[] memory payees, uint256[] memory shares ) ERC721A("RenArt", "RENA", 5) EIP712("RenArt-Voucher", "1") PaymentSplitter(payees, shares) { _baseTokenURI = _initBaseURI; stageInfo = _initStageInfo; _reservedCount = 0; } /// @notice Whitelist mint using the voucher function whitelistMint( NFTVoucher calldata voucher, bytes calldata signature, uint8 amount ) external payable { MinterInfo storage minterInfo = whitelistInfo[_msgSender()]; // make sure voucher is valid _verify(voucher, signature); // if haven't redeemed then redeem first if (voucher.nonce > minterInfo.nonce) { // update minter info minterInfo.stageId = voucher.stageId; minterInfo.remain = voucher.amount; minterInfo.nonce = voucher.nonce; } // check stage require(voucher.stageId == stageInfo.stageId, "Wrong stage"); // check time require(block.timestamp >= stageInfo.startTime, "Sale not started"); require(block.timestamp <= stageInfo.endTime, "Sale already ended"); // check if enough remain require(amount <= minterInfo.remain, "Not enough remain"); // check if exceed require( totalSupply() + amount <= stageInfo.maxSupply, "Exceed stage max supply" ); // check fund require(msg.value >= voucher.price * amount, "Not enough fund"); super._safeMint(_msgSender(), amount); minterInfo.remain -= amount; } /// @notice Public mint function publicMint(uint8 amount) external payable { // check public mint stage require(stageInfo.publicStage, "Public mint not started"); // check time require(block.timestamp >= stageInfo.startTime, "Sale not started"); require(block.timestamp <= stageInfo.endTime, "Sale already ended"); // check if exceed max per time require(amount <= MAX_MINT_PER_TIME, "Exceed max mint amount"); // check if exceed total supply require(totalSupply() + amount <= MAX_SUPPLY, "Exceed total supply"); // check fund require(msg.value >= stageInfo.mintPrice * amount, "Not enough fund"); // batch mint super._safeMint(_msgSender(), amount); } /// @dev Verify voucher function _verify(NFTVoucher calldata voucher, bytes calldata signature) private view { bytes32 digest = _hashTypedDataV4( keccak256( abi.encode( keccak256( "NFTVoucher(address redeemer,uint8 stageId,uint8 amount,uint8 nonce,uint72 price)" ), _msgSender(), voucher.stageId, voucher.amount, voucher.nonce, voucher.price ) ) ); require( owner() == ECDSA.recover(digest, signature), "invalid or unauthorized" ); } /// @dev Reserve NFT function reserve(address to, uint256 amount) external onlyOwner { require(_reservedCount + amount <= MAX_RESERVE, "Exceed reserve max"); super._safeMint(to, amount); _reservedCount += amount; } /// @dev Go to next stage function nextStage(StageInfo memory _stageInfo) external onlyOwner { require( _stageInfo.stageId >= stageInfo.stageId, "Cannot set to previous stage" ); require(_stageInfo.maxSupply <= MAX_SUPPLY, "Set exceed max supply"); require(_stageInfo.stageId <= 3, "Can only have three stage"); stageInfo = _stageInfo; } /// @dev Set new baseURI function setBaseURI(string memory baseURI) external onlyOwner { _baseTokenURI = baseURI; } /// @dev override _baseURI() function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } }
Whitelist mint using the voucher make sure voucher is valid if haven't redeemed then redeem first update minter info
function whitelistMint( NFTVoucher calldata voucher, bytes calldata signature, uint8 amount ) external payable { MinterInfo storage minterInfo = whitelistInfo[_msgSender()]; _verify(voucher, signature); if (voucher.nonce > minterInfo.nonce) { minterInfo.stageId = voucher.stageId; minterInfo.remain = voucher.amount; minterInfo.nonce = voucher.nonce; } require(block.timestamp <= stageInfo.endTime, "Sale already ended"); totalSupply() + amount <= stageInfo.maxSupply, "Exceed stage max supply" ); super._safeMint(_msgSender(), amount); minterInfo.remain -= amount; }
13,990,400
./partial_match/1/0xbc6a1af02c09fc1514B95eC98756ccAa95e8Af2e/sources/GEtherBridge.sol
Performs a deposit of the reserve asset to the given gToken. _token The gToken to deposit to. _amount The amount to be deposited. return _success A boolean indicating whether or not the action succeeded./
function _depositUnderlying(Self storage _self, address _token, uint256 _amount) internal returns (bool _success) { _amount = G.min(_amount, G.getBalance(_self.reserveToken)); if (_amount == 0) return true; G.approveFunds(_self.reserveToken, _token, _amount); try GCToken(_token).depositUnderlying(_amount) { return true; G.approveFunds(_self.reserveToken, _token, 0); return false; } }
2,650,985
./partial_match/1/0xa77e44A139cb3C4A58d73708b2cB25b9D101AEF5/sources/DHedge.sol
Unsafe internal method that assumes we are removing an element that exists overwrite the asset to be removed with the last supported asset delete the last supported asset and resize the array
function _removeFromSupportedAssets(bytes32 key) internal { uint256 length = supportedAssets.length; bytes32 lastAsset = supportedAssets[length.sub(1)]; supportedAssets[index] = lastAsset; supportedAssets.pop(); emit AssetRemoved(address(this), manager(), key); }
2,784,428
./full_match/1/0x453F310662345de095E98053c767d916D6a30e82/sources/HoboTownDaoContract.sol
Mints a token to an address with a tokenURI. fee may or may not be required _to address of the future owner of the token _amount number of tokens to mint/
function mintToMultiple(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(mintingOpen == true, "Minting is not open right now!"); require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 999"); require(msg.value == getPrice(_amount), "Value below required mint fee for amount"); _safeMint(_to, _amount, false); }
17,053,787
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "../governance/Managed.sol"; import "../upgrades/GraphUpgradeable.sol"; import "./DisputeManagerStorage.sol"; import "./IDisputeManager.sol"; /* * @title DisputeManager * @dev Provides a way to align the incentives of participants by having slashing as deterrent * for incorrect behaviour. * * There are two types of disputes that can be created: Query disputes and Indexing disputes. * * Query Disputes: * Graph nodes receive queries and return responses with signed receipts called attestations. * An attestation can be disputed if the consumer thinks the query response was invalid. * Indexers use the derived private key for an allocation to sign attestations. * * Indexing Disputes: * Indexers present a Proof of Indexing (POI) when they close allocations to prove * they were indexing a subgraph. The Staking contract emits that proof with the format * keccak256(indexer.address, POI). * Any challenger can dispute the validity of a POI by submitting a dispute to this contract * along with a deposit. * * Arbitration: * Disputes can only be accepted, rejected or drawn by the arbitrator role that can be delegated * to a EOA or DAO. */ contract DisputeManager is DisputeManagerV1Storage, GraphUpgradeable, IDisputeManager { using SafeMath for uint256; // -- EIP-712 -- bytes32 private constant DOMAIN_TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 private constant DOMAIN_NAME_HASH = keccak256("Graph Protocol"); bytes32 private constant DOMAIN_VERSION_HASH = keccak256("0"); bytes32 private constant DOMAIN_SALT = 0xa070ffb1cd7409649bf77822cce74495468e06dbfaef09556838bf188679b9c2; bytes32 private constant RECEIPT_TYPE_HASH = keccak256( "Receipt(bytes32 requestCID,bytes32 responseCID,bytes32 subgraphDeploymentID)" ); // -- Constants -- uint256 private constant ATTESTATION_SIZE_BYTES = 161; uint256 private constant RECEIPT_SIZE_BYTES = 96; uint256 private constant SIG_R_LENGTH = 32; uint256 private constant SIG_S_LENGTH = 32; uint256 private constant SIG_R_OFFSET = RECEIPT_SIZE_BYTES; uint256 private constant SIG_S_OFFSET = RECEIPT_SIZE_BYTES + SIG_R_LENGTH; uint256 private constant SIG_V_OFFSET = RECEIPT_SIZE_BYTES + SIG_R_LENGTH + SIG_S_LENGTH; uint256 private constant UINT8_BYTE_LENGTH = 1; uint256 private constant BYTES32_BYTE_LENGTH = 32; uint256 private constant MAX_PPM = 1000000; // 100% in parts per million // -- Events -- /** * @dev Emitted when a query dispute is created for `subgraphDeploymentID` and `indexer` * by `fisherman`. * The event emits the amount of `tokens` deposited by the fisherman and `attestation` submitted. */ event QueryDisputeCreated( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens, bytes32 subgraphDeploymentID, bytes attestation ); /** * @dev Emitted when an indexing dispute is created for `allocationID` and `indexer` * by `fisherman`. * The event emits the amount of `tokens` deposited by the fisherman. */ event IndexingDisputeCreated( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens, address allocationID ); /** * @dev Emitted when arbitrator accepts a `disputeID` to `indexer` created by `fisherman`. * The event emits the amount `tokens` transferred to the fisherman, the deposit plus reward. */ event DisputeAccepted( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when arbitrator rejects a `disputeID` for `indexer` created by `fisherman`. * The event emits the amount `tokens` burned from the fisherman deposit. */ event DisputeRejected( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when arbitrator draw a `disputeID` for `indexer` created by `fisherman`. * The event emits the amount `tokens` used as deposit and returned to the fisherman. */ event DisputeDrawn( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when two disputes are in conflict to link them. * This event will be emitted after each DisputeCreated event is emitted * for each of the individual disputes. */ event DisputeLinked(bytes32 indexed disputeID1, bytes32 indexed disputeID2); /** * @dev Check if the caller is the arbitrator. */ modifier onlyArbitrator { require(msg.sender == arbitrator, "Caller is not the Arbitrator"); _; } /** * @dev Initialize this contract. * @param _arbitrator Arbitrator role * @param _minimumDeposit Minimum deposit required to create a Dispute * @param _fishermanRewardPercentage Percent of slashed funds for fisherman (ppm) * @param _slashingPercentage Percentage of indexer stake slashed (ppm) */ function initialize( address _controller, address _arbitrator, uint256 _minimumDeposit, uint32 _fishermanRewardPercentage, uint32 _slashingPercentage ) external onlyImpl { Managed._initialize(_controller); // Settings _setArbitrator(_arbitrator); _setMinimumDeposit(_minimumDeposit); _setFishermanRewardPercentage(_fishermanRewardPercentage); _setSlashingPercentage(_slashingPercentage); // EIP-712 domain separator DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME_HASH, DOMAIN_VERSION_HASH, _getChainID(), address(this), DOMAIN_SALT ) ); } /** * @dev Set the arbitrator address. * @notice Update the arbitrator to `_arbitrator` * @param _arbitrator The address of the arbitration contract or party */ function setArbitrator(address _arbitrator) external override onlyGovernor { _setArbitrator(_arbitrator); } /** * @dev Internal: Set the arbitrator address. * @notice Update the arbitrator to `_arbitrator` * @param _arbitrator The address of the arbitration contract or party */ function _setArbitrator(address _arbitrator) private { require(_arbitrator != address(0), "Arbitrator must be set"); arbitrator = _arbitrator; emit ParameterUpdated("arbitrator"); } /** * @dev Set the minimum deposit required to create a dispute. * @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens * @param _minimumDeposit The minimum deposit in Graph Tokens */ function setMinimumDeposit(uint256 _minimumDeposit) external override onlyGovernor { _setMinimumDeposit(_minimumDeposit); } /** * @dev Internal: Set the minimum deposit required to create a dispute. * @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens * @param _minimumDeposit The minimum deposit in Graph Tokens */ function _setMinimumDeposit(uint256 _minimumDeposit) private { require(_minimumDeposit > 0, "Minimum deposit must be set"); minimumDeposit = _minimumDeposit; emit ParameterUpdated("minimumDeposit"); } /** * @dev Set the percent reward that the fisherman gets when slashing occurs. * @notice Update the reward percentage to `_percentage` * @param _percentage Reward as a percentage of indexer stake */ function setFishermanRewardPercentage(uint32 _percentage) external override onlyGovernor { _setFishermanRewardPercentage(_percentage); } /** * @dev Internal: Set the percent reward that the fisherman gets when slashing occurs. * @notice Update the reward percentage to `_percentage` * @param _percentage Reward as a percentage of indexer stake */ function _setFishermanRewardPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Reward percentage must be below or equal to MAX_PPM"); fishermanRewardPercentage = _percentage; emit ParameterUpdated("fishermanRewardPercentage"); } /** * @dev Set the percentage used for slashing indexers. * @param _percentage Percentage used for slashing */ function setSlashingPercentage(uint32 _percentage) external override onlyGovernor { _setSlashingPercentage(_percentage); } /** * @dev Internal: Set the percentage used for slashing indexers. * @param _percentage Percentage used for slashing */ function _setSlashingPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Slashing percentage must be below or equal to MAX_PPM"); slashingPercentage = _percentage; emit ParameterUpdated("slashingPercentage"); } /** * @dev Return whether a dispute exists or not. * @notice Return if dispute with ID `_disputeID` exists * @param _disputeID True if dispute already exists */ function isDisputeCreated(bytes32 _disputeID) public override view returns (bool) { return disputes[_disputeID].fisherman != address(0); } /** * @dev Get the message hash that an indexer used to sign the receipt. * Encodes a receipt using a domain separator, as described on * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification. * @notice Return the message hash used to sign the receipt * @param _receipt Receipt returned by indexer and submitted by fisherman * @return Message hash used to sign the receipt */ function encodeHashReceipt(Receipt memory _receipt) public override view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", // EIP-191 encoding pad, EIP-712 version 1 DOMAIN_SEPARATOR, keccak256( abi.encode( RECEIPT_TYPE_HASH, _receipt.requestCID, _receipt.responseCID, _receipt.subgraphDeploymentID ) // EIP 712-encoded message hash ) ) ); } /** * @dev Returns if two attestations are conflicting. * Everything must match except for the responseID. * @param _attestation1 Attestation * @param _attestation2 Attestation * @return True if the two attestations are conflicting */ function areConflictingAttestations( Attestation memory _attestation1, Attestation memory _attestation2 ) public override pure returns (bool) { return (_attestation1.requestCID == _attestation2.requestCID && _attestation1.subgraphDeploymentID == _attestation2.subgraphDeploymentID && _attestation1.responseCID != _attestation2.responseCID); } /** * @dev Returns the indexer that signed an attestation. * @param _attestation Attestation * @return Indexer address */ function getAttestationIndexer(Attestation memory _attestation) public override view returns (address) { // Get attestation signer, allocationID address allocationID = _recoverAttestationSigner(_attestation); IStaking.Allocation memory alloc = staking().getAllocation(allocationID); require(alloc.indexer != address(0), "Indexer cannot be found for the attestation"); require( alloc.subgraphDeploymentID == _attestation.subgraphDeploymentID, "Allocation and attestation subgraphDeploymentID must match" ); return alloc.indexer; } /** * @dev Get the fisherman reward for a given indexer stake. * @notice Return the fisherman reward based on the `_indexer` stake * @param _indexer Indexer to be slashed * @return Reward calculated as percentage of the indexer slashed funds */ function getTokensToReward(address _indexer) public override view returns (uint256) { uint256 tokens = getTokensToSlash(_indexer); if (tokens == 0) { return 0; } return uint256(fishermanRewardPercentage).mul(tokens).div(MAX_PPM); } /** * @dev Get the amount of tokens to slash for an indexer based on the current stake. * @param _indexer Address of the indexer * @return Amount of tokens to slash */ function getTokensToSlash(address _indexer) public override view returns (uint256) { uint256 tokens = staking().getIndexerStakedTokens(_indexer); // slashable tokens if (tokens == 0) { return 0; } return uint256(slashingPercentage).mul(tokens).div(MAX_PPM); } /** * @dev Create a query dispute for the arbitrator to resolve. * This function is called by a fisherman that will need to `_deposit` at * least `minimumDeposit` GRT tokens. * @param _attestationData Attestation bytes submitted by the fisherman * @param _deposit Amount of tokens staked as deposit */ function createQueryDispute(bytes calldata _attestationData, uint256 _deposit) external override returns (bytes32) { // Get funds from submitter _pullSubmitterDeposit(_deposit); // Create a dispute return _createQueryDisputeWithAttestation( msg.sender, _deposit, _parseAttestation(_attestationData), _attestationData ); } /** * @dev Create query disputes for two conflicting attestations. * A conflicting attestation is a proof presented by two different indexers * where for the same request on a subgraph the response is different. * For this type of dispute the submitter is not required to present a deposit * as one of the attestation is considered to be right. * Two linked disputes will be created and if the arbitrator resolve one, the other * one will be automatically resolved. * @param _attestationData1 First attestation data submitted * @param _attestationData2 Second attestation data submitted * @return DisputeID1, DisputeID2 */ function createQueryDisputeConflict( bytes calldata _attestationData1, bytes calldata _attestationData2 ) external override returns (bytes32, bytes32) { address fisherman = msg.sender; // Parse each attestation Attestation memory attestation1 = _parseAttestation(_attestationData1); Attestation memory attestation2 = _parseAttestation(_attestationData2); // Test that attestations are conflicting require( areConflictingAttestations(attestation1, attestation2), "Attestations must be in conflict" ); // Create the disputes // The deposit is zero for conflicting attestations bytes32 dID1 = _createQueryDisputeWithAttestation( fisherman, 0, attestation1, _attestationData1 ); bytes32 dID2 = _createQueryDisputeWithAttestation( fisherman, 0, attestation2, _attestationData2 ); // Store the linked disputes to be resolved disputes[dID1].relatedDisputeID = dID2; disputes[dID2].relatedDisputeID = dID1; // Emit event that links the two created disputes emit DisputeLinked(dID1, dID2); return (dID1, dID2); } /** * @dev Create a query dispute passing the parsed attestation. * To be used in createQueryDispute() and createQueryDisputeConflict() * to avoid calling parseAttestation() multiple times * `_attestationData` is only passed to be emitted * @param _fisherman Creator of dispute * @param _deposit Amount of tokens staked as deposit * @param _attestation Attestation struct parsed from bytes * @param _attestationData Attestation bytes submitted by the fisherman * @return DisputeID */ function _createQueryDisputeWithAttestation( address _fisherman, uint256 _deposit, Attestation memory _attestation, bytes memory _attestationData ) private returns (bytes32) { // Get the indexer that signed the attestation address indexer = getAttestationIndexer(_attestation); // The indexer is disputable require(staking().hasStake(indexer), "Dispute indexer has no stake"); // Create a disputeID bytes32 disputeID = keccak256( abi.encodePacked( _attestation.requestCID, _attestation.responseCID, _attestation.subgraphDeploymentID, indexer, _fisherman ) ); // Only one dispute for a (indexer, subgraphDeploymentID) at a time require(!isDisputeCreated(disputeID), "Dispute already created"); // Store dispute disputes[disputeID] = Dispute( indexer, _fisherman, _deposit, 0 // no related dispute ); emit QueryDisputeCreated( disputeID, indexer, _fisherman, _deposit, _attestation.subgraphDeploymentID, _attestationData ); return disputeID; } /** * @dev Create an indexing dispute for the arbitrator to resolve. * The disputes are created in reference to an allocationID * This function is called by a challenger that will need to `_deposit` at * least `minimumDeposit` GRT tokens. * @param _allocationID The allocation to dispute * @param _deposit Amount of tokens staked as deposit */ function createIndexingDispute(address _allocationID, uint256 _deposit) external override returns (bytes32) { // Get funds from submitter _pullSubmitterDeposit(_deposit); // Create a dispute return _createIndexingDisputeWithAllocation(msg.sender, _deposit, _allocationID); } /** * @dev Create indexing dispute internal function. * @param _fisherman The challenger creating the dispute * @param _deposit Amount of tokens staked as deposit * @param _allocationID Allocation disputed */ function _createIndexingDisputeWithAllocation( address _fisherman, uint256 _deposit, address _allocationID ) private returns (bytes32) { // Create a disputeID bytes32 disputeID = keccak256(abi.encodePacked(_allocationID)); // Only one dispute for an allocationID at a time require(!isDisputeCreated(disputeID), "Dispute already created"); // Allocation must exist IStaking.Allocation memory alloc = staking().getAllocation(_allocationID); require(alloc.indexer != address(0), "Dispute allocation must exist"); // The indexer must be disputable require(staking().hasStake(alloc.indexer), "Dispute indexer has no stake"); // Store dispute disputes[disputeID] = Dispute(alloc.indexer, _fisherman, _deposit, 0); emit IndexingDisputeCreated(disputeID, alloc.indexer, _fisherman, _deposit, _allocationID); return disputeID; } /** * @dev The arbitrator accepts a dispute as being valid. * @notice Accept a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be accepted */ function acceptDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Slash uint256 tokensToReward = _slashIndexer(dispute.indexer, dispute.fisherman); // Give the fisherman their deposit back if (dispute.deposit > 0) { require( graphToken().transfer(dispute.fisherman, dispute.deposit), "Error sending dispute deposit" ); } // Resolve the conflicting dispute if any _resolveDisputeInConflict(dispute); emit DisputeAccepted( _disputeID, dispute.indexer, dispute.fisherman, dispute.deposit.add(tokensToReward) ); } /** * @dev The arbitrator rejects a dispute as being invalid. * @notice Reject a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be rejected */ function rejectDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Handle conflicting dispute if any require( !_isDisputeInConflict(dispute), "Dispute for conflicting attestation, must accept the related ID to reject" ); // Burn the fisherman's deposit if (dispute.deposit > 0) { graphToken().burn(dispute.deposit); } emit DisputeRejected(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); } /** * @dev The arbitrator draws dispute. * @notice Ignore a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be disregarded */ function drawDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Return deposit to the fisherman if (dispute.deposit > 0) { require( graphToken().transfer(dispute.fisherman, dispute.deposit), "Error sending dispute deposit" ); } // Resolve the conflicting dispute if any _resolveDisputeInConflict(dispute); emit DisputeDrawn(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); } /** * @dev Resolve a dispute by removing it from storage and returning a memory copy. * @param _disputeID ID of the dispute to resolve * @return Dispute */ function _resolveDispute(bytes32 _disputeID) private returns (Dispute memory) { require(isDisputeCreated(_disputeID), "Dispute does not exist"); Dispute memory dispute = disputes[_disputeID]; // Resolve dispute delete disputes[_disputeID]; // Re-entrancy return dispute; } /** * @dev Returns whether the dispute is for a conflicting attestation or not. * @param _dispute Dispute * @return True conflicting attestation dispute */ function _isDisputeInConflict(Dispute memory _dispute) private pure returns (bool) { return _dispute.relatedDisputeID != 0; } /** * @dev Resolve the conflicting dispute if there is any for the one passed to this function. * @param _dispute Dispute * @return True if resolved */ function _resolveDisputeInConflict(Dispute memory _dispute) private returns (bool) { if (_isDisputeInConflict(_dispute)) { bytes32 relatedDisputeID = _dispute.relatedDisputeID; delete disputes[relatedDisputeID]; return true; } return false; } /** * @dev Pull deposit from submitter account. * @param _deposit Amount of tokens to deposit */ function _pullSubmitterDeposit(uint256 _deposit) private { // Ensure that fisherman has staked at least the minimum amount require(_deposit >= minimumDeposit, "Dispute deposit is under minimum required"); // Transfer tokens to deposit from fisherman to this contract require( graphToken().transferFrom(msg.sender, address(this), _deposit), "Cannot transfer tokens to deposit" ); } /** * @dev Make the staking contract slash the indexer and reward the challenger. * Give the challenger a reward equal to the fishermanRewardPercentage of slashed amount * @param _indexer Address of the indexer * @param _challenger Address of the challenger * @return Dispute reward tokens */ function _slashIndexer(address _indexer, address _challenger) private returns (uint256) { // Have staking contract slash the indexer and reward the fisherman // Give the fisherman a reward equal to the fishermanRewardPercentage of slashed amount uint256 tokensToSlash = getTokensToSlash(_indexer); uint256 tokensToReward = getTokensToReward(_indexer); require(tokensToSlash > 0, "Dispute has zero tokens to slash"); staking().slash(_indexer, tokensToSlash, tokensToReward, _challenger); return tokensToReward; } /** * @dev Recover the signer address of the `_attestation`. * @param _attestation The attestation struct * @return Signer address */ function _recoverAttestationSigner(Attestation memory _attestation) private view returns (address) { // Obtain the hash of the fully-encoded message, per EIP-712 encoding Receipt memory receipt = Receipt( _attestation.requestCID, _attestation.responseCID, _attestation.subgraphDeploymentID ); bytes32 messageHash = encodeHashReceipt(receipt); // Obtain the signer of the fully-encoded EIP-712 message hash // NOTE: The signer of the attestation is the indexer that served the request return ECDSA.recover( messageHash, abi.encodePacked(_attestation.r, _attestation.s, _attestation.v) ); } /** * @dev Get the running network chain ID * @return The chain ID */ function _getChainID() private pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Parse the bytes attestation into a struct from `_data`. * @return Attestation struct */ function _parseAttestation(bytes memory _data) private pure returns (Attestation memory) { // Check attestation data length require(_data.length == ATTESTATION_SIZE_BYTES, "Attestation must be 161 bytes long"); // Decode receipt (bytes32 requestCID, bytes32 responseCID, bytes32 subgraphDeploymentID) = abi.decode( _data, (bytes32, bytes32, bytes32) ); // Decode signature // Signature is expected to be in the order defined in the Attestation struct bytes32 r = _toBytes32(_data, SIG_R_OFFSET); bytes32 s = _toBytes32(_data, SIG_S_OFFSET); uint8 v = _toUint8(_data, SIG_V_OFFSET); return Attestation(requestCID, responseCID, subgraphDeploymentID, r, s, v); } /** * @dev Parse a uint8 from `_bytes` starting at offset `_start`. * @return uint8 value */ function _toUint8(bytes memory _bytes, uint256 _start) private pure returns (uint8) { require(_bytes.length >= (_start + UINT8_BYTE_LENGTH), "Bytes: out of bounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } /** * @dev Parse a bytes32 from `_bytes` starting at offset `_start`. * @return bytes32 value */ function _toBytes32(bytes memory _bytes, uint256 _start) private pure returns (bytes32) { require(_bytes.length >= (_start + BYTES32_BYTE_LENGTH), "Bytes: out of bounds"); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } }
Get the message hash that an indexer used to sign the receipt. Encodes a receipt using a domain separator, as described on Return the message hash used to sign the receipt _receipt Receipt returned by indexer and submitted by fisherman return Message hash used to sign the receipt/
function encodeHashReceipt(Receipt memory _receipt) public override view returns (bytes32) { return keccak256( abi.encodePacked( DOMAIN_SEPARATOR, keccak256( abi.encode( RECEIPT_TYPE_HASH, _receipt.requestCID, _receipt.responseCID, _receipt.subgraphDeploymentID ) ) ); }
908,954
./partial_match/1/0x9fA4C76131EF8eA649fE1a6bdcB015e847E08776/sources/RewardedWbtcPbtcUniV2Pair.sol
Swap _amount / 2 pBTC sent to this contract into WBTC and put them into a pBTC/WBTC Uniswap pool. The amount of UniV2 token will be sent to ModifiedUnipool in order to mature reward. _user address of the user who will have UniV2 tokens in ModifiedUnipool _amount amount of pbtc to use to perform this operation/
function _stakeFor(address _user, uint256 _amount) internal { uint256 pbtcAmountIn = _amount / 2; (uint256 wbtcReserve, uint256 pbtcReserve, ) = uniV2.getReserves(); uint256 wbtcAmountOut = UniswapV2Library.getAmountOut( pbtcAmountIn, pbtcReserve, wbtcReserve ); pbtc.safeTransfer(address(uniV2), pbtcAmountIn); uniV2.swap(wbtcAmountOut, 0, address(this), ""); pbtc.safeTransfer(address(uniV2), pbtcAmountIn); wbtc.safeTransfer(address(uniV2), wbtcAmountOut); uint256 liquidity = uniV2.mint(address(this)); uniV2.approve(address(modifiedUnipool), liquidity); modifiedUnipool.stakeFor(_user, liquidity); emit Staked(_user, _amount); }
4,393,101
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import './interfaces/IBuyBackAndBurn.sol'; import './interfaces/IMultiSignatureOracle.sol'; import './utils/MyPausableUpgradeable.sol'; import './token/MintableERC721.sol'; import 'hardhat/console.sol'; /** * @title CrossChainBridgeERC721V1 * Provides cross chain bridging services for (whitelisted) ERC721 tokens */ contract CrossChainBridgeERC721V1 is MyPausableUpgradeable, IERC721Receiver { // Roles bytes32 public constant MANAGE_COLLECTED_FEES_ROLE = keccak256('MANAGE_COLLECTED_FEES_ROLE'); bytes32 public constant MANAGE_FEES_ROLE = keccak256('MANAGE_FEES_ROLE'); bytes32 public constant MANAGE_ORACLES_ROLE = keccak256('MANAGE_ORACLES_ROLE'); bytes32 public constant MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE = keccak256('MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE'); bytes32 public constant MANAGE_COLLECTION_WHITELIST_ROLE = keccak256('MANAGE_COLLECTION_WHITELIST_ROLE'); event TokenDeposited( address indexed sourceNetworkCollectionAddress, uint256 tokenId, address indexed receiverAddress, uint256 sourceChainId, uint256 targetChainId, uint256 number ); event TokenReleased( address indexed sourceNetworkCollectionAddress, uint256 tokenId, address indexed receiverAddress, uint256 depositChainId, uint256 depositNumber ); event AddedCollectionToWhitelist(address indexed collectionAddress); event RemovedCollectionFromWhitelist(address indexed collectionAddress); event PeggedCollectionMappingAdded( address indexed depositChainCollectionAddress, address indexed releaseChainCollectionAddress ); /// Counts all deposits /// Assigns a unique deposit ID to each deposit which helps to prevent double releases uint256 public depositCount; /// A mapping from deposit IDs to boolean if a deposit has been released or not /// depositChainId => depositNumber => true (released) mapping(uint256 => mapping(uint256 => bool)) public releasedDeposits; /// A mapping for a collection if a NFT for a tokenId deposit has been minted or not /// tokenAddress => tokenId => bool mapping(address => mapping(uint256 => bool)) public mintedDeposits; /// Default bridge fee (fixed amount per transaction) uint256 public defaultBridgeFee; /// Individual bridge fees per supported token (fixed amount per transaction) /// tokenAdressInDepositNetwork => flat fee amount in native token mapping(address => uint256) public bridgeFees; /// Storage of the outside pegged tokens /// tokenAddressInThisNetwork => tokenAddressInTargetNetwork mapping(address => address) public outsidePeggedCollections; /// Mapping to track which collections are whitelisted /// Only the official collections of the projects has to be whitelisted /// Pegged collections by the bridge must not be whitelisted /// tokenAddressInThisNetwork => true/false mapping(address => bool) public officialCollectionWhitelist; /// Contract to receive a part of the bridge fees for token burns IBuyBackAndBurn public buyBackAndBurn; /// MultiSignatureOracle contract IMultiSignatureOracle public multiSignatureOracle; /** * @notice Initializer instead of constructor to have the contract upgradable * @dev can only be called once after deployment of the contract */ function initialize(address _buyBackAndBurn, address _multiSignatureOracle) external initializer { // call parent initializers __MyPausableUpgradeable_init(); // set up admin roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // initialize required state variables buyBackAndBurn = IBuyBackAndBurn(_buyBackAndBurn); multiSignatureOracle = IMultiSignatureOracle(_multiSignatureOracle); defaultBridgeFee = 0; } /** * @notice Adds a collection to the whitelist (effectively allowing bridge transactions for this token) * * @dev can only be called by MANAGE_COLLECTION_WHITELIST_ROLE * @param collectionAddress the address of the token in the network this contract was released on * @dev emits event AddedCollectionToWhitelist after successful whitelisting */ function addCollectionToWhitelist(address collectionAddress) external { require( hasRole(MANAGE_COLLECTION_WHITELIST_ROLE, _msgSender()), 'CrossChainBridgeERC721: must have MANAGE_COLLECTION_WHITELIST_ROLE role to execute this function' ); require(collectionAddress != address(0), 'CrossChainBridgeERC721V1: invalid collectionAddress provided'); officialCollectionWhitelist[collectionAddress] = true; emit AddedCollectionToWhitelist(collectionAddress); } /** * @notice Adds an outside pegged collection (= same collection but in a different network) * * @dev can only be called by MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE * @param depositChainCollectionAddress the address of the collection in the network the deposit is possible (deposit collection) * @param peggedCollectionAddress the address of the pegged collection in the network this bridge contract is released on (release collection) */ function addOutsidePeggedCollection(address depositChainCollectionAddress, address peggedCollectionAddress) external { require( hasRole(MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE, _msgSender()), 'CrossChainBridgeERC721: must have MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE role to execute this function' ); require( depositChainCollectionAddress != address(0) && peggedCollectionAddress != address(0), 'CrossChainBridgeERC721V1: invalid collection address provided' ); outsidePeggedCollections[depositChainCollectionAddress] = peggedCollectionAddress; emit PeggedCollectionMappingAdded(depositChainCollectionAddress, peggedCollectionAddress); } /** * @notice Accepts ERC721 deposits that should be bridged into another network (effectively starting a bridge transaction) * * @dev the collection must be whitelisted by the bridge or the call will be reverted * @param collectionAddress the address of the ERC721 contract the collection was issued with * @param tokenId the (native) ID of the ERC721 token that should be bridged * @param receiverAddress target address the bridged token should be sent to * @param targetChainId chain ID of the target network * @dev emits event TokenDeposited after successful deposit * */ function deposit( address collectionAddress, uint256 tokenId, address receiverAddress, uint256 targetChainId ) external whenNotPaused { // check if token was minted from an original collection or minted by this bridge if (mintedDeposits[collectionAddress][tokenId]) { // no whitelist check necessary since token was minted by this bridge MintableERC721(collectionAddress).burn(tokenId); } else { require(officialCollectionWhitelist[collectionAddress], 'CrossChainBridgeERC721V1: collection not whitelisted'); // transfer the token into the bridge IERC721Upgradeable(collectionAddress).safeTransferFrom(_msgSender(), address(this), tokenId); } // For every deposit we increase the counter to create a unique ID that can be used on the target side bridge to avoid double releases depositCount = depositCount + 1; // We always dispatch the deposit event with the "true" token address in the source network emit TokenDeposited(collectionAddress, tokenId, receiverAddress, _getChainID(), targetChainId, depositCount); } /** * @notice Releases an ERC721 token in this network after a deposit was made in another network (effectively completing a bridge transaction) * * @param sigV Array of recovery Ids for the signature * @param sigR Array of R values of the signatures * @param sigS Array of S values of the signatures * @param receiverAddress The account to receive the tokens * @param sourceNetworkCollectionAddress the address of the ERC721 contract in the network the deposit was made * @param tokenId The token id to be sent * @param depositChainId chain ID of the network in which the deposit was made * @param depositNumber The identifier of the corresponding deposit * @dev emits event TokenReleased after successful release */ function release( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address receiverAddress, address sourceNetworkCollectionAddress, uint256 tokenId, uint256 depositChainId, uint256 depositNumber ) external payable whenNotPaused { // check input parameters require( !releasedDeposits[depositChainId][depositNumber], 'CrossChainBridgeERC721V1: deposit was already processed and released' ); require( multiSignatureOracle.signaturesCheckERC721( sigV, sigR, sigS, receiverAddress, sourceNetworkCollectionAddress, tokenId, depositChainId, depositNumber ), 'CrossChainBridgeERC721V1: release not permitted. Not enough signatures from permitted oracles' ); // get collection address in release network address collectionAddress = sourceNetworkCollectionAddress; if (outsidePeggedCollections[collectionAddress] != address(0)) { collectionAddress = outsidePeggedCollections[collectionAddress]; } // calculate bridging fee uint256 nftBridgingFee = defaultBridgeFee; if (bridgeFees[collectionAddress] > 0) { nftBridgingFee = bridgeFees[collectionAddress]; } // check if transaction contains enough native tokens to pay the bridging fee require(msg.value >= nftBridgingFee, 'CrossChainBridgeERC721V1: bridging fee exceeds release transaction value'); // transfer bridging fee to buyBackAndBurn contract if (nftBridgingFee > 0) { buyBackAndBurn.depositNativeToken{value: nftBridgingFee}(nftBridgingFee); } // check if to-be-released token is part of the official collection (whitelisted) if (officialCollectionWhitelist[collectionAddress] == true) { ERC721Upgradeable(collectionAddress).safeTransferFrom(address(this), receiverAddress, tokenId); } else { MintableERC721(collectionAddress).mint(receiverAddress, tokenId); mintedDeposits[collectionAddress][tokenId] = true; } // update records to track released deposits releasedDeposits[depositChainId][depositNumber] = true; // release successful, deposit event emit TokenReleased(collectionAddress, tokenId, receiverAddress, depositChainId, depositNumber); } /** * @notice Removes an outside pegged collection * * @dev can only be called by MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE * @param collectionAddress the address of the collection contract */ function removeOutsidePeggedCollection(address collectionAddress) external { require( hasRole(MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE, _msgSender()), 'CrossChainBridgeERC721: must have MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE role to execute this function' ); outsidePeggedCollections[collectionAddress] = address(0); } /** * @notice Removes a token from the whitelist (i.e. stops bridging) * * @dev can only be called by MANAGE_FEES_ROLE * @param collectionAddress the address of the token contract * @dev emits event RemovedCollectionFromWhitelist after successful de-whitelisting */ function removeCollectionFromWhitelist(address collectionAddress) external { require( hasRole(MANAGE_COLLECTION_WHITELIST_ROLE, _msgSender()), 'CrossChainBridgeERC721: must have MANAGE_COLLECTION_WHITELIST_ROLE role to execute this function' ); officialCollectionWhitelist[collectionAddress] = false; emit RemovedCollectionFromWhitelist(collectionAddress); } /** * @notice Sets the default bridge (flat) fee that is being used for token buybacks and burns * * @dev can only be called by MANAGE_FEES_ROLE * @param fee flat fee amount in native token currency */ function setDefaultBridgeFee(uint256 fee) external { require( hasRole(MANAGE_FEES_ROLE, _msgSender()), 'CrossChainBridgeERC721: must have MANAGE_FEES_ROLE role to execute this function' ); defaultBridgeFee = fee; } /** * @notice Sets an individual bridge (flat) fee for the provided collection * * @dev can only be called by MANAGE_FEES_ROLE * @param collectionAddress the address of the token contract * @param fee flat fee amount in native token currency */ function setBridgeFee(address collectionAddress, uint256 fee) external { require( hasRole(MANAGE_FEES_ROLE, _msgSender()), 'CrossChainBridgeERC721: must have MANAGE_FEES_ROLE role to execute this function' ); bridgeFees[collectionAddress] = fee; } /** * @notice Sets the address for the BuyBackAndBurn contract that receives bridging fees to fund token burns * * @dev can only be called by MANAGE_COLLECTED_FEES_ROLE * @param buyBackAndBurnContract the address of the BuyBackAndBurn contract */ function setBuyBackAndBurn(IBuyBackAndBurn buyBackAndBurnContract) external { require( address(buyBackAndBurnContract) != address(0), 'CrossChainBridgeERC721: invalid buyBackAndBurnContract address provided' ); require( hasRole(MANAGE_COLLECTED_FEES_ROLE, _msgSender()), 'CrossChainBridgeERC721: must have MANAGE_COLLECTED_FEES_ROLE role to execute this function' ); buyBackAndBurn = buyBackAndBurnContract; } /** * @notice Sets the address for the MultiSignatureOracle contract * * @dev can only be called by MANAGE_ORACLES_ROLE * @param oracle the address of the MultiSignatureOracle contract */ function setMultiSignatureOracle(IMultiSignatureOracle oracle) external { require(address(oracle) != address(0), 'CrossChainBridgeERC721: invalid oracle address provided'); require( hasRole(MANAGE_ORACLES_ROLE, _msgSender()), 'CrossChainBridgeERC721: must have MANAGE_ORACLES_ROLE role to execute this function' ); multiSignatureOracle = oracle; } /** * @notice Always returns `this.onERC721Received.selector` * @dev see OpenZeppelin IERC721Receiver for more details */ function onERC721Received( address, address, uint256, bytes memory ) external virtual override returns (bytes4) { return this.onERC721Received.selector; } // returns the ID of the network this contract is deployed in function _getChainID() private view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import './IRouter.sol'; interface IBuyBackAndBurn { function depositERC20(IERC20 token, uint256 amount) external; function depositNativeToken(uint256 amount) external payable; //function iRouter() external returns (IRouter); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; interface IMultiSignatureOracle { function signaturesCheckERC721( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address receiverAddress, address collectionAddress, uint256 tokenId, uint256 depositChainId, uint256 depositNumber ) external returns (bool); function signaturesCheckERC20( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address receiverAddress, address sourceNetworkTokenAddress, uint256 amount, uint256 depositChainId, uint256 depositNumber ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol'; /** * @title MyPausableUpgradeable * This contracts introduces pausability,reentrancy guard and access control to all smart contracts that inherit from it */ abstract contract MyPausableUpgradeable is AccessControlUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, UUPSUpgradeable { bytes32 public constant PAUSABILITY_PAUSE_ROLE = keccak256('PAUSABILITY_PAUSE_ROLE'); bytes32 public constant PAUSABILITY_UNPAUSE_ROLE = keccak256('PAUSABILITY_UNPAUSE_ROLE'); bytes32 public constant MANAGE_UPGRADES_ROLE = keccak256('MANAGE_UPGRADES_ROLE'); /** * @notice Initializer instead of constructor to have the contract upgradeable * @dev can only be called once after deployment of the contract */ function __MyPausableUpgradeable_init() internal initializer { // call parent initializers __ReentrancyGuard_init(); __AccessControl_init(); __Pausable_init(); __UUPSUpgradeable_init(); // set up admin roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSABILITY_PAUSE_ROLE, _msgSender()); _setupRole(PAUSABILITY_UNPAUSE_ROLE, _msgSender()); _setupRole(MANAGE_UPGRADES_ROLE, _msgSender()); } /** * @notice This function s required to enable the OpenZeppelin UUPS proxy upgrade pattern * We decided to implement this function here as every other contract inherits from this one * * @dev can only be called by MANAGE_UPGRADES_ROLE */ function _authorizeUpgrade(address) internal view override { require( hasRole(MANAGE_UPGRADES_ROLE, _msgSender()), 'MyPausableUpgradeable: must have MANAGE_UPGRADES_ROLE to execute this function' ); } /** * @notice Pauses all contract functions that have the "whenNotPaused" modifier * * @dev can only be called by PAUSABILITY_ADMIN_ROLE */ function pause() external whenNotPaused { require( hasRole(PAUSABILITY_PAUSE_ROLE, _msgSender()), 'MyPausableUpgradeable: must have PAUSABILITY_PAUSE_ROLE to execute this function' ); PausableUpgradeable._pause(); } /** * @notice Un-pauses/resumes all contract functions that have the "whenNotPaused" modifier * * @dev can only be called by PAUSABILITY_ADMIN_ROLE */ function unpause() external whenPaused { require( hasRole(PAUSABILITY_UNPAUSE_ROLE, _msgSender()), 'MyPausableUpgradeable: must have PAUSABILITY_UNPAUSE_ROLE to execute this function' ); PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol'; import '../utils/MyPausableUpgradeable.sol'; /** * @title MintableERC721 * This is the base contract for LP tokens that are created by the CrossChainBridgeERC721 contract */ contract MintableERC721 is ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, MyPausableUpgradeable { bytes32 public constant MINTER_ROLE = keccak256('MINTER_ROLE'); bytes32 public constant MANAGE_TOKEN_ROLE = keccak256('MANAGE_TOKEN_ROLE'); string private _internalBaseURI; string private _customName; string private _customSymbol; /** * @notice Initializer instead of constructor to have the contract upgradeable * * @dev can only be called once after deployment of the contract * @param initName The name of the token to be created * @param initSymbol The symbol of the token to be created */ function initialize( string memory initName, string memory initSymbol, string memory baseURI ) external initializer { // call parent initializers __ERC721_init_unchained(initName, initSymbol); // must be called here since there is no such call in the parent contracts __ERC721Enumerable_init(); __MyPausableUpgradeable_init(); // set up admin roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(MANAGE_TOKEN_ROLE, _msgSender()); _internalBaseURI = baseURI; _customName = initName; _customSymbol = initSymbol; } function burn(uint256 tokenId) external virtual whenNotPaused { require(_isApprovedOrOwner(_msgSender(), tokenId), 'MintableERC721: caller is neither owner nor approved'); _burn(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721EnumerableUpgradeable, AccessControlUpgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } function setBaseURI(string memory newBaseUri) external { require( hasRole(MANAGE_TOKEN_ROLE, _msgSender()), 'MintableERC721: must have MANAGE_TOKEN_ROLE to execute this function' ); _internalBaseURI = newBaseUri; } function mint(address to, uint256 tokenId) public virtual whenNotPaused { require(hasRole(MINTER_ROLE, _msgSender()), 'MintableERC721: must have MINTER_ROLE to execute this function'); _mint(to, tokenId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721URIStorageUpgradeable, ERC721Upgradeable) returns (string memory) { return super.tokenURI(tokenId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) whenNotPaused { super._burn(tokenId); } function _baseURI() internal view override returns (string memory) { return _internalBaseURI; } function setTokenURI(uint256 tokenId, string memory _tokenURI) public { require( hasRole(MANAGE_TOKEN_ROLE, _msgSender()), 'MintableERC721: must have MANAGE_TOKEN_ROLE to execute this function' ); super._setTokenURI(tokenId, _tokenURI); } function setName(string memory newName) external { require( hasRole(MANAGE_TOKEN_ROLE, _msgSender()), 'MintableERC721: must have MANAGE_TOKEN_ROLE to execute this function' ); _customName = newName; } function setSymbol(string memory newSymbol) external { require( hasRole(MANAGE_TOKEN_ROLE, _msgSender()), 'MintableERC721: must have MANAGE_TOKEN_ROLE to execute this function' ); _customSymbol = newSymbol; } function name() public view override returns (string memory) { return _customName; } function symbol() public view override returns (string memory) { return _customSymbol; } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { super.safeTransferFrom(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IRouter { function tradeERC20( IERC20 collectedToken, IERC20 burnToken, uint256 amount ) external returns (uint256 tokensReceived); function tradeNativeTokenForERC20(IERC20 output, uint256 inputAmount) external payable returns (uint256); function addSwapPath( address input, address output, address[] memory path ) external; function wrappedNative() external returns (address); // function getDexAddress() external returns(address); } // 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"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @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 "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721URIStorage_init_unchained(); } function __ERC721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); }
Adds an outside pegged collection (= same collection but in a different network) can only be called by MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE depositChainCollectionAddress the address of the collection in the network the deposit is possible (deposit collection) peggedCollectionAddress the address of the pegged collection in the network this bridge contract is released on (release collection)/
function addOutsidePeggedCollection(address depositChainCollectionAddress, address peggedCollectionAddress) external { require( hasRole(MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE, _msgSender()), 'CrossChainBridgeERC721: must have MANAGE_OUTSIDE_PEGGED_COLLECTION_ROLE role to execute this function' ); require( depositChainCollectionAddress != address(0) && peggedCollectionAddress != address(0), 'CrossChainBridgeERC721V1: invalid collection address provided' ); outsidePeggedCollections[depositChainCollectionAddress] = peggedCollectionAddress; emit PeggedCollectionMappingAdded(depositChainCollectionAddress, peggedCollectionAddress); }
1,512,059
./full_match/80001/0x2964913Bc09333d3a744F6B87f741F86bcd768F1/sources/contracts/RecruitmentATSSmartContract.sol
Function to add an employer Ensure the employer does not already exist Add the employer
function addEmployer( string memory name, string memory emailAddress, address ethAddress ) public { require( employers[ethAddress].ethAddress == address(0), 'Employer already exists.' ); employers[ethAddress] = Employer(emailAddress, name, ethAddress); employersByEmail[emailAddress] = Employer( emailAddress, name, ethAddress ); }
5,670,054
./full_match/1/0xF5F0C19c4Fc2dc2A69eDcFCAE9E29892D544333b/sources/contracts/collections/ADaydreamForLibby/ADaydreamForLibby.sol
Computes a pseudorandom seed for a mint batch. Even though this process can be gamed in principle, it is extremly difficult to do so in practise. Therefore we can still rely on this to derive fair seeds.
function _computeBatchSeed(address to) private view returns (uint24) { return uint24( bytes3( keccak256( abi.encodePacked( block.timestamp, block.difficulty, blockhash(block.number - 1), to ) ) ) ); }
8,412,479
/** * SPDX-License-Identifier: MIT * * * Reference: https://github.com/ajlopez/DeFiProt/blob/master/contracts/test/StandardToken.sol * * * @Author defi3 * * * Creation, 2021-05 * * Main Update 1, 2021-06-17, migrate to ^0.8.0 * */ pragma solidity ^0.8.0; import "./IERC20.sol"; import "./ERC20Basic.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20Standard is IERC20, ERC20Basic { using ERC20Balances for mapping(address => uint256); mapping (address => mapping (address => uint256)) internal _allowances; /** * @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 amount uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 amount) public override returns (bool) { require(_allowances[from][msg.sender] >= amount); _balances.move(from, to, amount); _allowances[from][msg.sender] -= amount; emit Transfer(from, to, amount); 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 amount The amount of tokens to be spent. */ function approve(address spender, uint256 amount) public override returns (bool) { _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); 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 override returns (uint256) { return _allowances[owner][spender]; } }
Transfer tokens from one address to another from address The address which you want to send tokens from to address The address which you want to transfer to amount uint256 the amount of tokens to be transferred/
function transferFrom(address from, address to, uint256 amount) public override returns (bool) { require(_allowances[from][msg.sender] >= amount); _balances.move(from, to, amount); _allowances[from][msg.sender] -= amount; emit Transfer(from, to, amount); return true; }
6,486,213
pragma solidity ^0.4.19; import "./Fundraiser.sol"; import "../util/SafeMath.sol"; contract Core is Fundraiser { uint256 public campaignEscrowAmount = 0; // Required escrow to create a campaign. Default, zero uint256 public totalRaised = 0; // Total funds raised by the contract event ReadyCampaign(uint256 campaignId); // Campaign owner has marked campaign ready for activation event ActivateCampaign(uint256 campaignId); // Contract owner has marked campaign active event VetoCampaign(uint256 campaignId); // Contract owner has removed a campaign from the dapp // Create a new campaign. Must include escrow amount in tx. function createCampaign( string _campaignName, string _taxid ) public payable returns (uint256) { require(msg.value == campaignEscrowAmount); uint256 campaignId = _createCampaign(msg.sender, _campaignName, _taxid); campaignBalance[campaignId] += campaignEscrowAmount; return campaignId; } // Add a certificate to an existing campaign. Must be the campaign owner. Returns the new certificate index. function createCertificate( uint32 _campaignId, uint24 _supply, string _name, uint104 _price ) public returns (uint256) { require(campaignIndexToOwner[_campaignId] == msg.sender); require(_campaignId > 0); Campaign storage campaign = campaigns[_campaignId]; require(campaign.active == false); require(campaign.veto == false); require(campaign.ready == false); return _createCertificate(_campaignId, _supply, _name, _price); } // Change the values of an existing certificate. Campaign cannot be active. Must be campaign owner. function updateCertificate( uint256 _campaignId, uint256 _certificateIdx, uint24 _supply, string _name, uint104 _price ) public { require(campaignIndexToOwner[_campaignId] == msg.sender); require(_campaignId > 0); Campaign storage campaign = campaigns[_campaignId]; require(campaign.active == false); require(campaign.veto == false); require(campaign.ready == false); return _updateCertificate(_campaignId, _certificateIdx, _supply, _name, _price); } // Make a donation and issue the ERC-721 token for a campaign & certificate. Must include certificate price in tx. function createToken( uint128 _campaignId, uint256 _certificateIdx ) public payable returns (uint) { Campaign storage campaign = campaigns[_campaignId]; // Campaign is valid & active require(campaign.active == true); require(campaign.veto == false); // Ensure Token is still for sale Certificate storage certificate = campaignCertificates[_campaignId][_certificateIdx]; require(certificate.remaining > 0); require(msg.value == uint104(certificate.price)); uint24 unitNumber = certificate.supply - certificate.remaining + 1; campaignBalance[_campaignId] += msg.value; totalRaised += msg.value; return _createToken(_campaignId, _certificateIdx, unitNumber, msg.sender, msg.value); } // Campaign owner marks their campaign ready for activation function readyCampaign(uint256 _campaignId) public { require(_campaignId > 0); require(campaignIndexToOwner[_campaignId] == msg.sender); campaigns[_campaignId].ready = true; ReadyCampaign(_campaignId); } // Contract owner marks a campaign active. function activateCampaign(uint256 _campaignId) public onlyOwner { require(_campaignId > 0); require(campaigns[_campaignId].active == false); require(campaigns[_campaignId].veto == false); require(campaignCertificates[_campaignId].length > 0); campaigns[_campaignId].active = true; ActivateCampaign(_campaignId); } // Contract owner removes a campaign // Certs capped in Fundraiser function vetoCampaign(uint256 _campaignId) public onlyOwner { require(_campaignId > 0); delete campaigns[_campaignId]; campaigns[_campaignId].veto = true; campaigns[_campaignId].owner = owner; Certificate[] storage certificates = campaignCertificates[_campaignId]; for (uint256 i = 0; i < certificates.length; i++) { delete certificates[i]; } VetoCampaign(_campaignId); } // Contract owner changes the amount required to start a campaign function changeEscrowAmount(uint64 _campaignEscrowAmount) public onlyOwner { campaignEscrowAmount = _campaignEscrowAmount; } }
Contract owner changes the amount required to start a campaign
function changeEscrowAmount(uint64 _campaignEscrowAmount) public onlyOwner { campaignEscrowAmount = _campaignEscrowAmount; }
6,475,763
pragma solidity ^0.4.20; contract LotteryGenerator { address[] public lotteries; struct lottery{ uint index; address manager; } mapping(address => lottery) lotteryStructs; function createLottery(string name) public { require(bytes(name).length > 0); address newLottery = new Lottery(name, msg.sender); lotteryStructs[newLottery].index = lotteries.push(newLottery) - 1; lotteryStructs[newLottery].manager = msg.sender; // event LotteryCreated(newLottery); } function getLotteries() public view returns(address[]) { return lotteries; } function deleteLottery(address lotteryAddress) public { require(msg.sender == lotteryStructs[lotteryAddress].manager); uint indexToDelete = lotteryStructs[lotteryAddress].index; address lastAddress = lotteries[lotteries.length - 1]; lotteries[indexToDelete] = lastAddress; lotteries.length --; } // Events event LotteryCreated( address lotteryAddress ); } contract Lottery { // name of the lottery string public lotteryName; // Creator of the lottery contract address public manager; // variables for players struct Player { string name; uint entryCount; uint index; } address[] public addressIndexes; mapping(address => Player) players; address[] public lotteryBag; // Variables for lottery information Player public winner; bool public isLotteryLive; uint public maxEntriesForPlayer; uint public ethToParticipate; // constructor function Lottery(string name, address creator) public { manager = creator; lotteryName = name; } // Let users participate by sending eth directly to contract address function () public payable { // player name will be unknown participate("Unknown"); } function participate(string playerName) public payable { require(bytes(playerName).length > 0); require(isLotteryLive); require(msg.value == ethToParticipate * 1 ether); require(players[msg.sender].entryCount < maxEntriesForPlayer); if (isNewPlayer(msg.sender)) { players[msg.sender].entryCount = 1; players[msg.sender].name = playerName; players[msg.sender].index = addressIndexes.push(msg.sender) - 1; } else { players[msg.sender].entryCount += 1; } lotteryBag.push(msg.sender); // event PlayerParticipated(players[msg.sender].name, players[msg.sender].entryCount); } function activateLottery(uint maxEntries, uint ethRequired) public restricted { isLotteryLive = true; maxEntriesForPlayer = maxEntries == 0 ? 1: maxEntries; ethToParticipate = ethRequired == 0 ? 1: ethRequired; } function declareWinner() public restricted { require(lotteryBag.length > 0); uint index = generateRandomNumber() % lotteryBag.length; lotteryBag[index].transfer(this.balance); winner.name = players[lotteryBag[index]].name; winner.entryCount = players[lotteryBag[index]].entryCount; // empty the lottery bag and indexAddresses lotteryBag = new address[](0); addressIndexes = new address[](0); // Mark the lottery inactive isLotteryLive = false; // event WinnerDeclared(winner.name, winner.entryCount); } function getPlayers() public view returns(address[]) { return addressIndexes; } function getPlayer(address playerAddress) public view returns (string, uint) { if (isNewPlayer(playerAddress)) { return ("", 0); } return (players[playerAddress].name, players[playerAddress].entryCount); } function getWinningPrice() public view returns (uint) { return this.balance; } // Private functions function isNewPlayer(address playerAddress) private view returns(bool) { if (addressIndexes.length == 0) { return true; } return (addressIndexes[players[playerAddress].index] != playerAddress); } // NOTE: This should not be used for generating random number in real world function generateRandomNumber() private view returns(uint) { return uint(keccak256(block.difficulty, now, lotteryBag)); } // Modifiers modifier restricted() { require(msg.sender == manager); _; } // Events event WinnerDeclared( string name, uint entryCount ); event PlayerParticipated( string name, uint entryCount ); }
NOTE: This should not be used for generating random number in real world
function generateRandomNumber() private view returns(uint) { return uint(keccak256(block.difficulty, now, lotteryBag)); }
5,424,077
pragma solidity =0.6.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "./libraries/TransferHelper.sol"; import "./interfaces/IPancakeRouter02.sol"; import "./interfaces/IWETH.sol"; contract FeeReceiver is Pausable, Ownable { using SafeMath for uint256; event BuybackRateUpdated(uint256 newBuybackRate); event RevenueReceiverUpdated(address newRevenueReceiver); event RouterWhitelistUpdated(address router, bool status); event BuybackExecuted(uint256 amountBuyback, uint256 amountRevenue); address internal constant ZERO_ADDRESS = address(0); uint256 public constant FEE_DENOMINATOR = 10000; IPancakeRouter02 public pancakeRouter; address payable public revenueReceiver; uint256 public buybackRate; address public SYA; address public WETH; mapping(address => bool) public routerWhitelist; constructor( IPancakeRouter02 _pancakeRouterV2, address _SYA, address _WETH, address payable _revenueReceiver, uint256 _buybackRate ) public { pancakeRouter = _pancakeRouterV2; SYA = _SYA; WETH = _WETH; revenueReceiver = _revenueReceiver; buybackRate = _buybackRate; routerWhitelist[address(pancakeRouter)] = true; } /// @dev executes the buyback, buys SYA on pancake & sends revenue to the revenueReceiver by the defined rate. function executeBuyback() external whenNotPaused { require(address(this).balance > 0, "FeeReceiver: No balance for buyback"); address[] memory path = new address[](2); path[0] = WETH; path[1] = SYA; uint256 balance = address(this).balance; uint256 amountBuyback = balance.mul(buybackRate).div(FEE_DENOMINATOR); uint256 amountRevenue = balance.sub(amountBuyback); pancakeRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountBuyback}( 0, path, ZERO_ADDRESS, block.timestamp ); TransferHelper.safeTransferETH(revenueReceiver, amountRevenue); emit BuybackExecuted(amountBuyback, amountRevenue); } /// @dev converts collected tokens from fees to ETH for executing buybacks function convertToETH( address _router, IERC20 _token, bool _fee ) public whenNotPaused { require(routerWhitelist[_router], "FeeReceiver: Router not whitelisted"); address[] memory path = new address[](2); path[0] = address(_token); path[1] = WETH; uint256 balance = _token.balanceOf(address(this)); TransferHelper.safeApprove(address(_token), address(pancakeRouter), balance); if (_fee) { IPancakeRouter02(_router).swapExactTokensForETHSupportingFeeOnTransferTokens( balance, 0, path, address(this), block.timestamp ); } else { IPancakeRouter02(_router).swapExactTokensForETH(balance, 0, path, address(this), block.timestamp); } } /// @dev converts WETH to ETH function unwrapWETH() public whenNotPaused { uint256 balance = IWETH(WETH).balanceOf(address(this)); require(balance > 0, "FeeReceiver: Nothing to unwrap"); IWETH(WETH).withdraw(balance); } /// @dev lets the owner update update the router whitelist function updateRouterWhiteliste(address _router, bool _status) external onlyOwner { routerWhitelist[_router] = _status; emit RouterWhitelistUpdated(_router, _status); } /// @dev lets the owner update the buyback rate function updateBuybackRate(uint256 _newBuybackRate) external onlyOwner { buybackRate = _newBuybackRate; emit BuybackRateUpdated(_newBuybackRate); } /// @dev lets the owner update the revenue receiver address function updateRevenueReceiver(address payable _newRevenueReceiver) external onlyOwner { revenueReceiver = _newRevenueReceiver; emit RevenueReceiverUpdated(_newRevenueReceiver); } /// @dev lets the owner withdraw ETH from the contract function withdrawETH(address payable to, uint256 amount) external onlyOwner { to.transfer(amount); } /// @dev lets the owner withdraw any ERC20 Token from the contract function withdrawERC20Token( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /// @dev allows to receive ETH on this contract receive() external payable {} /// @dev lets the owner pause the contract function pause() external onlyOwner { _pause(); } /// @dev lets the owner unpause the contract function unpause() external onlyOwner { _unpause(); } } // 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 "../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()); } } pragma solidity =0.6.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED"); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED"); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED"); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "TransferHelper: ETH_TRANSFER_FAILED"); } } pragma solidity >=0.6.2; import "./IPancakeRouter01.sol"; interface IPancakeRouter02 is IPancakeRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; function approve(address _spender, uint256 _amount) external returns (bool); function balanceOf(address _account) external view returns (uint256); } // 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; } } pragma solidity >=0.6.2; interface IPancakeRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } pragma solidity =0.6.6; import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "./libraries/TransferHelper.sol"; import "./libraries/PancakeLibrary.sol"; import "./interfaces/IReferralRegistry.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IZerox.sol"; contract FloozRouter is Ownable, Pausable, ReentrancyGuard { using SafeMath for uint256; using LibBytesV06 for bytes; event SwapFeeUpdated(uint16 swapFee); event ReferralRegistryUpdated(address referralRegistry); event ReferralRewardRateUpdated(uint16 referralRewardRate); event ReferralsActivatedUpdated(bool activated); event FeeReceiverUpdated(address payable feeReceiver); event BalanceThresholdUpdated(uint256 balanceThreshold); event CustomReferralRewardRateUpdated(address indexed account, uint16 referralRate); event ReferralRewardPaid(address from, address indexed to, address tokenOut, address tokenReward, uint256 amount); event ForkUpdated(address factory); // Denominator of fee uint256 public constant FEE_DENOMINATOR = 10000; // Numerator of fee uint16 public swapFee; // address of WETH address public immutable WETH; // address of zeroEx proxy contract to forward swaps address payable public immutable zeroEx; // address of referral registry that stores referral anchors IReferralRegistry public referralRegistry; // address of SYA token IERC20 public saveYourAssetsToken; // balance threshold of SYA tokens which actives feeless swapping uint256 public balanceThreshold; // address that receives protocol fees address payable public feeReceiver; // percentage of fees that will be paid as rewards uint16 public referralRewardRate; // stores if the referral system is turned on or off bool public referralsActivated; // stores individual referral rates mapping(address => uint16) public customReferralRewardRate; // stores uniswap forks status, index is the factory address mapping(address => bool) public forkActivated; // stores uniswap forks initCodes, index is the factory address mapping(address => bytes) public forkInitCode; /// @dev construct this contract /// @param _WETH address of WETH. /// @param _swapFee nominator for swapFee. Denominator = 10000 /// @param _referralRewardRate percentage of swapFee that are paid out as rewards /// @param _feeReceiver address that receives protocol fees /// @param _balanceThreshold balance threshold of SYA tokens which actives feeless swapping /// @param _saveYourAssetsToken address of SYA token /// @param _referralRegistry address of referral registry that stores referral anchors /// @param _zeroEx address of zeroX proxy contract to forward swaps constructor( address _WETH, uint16 _swapFee, uint16 _referralRewardRate, address payable _feeReceiver, uint256 _balanceThreshold, IERC20 _saveYourAssetsToken, IReferralRegistry _referralRegistry, address payable _zeroEx ) public { WETH = _WETH; swapFee = _swapFee; referralRewardRate = _referralRewardRate; feeReceiver = _feeReceiver; saveYourAssetsToken = _saveYourAssetsToken; balanceThreshold = _balanceThreshold; referralRegistry = _referralRegistry; zeroEx = _zeroEx; referralsActivated = true; } /// @dev execute swap directly on Uniswap/Pancake & simular forks /// @param fork fork used to execute swap /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapExactETHForTokens( address fork, uint256 amountOutMin, address[] calldata path, address referee ) external payable whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); referee = _getReferee(referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( msg.value, referee, false ); amounts = _getAmountsOut(fork, swapAmount, path); require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(_pairFor(fork, path[0], path[1]), amounts[0])); _swap(fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountIn amount of tokensIn /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none function swapExactTokensForETHSupportingFeeOnTransferTokens( address fork, uint256 amountIn, uint256 amountOutMin, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); referee = _getReferee(referee); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amountIn); _swapSupportingFeeOnTransferTokens(fork, path, address(this)); uint256 amountOut = IERC20(WETH).balanceOf(address(this)); IWETH(WETH).withdraw(amountOut); (uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( amountOut, referee, false ); require(amountWithdraw >= amountOutMin, "FloozRouter: LOW_SLIPPAGE"); TransferHelper.safeTransferETH(msg.sender, amountWithdraw); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapExactTokensForTokens( address fork, uint256 amountIn, uint256 amountOutMin, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { referee = _getReferee(referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( amountIn, referee, false ); amounts = _getAmountsOut(fork, swapAmount, path); require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), swapAmount); _swap(fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapExactTokensForETH( address fork, uint256 amountIn, uint256 amountOutMin, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); referee = _getReferee(referee); amounts = _getAmountsOut(fork, amountIn, path); (uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( amounts[amounts.length - 1], referee, false ); require(amountWithdraw >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amounts[0]); _swap(fork, amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(msg.sender, amountWithdraw); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountOut expected amount of tokens out /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapETHForExactTokens( address fork, uint256 amountOut, address[] calldata path, address referee ) external payable whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); amounts = _getAmountsIn(fork, amountOut, path); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(amounts[0], referee, true); require(amounts[0].add(feeAmount).add(referralReward) <= msg.value, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(_pairFor(fork, path[0], path[1]), amounts[0])); _swap(fork, amounts, path, msg.sender); // refund dust eth, if any if (msg.value > amounts[0].add(feeAmount).add(referralReward)) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0].add(feeAmount).add(referralReward)); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none function swapExactTokensForTokensSupportingFeeOnTransferTokens( address fork, uint256 amountIn, uint256 amountOutMin, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) { referee = _getReferee(referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( amountIn, referee, false ); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), swapAmount); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender); _swapSupportingFeeOnTransferTokens(fork, path, msg.sender); require( IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountOut expected tokens to receive /// @param amountInMax maximum tokens to send /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapTokensForExactTokens( address fork, uint256 amountOut, uint256 amountInMax, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { referee = _getReferee(referee); amounts = _getAmountsIn(fork, amountOut, path); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(amounts[0], referee, true); require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amounts[0]); _swap(fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountOut expected tokens to receive /// @param amountInMax maximum tokens to send /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapTokensForExactETH( address fork, uint256 amountOut, uint256 amountInMax, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); referee = _getReferee(referee); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(amountOut, referee, true); amounts = _getAmountsIn(fork, amountOut.add(feeAmount).add(referralReward), path); require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amounts[0]); _swap(fork, amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(msg.sender, amountOut); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountOutMin minimum expected tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none function swapExactETHForTokensSupportingFeeOnTransferTokens( address fork, uint256 amountOutMin, address[] calldata path, address referee ) external payable whenNotPaused isValidFork(fork) isValidReferee(referee) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); referee = _getReferee(referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( msg.value, referee, false ); IWETH(WETH).deposit{value: swapAmount}(); assert(IWETH(WETH).transfer(_pairFor(fork, path[0], path[1]), swapAmount)); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender); _swapSupportingFeeOnTransferTokens(fork, path, msg.sender); require( IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev returns the referee for a given address, if new, registers referee /// @param referee the address of the referee for msg.sender /// @return referee address from referral registry function _getReferee(address referee) internal returns (address) { address sender = msg.sender; if (!referralRegistry.hasUserReferee(sender) && referee != address(0)) { referralRegistry.createReferralAnchor(sender, referee); } return referralRegistry.getUserReferee(sender); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap( address fork, uint256[] memory amounts, address[] memory path, address _to ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = PancakeLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to; IPancakePair(_pairFor(fork, input, output)).swap(amount0Out, amount1Out, to, new bytes(0)); } } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens( address fork, address[] memory path, address _to ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = PancakeLibrary.sortTokens(input, output); IPancakePair pair = IPancakePair(_pairFor(fork, input, output)); uint256 amountInput; uint256 amountOutput; { // scope to avoid stack too deep errors (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (uint256 reserveInput, uint256 reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = _getAmountOut(amountInput, reserveInput, reserveOutput); } (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0)); address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } /// @dev Fallback function to execute swaps directly on 0x for users that don't pay a fee /// @dev params as of API documentation from 0x API (https://0x.org/docs/api#response-1) fallback() external payable { require(userAboveBalanceThreshold(msg.sender), "FloozRouter: FORBIDDEN"); bytes4 selector = msg.data.readBytes4(0); address impl = IZerox(zeroEx).getFunctionImplementation(selector); require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION"); (bool success, ) = impl.delegatecall(msg.data); require(success, "FloozRouter: REVERTED"); } /// @dev Executes a swap on 0x API /// @param data calldata expected by data field on 0x API (https://0x.org/docs/api#response-1) /// @param tokenOut the address of currency to sell – 0x address for ETH /// @param tokenIn the address of currency to buy – 0x address for ETH /// @param referee address of referee for msg.sender, 0x adress if none function executeZeroExSwap( bytes calldata data, address tokenOut, address tokenIn, address referee ) external payable nonReentrant whenNotPaused isValidReferee(referee) { referee = _getReferee(referee); bytes4 selector = data.readBytes4(0); address impl = IZerox(zeroEx).getFunctionImplementation(selector); require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION"); bool isAboveThreshold = userAboveBalanceThreshold(msg.sender); // skip fees & rewards for god mode users if (isAboveThreshold) { (bool success, ) = impl.delegatecall(data); require(success, "FloozRouter: REVERTED"); } else { // if ETH in execute trade as router & distribute funds & fees if (msg.value > 0) { (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( msg.value, referee, false ); (bool success, ) = impl.call{value: swapAmount}(data); require(success, "FloozRouter: REVERTED"); TransferHelper.safeTransfer(tokenIn, msg.sender, IERC20(tokenIn).balanceOf(address(this))); _withdrawFeesAndRewards(address(0), tokenIn, referee, feeAmount, referralReward); } else { uint256 balanceBefore = IERC20(tokenOut).balanceOf(msg.sender); (bool success, ) = impl.delegatecall(data); require(success, "FloozRouter: REVERTED"); uint256 balanceAfter = IERC20(tokenOut).balanceOf(msg.sender); require(balanceBefore > balanceAfter, "INVALID_TOKEN"); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( balanceBefore.sub(balanceAfter), referee, true ); _withdrawFeesAndRewards(tokenOut, tokenIn, referee, feeAmount, referralReward); } } } /// @dev calculates swap, fee & reward amounts /// @param amount total amount of tokens /// @param referee the address of the referee for msg.sender function _calculateFeesAndRewards( uint256 amount, address referee, bool additiveFee ) internal view returns ( uint256 swapAmount, uint256 feeAmount, uint256 referralReward ) { // no fees for users above threshold if (userAboveBalanceThreshold(msg.sender)) { swapAmount = amount; } else { if (additiveFee) { swapAmount = amount; feeAmount = swapAmount.mul(FEE_DENOMINATOR).div(FEE_DENOMINATOR.sub(swapFee)).sub(amount); } else { feeAmount = amount.mul(swapFee).div(FEE_DENOMINATOR); swapAmount = amount.sub(feeAmount); } // calculate referral rates, if referee is not 0x if (referee != address(0) && referralsActivated) { uint16 referralRate = customReferralRewardRate[referee] > 0 ? customReferralRewardRate[referee] : referralRewardRate; referralReward = feeAmount.mul(referralRate).div(FEE_DENOMINATOR); feeAmount = feeAmount.sub(referralReward); } else { referralReward = 0; } } } /// @dev lets the admin update an Uniswap style fork function updateFork( address _factory, bytes calldata _initCode, bool _activated ) external onlyOwner { forkActivated[_factory] = _activated; forkInitCode[_factory] = _initCode; emit ForkUpdated(_factory); } /// @dev returns if a users is above the SYA threshold and can swap without fees function userAboveBalanceThreshold(address _account) public view returns (bool) { return saveYourAssetsToken.balanceOf(_account) >= balanceThreshold; } /// @dev returns the fee nominator for a given user function getUserFee(address user) public view returns (uint256) { saveYourAssetsToken.balanceOf(user) >= balanceThreshold ? 0 : swapFee; } /// @dev lets the admin update the swapFee nominator function updateSwapFee(uint16 newSwapFee) external onlyOwner { swapFee = newSwapFee; emit SwapFeeUpdated(newSwapFee); } /// @dev lets the admin update the referral reward rate function updateReferralRewardRate(uint16 newReferralRewardRate) external onlyOwner { require(newReferralRewardRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE"); referralRewardRate = newReferralRewardRate; emit ReferralRewardRateUpdated(newReferralRewardRate); } /// @dev lets the admin update which address receives the protocol fees function updateFeeReceiver(address payable newFeeReceiver) external onlyOwner { feeReceiver = newFeeReceiver; emit FeeReceiverUpdated(newFeeReceiver); } /// @dev lets the admin update the SYA balance threshold, which activates feeless trading for users function updateBalanceThreshold(uint256 newBalanceThreshold) external onlyOwner { balanceThreshold = newBalanceThreshold; emit BalanceThresholdUpdated(balanceThreshold); } /// @dev lets the admin update the status of the referral system function updateReferralsActivated(bool newReferralsActivated) external onlyOwner { referralsActivated = newReferralsActivated; emit ReferralsActivatedUpdated(newReferralsActivated); } /// @dev lets the admin set a new referral registry function updateReferralRegistry(address newReferralRegistry) external onlyOwner { referralRegistry = IReferralRegistry(newReferralRegistry); emit ReferralRegistryUpdated(newReferralRegistry); } /// @dev lets the admin set a custom referral rate function updateCustomReferralRewardRate(address account, uint16 referralRate) external onlyOwner returns (uint256) { require(referralRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE"); customReferralRewardRate[account] = referralRate; emit CustomReferralRewardRateUpdated(account, referralRate); } /// @dev returns the referee for a given user – 0x address if none function getUserReferee(address user) external view returns (address) { return referralRegistry.getUserReferee(user); } /// @dev returns if the given user has been referred or not function hasUserReferee(address user) external view returns (bool) { return referralRegistry.hasUserReferee(user); } /// @dev lets the admin withdraw ETH from the contract. function withdrawETH(address payable to, uint256 amount) external onlyOwner { TransferHelper.safeTransferETH(to, amount); } /// @dev lets the admin withdraw ERC20s from the contract. function withdrawERC20Token( address token, address to, uint256 amount ) external onlyOwner { TransferHelper.safeTransfer(token, to, amount); } /// @dev distributes fees & referral rewards to users function _withdrawFeesAndRewards( address tokenReward, address tokenOut, address referee, uint256 feeAmount, uint256 referralReward ) internal { if (tokenReward == address(0)) { TransferHelper.safeTransferETH(feeReceiver, feeAmount); if (referralReward > 0) { TransferHelper.safeTransferETH(referee, referralReward); emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward); } } else { TransferHelper.safeTransferFrom(tokenReward, msg.sender, feeReceiver, feeAmount); if (referralReward > 0) { TransferHelper.safeTransferFrom(tokenReward, msg.sender, referee, referralReward); emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward); } } } /// @dev given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function _getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "FloozRouter: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn.mul((9980)); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(10000).add(amountInWithFee); amountOut = numerator / denominator; } /// @dev given an output amount of an asset and pair reserves, returns a required input amount of the other asset function _getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn.mul(amountOut).mul(10000); uint256 denominator = reserveOut.sub(amountOut).mul(9980); amountIn = (numerator / denominator).add(1); } /// @dev performs chained getAmountOut calculations on any number of pairs function _getAmountsOut( address fork, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "FloozRouter: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = _getReserves(fork, path[i], path[i + 1]); amounts[i + 1] = _getAmountOut(amounts[i], reserveIn, reserveOut); } } /// @dev performs chained getAmountIn calculations on any number of pairs function _getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "FloozRouter: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = _getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut); } } /// @dev fetches and sorts the reserves for a pair function _getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = PancakeLibrary.sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IPancakePair(_pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } /// @dev calculates the CREATE2 address for a pair without making any external calls function _pairFor( address factory, address tokenA, address tokenB ) internal view returns (address pair) { (address token0, address token1) = PancakeLibrary.sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), forkInitCode[factory] // init code hash ) ) ) ); } /// @dev lets the admin pause this contract function pause() external onlyOwner { _pause(); } /// @dev lets the admin unpause this contract function unpause() external onlyOwner { _unpause(); } /// @dev allows to receive ETH on the contract receive() external payable {} modifier isValidFork(address factory) { require(forkActivated[factory], "FloozRouter: INVALID_FACTORY"); _; } modifier isValidReferee(address referee) { require(msg.sender != referee, "FloozRouter: SELF_REFERRAL"); _; } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "./errors/LibBytesRichErrorsV06.sol"; import "./errors/LibRichErrorsV06.sol"; library LibBytesV06 { using LibBytesV06 for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// When `from == 0`, the original array will match the slice. /// In other cases its state will be corrupted. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, b.length, 0 )); } // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return equal True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { if (b.length < index + 20) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { if (b.length < index + 20) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return result bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { if (b.length < index + 32) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { if (b.length < index + 32) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return result bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { if (b.length < index + 4) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, b.length, index + 4 )); } // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } } } // 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; } } pragma solidity =0.6.6; import "@openzeppelin/contracts/math/SafeMath.sol"; interface IPancakePair { 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; } library PancakeLibrary { using SafeMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "PancakeLibrary: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "PancakeLibrary: ZERO_ADDRESS"); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "PancakeLibrary: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "PancakeLibrary: INSUFFICIENT_LIQUIDITY"); amountB = amountA.mul(reserveB) / reserveA; } } pragma solidity >=0.5.0; interface IReferralRegistry { function getUserReferee(address _user) external view returns (address); function hasUserReferee(address _user) external view returns (bool); function createReferralAnchor(address _user, address _referee) external; } pragma solidity ^0.6.5; interface IZerox { function getFunctionImplementation(bytes4 selector) external returns (address payable); } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibBytesRichErrorsV06 { enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, LengthGreaterThanZeroRequired, LengthGreaterThanOrEqualsFourRequired, LengthGreaterThanOrEqualsTwentyRequired, LengthGreaterThanOrEqualsThirtyTwoRequired, LengthGreaterThanOrEqualsNestedBytesLengthRequired, DestinationLengthGreaterThanOrEqualSourceLengthRequired } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required ); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibRichErrorsV06 { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError(string memory message) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } pragma solidity =0.6.6; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "./libraries/TransferHelper.sol"; import "./libraries/PancakeLibrary.sol"; import "./interfaces/IReferralRegistry.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IZerox.sol"; contract TestMultichainRouter is Ownable, Pausable, ReentrancyGuard { using SafeMath for uint256; using LibBytesV06 for bytes; event SwapFeeUpdated(uint16 swapFee); event ReferralRegistryUpdated(address referralRegistry); event ReferralRewardRateUpdated(uint16 referralRewardRate); event ReferralsActivatedUpdated(bool activated); event FeeReceiverUpdated(address payable feeReceiver); event CustomReferralRewardRateUpdated(address indexed account, uint16 referralRate); event ReferralRewardPaid(address from, address indexed to, address tokenOut, address tokenReward, uint256 amount); event ForkCreated(address factory); event ForkUpdated(address factory); struct SwapData { address fork; address referee; bool fee; } // Denominator of fee uint256 public constant FEE_DENOMINATOR = 10000; // Numerator of fee uint16 public swapFee; // address of WETH address public immutable WETH; // address of zeroEx proxy contract to forward swaps address payable public immutable zeroEx; // address of referral registry that stores referral anchors IReferralRegistry public referralRegistry; // address that receives protocol fees address payable public feeReceiver; // percentage of fees that will be paid as rewards uint16 public referralRewardRate; // stores if the referral system is turned on or off bool public referralsActivated; // stores individual referral rates mapping(address => uint16) public customReferralRewardRate; // stores uniswap forks status, index is the factory address mapping(address => bool) public forkActivated; // stores uniswap forks initCodes, index is the factory address mapping(address => bytes) public forkInitCode; /// @dev construct this contract /// @param _WETH address of WETH. /// @param _swapFee nominator for swapFee. Denominator = 10000 /// @param _referralRewardRate percentage of swapFee that are paid out as rewards /// @param _feeReceiver address that receives protocol fees /// @param _referralRegistry address of referral registry that stores referral anchors /// @param _zeroEx address of zeroX proxy contract to forward swaps constructor( address _WETH, uint16 _swapFee, uint16 _referralRewardRate, address payable _feeReceiver, IReferralRegistry _referralRegistry, address payable _zeroEx ) public { WETH = _WETH; swapFee = _swapFee; referralRewardRate = _referralRewardRate; feeReceiver = _feeReceiver; referralRegistry = _referralRegistry; zeroEx = _zeroEx; referralsActivated = true; } /// @dev execute swap directly on Uniswap/Pancake & simular forks /// @param swapData stores the swapData information /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @return amounts function swapExactETHForTokens( SwapData calldata swapData, uint256 amountOutMin, address[] calldata path ) external payable whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, msg.value, referee, false ); amounts = _getAmountsOut(swapData.fork, swapAmount, path); require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), amounts[0])); _swap(swapData.fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountIn amount of tokensIn /// @param amountOutMin minimum tokens to receive /// @param path Sell path. function swapExactTokensForETHSupportingFeeOnTransferTokens( SwapData calldata swapData, uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amountIn); _swapSupportingFeeOnTransferTokens(swapData.fork, path, address(this)); uint256 amountOut = IERC20(WETH).balanceOf(address(this)); IWETH(WETH).withdraw(amountOut); (uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amountOut, referee, false ); require(amountWithdraw >= amountOutMin, "FloozRouter: LOW_SLIPPAGE"); TransferHelper.safeTransferETH(msg.sender, amountWithdraw); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @return amounts function swapExactTokensForTokens( SwapData calldata swapData, uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { address referee = _getReferee(swapData.referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amountIn, referee, false ); amounts = _getAmountsOut(swapData.fork, swapAmount, path); require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), swapAmount); _swap(swapData.fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @return amounts function swapExactTokensForETH( SwapData calldata swapData, uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); amounts = _getAmountsOut(swapData.fork, amountIn, path); (uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amounts[amounts.length - 1], referee, false ); require(amountWithdraw >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]); _swap(swapData.fork, amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(msg.sender, amountWithdraw); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountOut expected amount of tokens out /// @param path Sell path. /// @return amounts function swapETHForExactTokens( SwapData calldata swapData, uint256 amountOut, address[] calldata path ) external payable whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); amounts = _getAmountsIn(swapData.fork, amountOut, path); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amounts[0], referee, true ); require(amounts[0].add(feeAmount).add(referralReward) <= msg.value, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), amounts[0])); _swap(swapData.fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); // refund dust eth, if any if (msg.value > amounts[0].add(feeAmount).add(referralReward)) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0].add(feeAmount).add(referralReward)); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. function swapExactTokensForTokensSupportingFeeOnTransferTokens( SwapData calldata swapData, uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) { address referee = _getReferee(swapData.referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amountIn, referee, false ); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), swapAmount); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender); _swapSupportingFeeOnTransferTokens(swapData.fork, path, msg.sender); require( IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountOut expected tokens to receive /// @param amountInMax maximum tokens to send /// @param path Sell path. /// @return amounts function swapTokensForExactTokens( SwapData calldata swapData, uint256 amountOut, uint256 amountInMax, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { address referee = _getReferee(swapData.referee); amounts = _getAmountsIn(swapData.fork, amountOut, path); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amounts[0], referee, true ); require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]); _swap(swapData.fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountOut expected tokens to receive /// @param amountInMax maximum tokens to send /// @param path Sell path. /// @return amounts function swapTokensForExactETH( SwapData calldata swapData, uint256 amountOut, uint256 amountInMax, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amountOut, referee, true ); amounts = _getAmountsIn(swapData.fork, amountOut.add(feeAmount).add(referralReward), path); require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]); _swap(swapData.fork, amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(msg.sender, amountOut); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountOutMin minimum expected tokens to receive /// @param path Sell path. function swapExactETHForTokensSupportingFeeOnTransferTokens( SwapData calldata swapData, uint256 amountOutMin, address[] calldata path ) external payable whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, msg.value, referee, false ); IWETH(WETH).deposit{value: swapAmount}(); assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), swapAmount)); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender); _swapSupportingFeeOnTransferTokens(swapData.fork, path, msg.sender); require( IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev returns the referee for a given address, if new, registers referee /// @param referee the address of the referee for msg.sender /// @return referee address from referral registry function _getReferee(address referee) internal returns (address) { address sender = msg.sender; if (!referralRegistry.hasUserReferee(sender) && referee != address(0)) { referralRegistry.createReferralAnchor(sender, referee); } return referralRegistry.getUserReferee(sender); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap( address fork, uint256[] memory amounts, address[] memory path, address _to ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = PancakeLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to; IPancakePair(_pairFor(fork, input, output)).swap(amount0Out, amount1Out, to, new bytes(0)); } } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens( address fork, address[] memory path, address _to ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = PancakeLibrary.sortTokens(input, output); IPancakePair pair = IPancakePair(_pairFor(fork, input, output)); uint256 amountInput; uint256 amountOutput; { // scope to avoid stack too deep errors (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (uint256 reserveInput, uint256 reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = _getAmountOut(amountInput, reserveInput, reserveOutput); } (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0)); address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } /// @dev Fallback function to execute swaps directly on 0x for users that don't pay a fee /// @dev params as of API documentation from 0x API (https://0x.org/docs/api#response-1) fallback() external payable { bytes4 selector = msg.data.readBytes4(0); address impl = IZerox(zeroEx).getFunctionImplementation(selector); require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION"); (bool success, ) = impl.delegatecall(msg.data); require(success, "FloozRouter: REVERTED"); } /// @dev Executes a swap on 0x API /// @param data calldata expected by data field on 0x API (https://0x.org/docs/api#response-1) /// @param tokenOut the address of currency to sell - 0x address for ETH /// @param tokenIn the address of currency to buy - 0x address for ETH /// @param referee address of referee for msg.sender, 0x adress if none /// @param fee boolean if fee should be applied or not function executeZeroExSwap( bytes calldata data, address tokenOut, address tokenIn, address referee, bool fee ) external payable nonReentrant whenNotPaused isValidReferee(referee) { referee = _getReferee(referee); bytes4 selector = data.readBytes4(0); address impl = IZerox(zeroEx).getFunctionImplementation(selector); require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION"); if (!fee) { (bool success, ) = impl.delegatecall(data); require(success, "FloozRouter: REVERTED"); } else { // if ETH in execute trade as router & distribute funds & fees if (msg.value > 0) { (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( fee, msg.value, referee, false ); _withdrawFeesAndRewards(address(0), tokenIn, referee, feeAmount, referralReward); (bool success, ) = impl.call{value: swapAmount}(data); require(success, "FloozRouter: REVERTED"); TransferHelper.safeTransfer(tokenIn, msg.sender, IERC20(tokenIn).balanceOf(address(this))); } else { uint256 balanceBefore = IERC20(tokenOut).balanceOf(msg.sender); (bool success, ) = impl.delegatecall(data); require(success, "FloozRouter: REVERTED"); uint256 balanceAfter = IERC20(tokenOut).balanceOf(msg.sender); require(balanceBefore > balanceAfter, "INVALID_TOKEN"); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( fee, balanceBefore.sub(balanceAfter), referee, true ); _withdrawFeesAndRewards(tokenOut, tokenIn, referee, feeAmount, referralReward); } } } /// @dev calculates swap, fee & reward amounts /// @param fee boolean if fee will be applied or not /// @param amount total amount of tokens /// @param referee the address of the referee for msg.sender function _calculateFeesAndRewards( bool fee, uint256 amount, address referee, bool additiveFee ) internal view returns ( uint256 swapAmount, uint256 feeAmount, uint256 referralReward ) { // no fees for users above threshold if (!fee) { swapAmount = amount; } else { if (additiveFee) { swapAmount = amount; feeAmount = swapAmount.mul(FEE_DENOMINATOR).div(FEE_DENOMINATOR.sub(swapFee)).sub(amount); } else { feeAmount = amount.mul(swapFee).div(FEE_DENOMINATOR); swapAmount = amount.sub(feeAmount); } // calculate referral rates, if referee is not 0x if (referee != address(0) && referralsActivated) { uint16 referralRate = customReferralRewardRate[referee] > 0 ? customReferralRewardRate[referee] : referralRewardRate; referralReward = feeAmount.mul(referralRate).div(FEE_DENOMINATOR); feeAmount = feeAmount.sub(referralReward); } else { referralReward = 0; } } } /// @dev lets the admin register an Uniswap style fork function registerFork(address _factory, bytes calldata _initCode) external onlyOwner { require(!forkActivated[_factory], "FloozRouter: ACTIVE_FORK"); forkActivated[_factory] = true; forkInitCode[_factory] = _initCode; emit ForkCreated(_factory); } /// @dev lets the admin update an Uniswap style fork function updateFork( address _factory, bytes calldata _initCode, bool _activated ) external onlyOwner { forkActivated[_factory] = _activated; forkInitCode[_factory] = _initCode; emit ForkUpdated(_factory); } /// @dev lets the admin update the swapFee nominator function updateSwapFee(uint16 newSwapFee) external onlyOwner { swapFee = newSwapFee; emit SwapFeeUpdated(newSwapFee); } /// @dev lets the admin update the referral reward rate function updateReferralRewardRate(uint16 newReferralRewardRate) external onlyOwner { referralRewardRate = newReferralRewardRate; emit ReferralRewardRateUpdated(newReferralRewardRate); } /// @dev lets the admin update which address receives the protocol fees function updateFeeReceiver(address payable newFeeReceiver) external onlyOwner { feeReceiver = newFeeReceiver; emit FeeReceiverUpdated(newFeeReceiver); } /// @dev lets the admin update the status of the referral system function updateReferralsActivated(bool newReferralsActivated) external onlyOwner { referralsActivated = newReferralsActivated; emit ReferralsActivatedUpdated(newReferralsActivated); } /// @dev lets the admin set a new referral registry function updateReferralRegistry(address newReferralRegistry) external onlyOwner { referralRegistry = IReferralRegistry(newReferralRegistry); emit ReferralRegistryUpdated(newReferralRegistry); } /// @dev lets the admin set a custom referral rate function updateCustomReferralRewardRate(address account, uint16 referralRate) external onlyOwner returns (uint256) { require(referralRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE"); customReferralRewardRate[account] = referralRate; emit CustomReferralRewardRateUpdated(account, referralRate); } /// @dev returns the referee for a given user - 0x address if none function getUserReferee(address user) external view returns (address) { return referralRegistry.getUserReferee(user); } /// @dev returns if the given user has been referred or not function hasUserReferee(address user) external view returns (bool) { return referralRegistry.hasUserReferee(user); } /// @dev lets the admin withdraw ETH from the contract. function withdrawETH(address payable to, uint256 amount) external onlyOwner { TransferHelper.safeTransferETH(to, amount); } /// @dev lets the admin withdraw ERC20s from the contract. function withdrawERC20Token( address token, address to, uint256 amount ) external onlyOwner { TransferHelper.safeTransfer(token, to, amount); } /// @dev distributes fees & referral rewards to users function _withdrawFeesAndRewards( address tokenReward, address tokenOut, address referee, uint256 feeAmount, uint256 referralReward ) internal { if (tokenReward == address(0)) { TransferHelper.safeTransferETH(feeReceiver, feeAmount); if (referralReward > 0) { TransferHelper.safeTransferETH(referee, referralReward); emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward); } } else { TransferHelper.safeTransferFrom(tokenReward, msg.sender, feeReceiver, feeAmount); if (referralReward > 0) { TransferHelper.safeTransferFrom(tokenReward, msg.sender, referee, referralReward); emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward); } } } /// @dev given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function _getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "FloozRouter: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn.mul((9975)); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(10000).add(amountInWithFee); amountOut = numerator / denominator; } /// @dev given an output amount of an asset and pair reserves, returns a required input amount of the other asset function _getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn.mul(amountOut).mul(10000); uint256 denominator = reserveOut.sub(amountOut).mul(9975); amountIn = (numerator / denominator).add(1); } /// @dev performs chained getAmountOut calculations on any number of pairs function _getAmountsOut( address fork, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "FloozRouter: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = _getReserves(fork, path[i], path[i + 1]); amounts[i + 1] = _getAmountOut(amounts[i], reserveIn, reserveOut); } } /// @dev performs chained getAmountIn calculations on any number of pairs function _getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "FloozRouter: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = _getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut); } } /// @dev fetches and sorts the reserves for a pair function _getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = PancakeLibrary.sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IPancakePair(_pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } /// @dev calculates the CREATE2 address for a pair without making any external calls function _pairFor( address factory, address tokenA, address tokenB ) internal view returns (address pair) { (address token0, address token1) = PancakeLibrary.sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), forkInitCode[factory] // init code hash ) ) ) ); } /// @dev lets the admin pause this contract function pause() external onlyOwner { _pause(); } /// @dev lets the admin unpause this contract function unpause() external onlyOwner { _unpause(); } /// @dev allows to receive ETH on the contract receive() external payable {} modifier isValidFork(address factory) { require(forkActivated[factory], "FloozRouter: INVALID_FACTORY"); _; } modifier isValidReferee(address referee) { require(msg.sender != referee, "FloozRouter: SELF_REFERRAL"); _; } } pragma solidity =0.6.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./libraries/TransferHelper.sol"; import "./interfaces/IWETH.sol"; contract FeeReceiverMultichain is Ownable { address public WETH; constructor(address _WETH) public { WETH = _WETH; } /// @dev converts WETH to ETH function unwrapWETH() public { uint256 balance = IWETH(WETH).balanceOf(address(this)); require(balance > 0, "FeeReceiver: Nothing to unwrap"); IWETH(WETH).withdraw(balance); } /// @dev lets the owner withdraw ETH from the contract function withdrawETH(address payable to, uint256 amount) external onlyOwner { to.transfer(amount); } /// @dev lets the owner withdraw any ERC20 Token from the contract function withdrawERC20Token( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /// @dev allows to receive ETH on this contract receive() external payable {} } pragma solidity =0.6.6; import "@openzeppelin/contracts/access/Ownable.sol"; contract ReferralRegistry is Ownable { event ReferralAnchorCreated(address indexed user, address indexed referee); event ReferralAnchorUpdated(address indexed user, address indexed referee); event AnchorManagerUpdated(address account, bool isManager); // stores addresses which are allowed to create new anchors mapping(address => bool) public isAnchorManager; // stores the address that referred a given user mapping(address => address) public referralAnchor; /// @dev create a new referral anchor on the registry /// @param _user address of the user /// @param _referee address wich referred the user function createReferralAnchor(address _user, address _referee) external onlyAnchorManager { require(referralAnchor[_user] == address(0), "ReferralRegistry: ANCHOR_EXISTS"); referralAnchor[_user] = _referee; emit ReferralAnchorCreated(_user, _referee); } /// @dev allows admin to overwrite anchor /// @param _user address of the user /// @param _referee address wich referred the user function updateReferralAnchor(address _user, address _referee) external onlyOwner { referralAnchor[_user] = _referee; emit ReferralAnchorUpdated(_user, _referee); } /// @dev allows admin to grant/remove anchor priviliges /// @param _anchorManager address of the anchor manager /// @param _isManager add or remove privileges function updateAnchorManager(address _anchorManager, bool _isManager) external onlyOwner { isAnchorManager[_anchorManager] = _isManager; emit AnchorManagerUpdated(_anchorManager, _isManager); } function getUserReferee(address _user) external view returns (address) { return referralAnchor[_user]; } function hasUserReferee(address _user) external view returns (bool) { return referralAnchor[_user] != address(0); } modifier onlyAnchorManager() { require(isAnchorManager[msg.sender], "ReferralRegistry: FORBIDDEN"); _; } }
given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function _getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn.mul(amountOut).mul(10000); uint256 denominator = reserveOut.sub(amountOut).mul(9975); amountIn = (numerator / denominator).add(1); }
600,895
./full_match/44787/0x79DC9f411386313e9E684151FEc5A2fb7431ca84/sources/contracts/StarFarm.sol
View function to see pending STARs on frontend.
function pendingStar(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accStarPerShare = pool.accStarPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)).add(pool.extraAmount); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accStarPerShare = accStarPerShare.add(starReward.mul(1e12).div(lpSupply)); } (uint256 _selfGain, ) = starNode.nodeGain(); uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100)); uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100)); uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12).sub(user.rewardDebt); uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12).sub(user.nftRewardDebt); return _amountpendingStar.sub(_nftAmountpendingStar);
13,246,977
./full_match/1/0xdbE5a8BBac5b3ba4e05BB9b9Ca51A6741bc81Bd1/sources/contracts/brokers/BrokersTokenTransferrer.sol
Transfer fee to the brokers. _from User address fees Fees details to be transferred
function _transferFee(address _from, Fees calldata fees) internal { if (fees.brokerAmount > 0) IERC20(fees.token).safeTransferFrom( _from, fees.broker, fees.brokerAmount ); if (fees.platformAmount > 0) IERC20(fees.token).safeTransferFrom( _from, fees.platform, fees.platformAmount ); emit FeeTransferred(_from, fees); }
17,074,784
./full_match/43114/0x9A641E87c60472D90F9A7e2e60e006bE66408B6F/sources/contracts/IsolatedLending.sol
Extinguish debt from payer wallet balance
function _repay( address payer, uint256 trancheId, uint256 repayAmount ) internal virtual { if (repayAmount > 0) { _burnStable(payer, repayAmount); trancheDebt[trancheId] -= repayAmount; } }
4,536,039
// Sources flattened with hardhat v2.8.3 https://hardhat.org // File @openzeppelin/contracts/access/IAccessControl.sol@v4.4.2 // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts/utils/Context.sol@v4.4.2 // 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/utils/Strings.sol@v4.4.2 // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.4.2 // 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@v4.4.2 // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/access/AccessControl.sol@v4.4.2 // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File @openzeppelin/contracts/security/ReentrancyGuard.sol@v4.4.2 // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/interfaces/IBribeVault.sol pragma solidity 0.8.12; interface IBribeVault { function depositBribeERC20( bytes32 bribeIdentifier, bytes32 rewardIdentifier, address token, uint256 amount, address briber ) external; function getBribe(bytes32 bribeIdentifier) external view returns (address token, uint256 amount); function depositBribe( bytes32 bribeIdentifier, bytes32 rewardIdentifier, address briber ) external payable; } // File contracts/BribeBase.sol pragma solidity 0.8.12; contract BribeBase is AccessControl, ReentrancyGuard { address public immutable BRIBE_VAULT; bytes32 public constant TEAM_ROLE = keccak256("TEAM_ROLE"); // Used for generating the bribe and reward identifiers bytes32 public immutable PROTOCOL; // Arbitrary bytes mapped to deadlines mapping(bytes32 => uint256) public proposalDeadlines; // Voter addresses mapped to addresses which will claim rewards on their behalf mapping(address => address) public rewardForwarding; // Tracks whitelisted tokens mapping(address => uint256) public indexOfWhitelistedToken; address[] public allWhitelistedTokens; event GrantTeamRole(address teamMember); event RevokeTeamRole(address teamMember); event SetProposal(bytes32 indexed proposal, uint256 deadline); event DepositBribe( bytes32 indexed proposal, address indexed token, uint256 amount, bytes32 bribeIdentifier, bytes32 rewardIdentifier, address indexed briber ); event SetRewardForwarding(address from, address to); event AddWhitelistTokens(address[] tokens); event RemoveWhitelistTokens(address[] tokens); constructor(address _BRIBE_VAULT, string memory _PROTOCOL) { require(_BRIBE_VAULT != address(0), "Invalid _BRIBE_VAULT"); BRIBE_VAULT = _BRIBE_VAULT; require(bytes(_PROTOCOL).length != 0, "Invalid _PROTOCOL"); PROTOCOL = keccak256(abi.encodePacked(_PROTOCOL)); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); } modifier onlyAuthorized() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(TEAM_ROLE, msg.sender), "Not authorized" ); _; } /** @notice Grant the team role to an address @param teamMember address Address to grant the teamMember role */ function grantTeamRole(address teamMember) external onlyRole(DEFAULT_ADMIN_ROLE) { require(teamMember != address(0), "Invalid teamMember"); _grantRole(TEAM_ROLE, teamMember); emit GrantTeamRole(teamMember); } /** @notice Revoke the team role from an address @param teamMember address Address to revoke the teamMember role */ function revokeTeamRole(address teamMember) external onlyRole(DEFAULT_ADMIN_ROLE) { require(hasRole(TEAM_ROLE, teamMember), "Invalid teamMember"); _revokeRole(TEAM_ROLE, teamMember); emit RevokeTeamRole(teamMember); } /** @notice Return the list of currently whitelisted token addresses */ function getWhitelistedTokens() external view returns (address[] memory) { return allWhitelistedTokens; } /** @notice Return whether the specified token is whitelisted @param token address Token address to be checked */ function isWhitelistedToken(address token) public view returns (bool) { if (allWhitelistedTokens.length == 0) { return false; } return indexOfWhitelistedToken[token] != 0 || allWhitelistedTokens[0] == token; } /** @notice Add whitelist tokens @param tokens address[] Tokens to add to whitelist */ function addWhitelistTokens(address[] calldata tokens) external onlyAuthorized { for (uint256 i; i < tokens.length; ++i) { require(tokens[i] != address(0), "Invalid token"); require(tokens[i] != BRIBE_VAULT, "Cannot whitelist BRIBE_VAULT"); require( !isWhitelistedToken(tokens[i]), "Token already whitelisted" ); // Perform creation op for the unordered key set allWhitelistedTokens.push(tokens[i]); indexOfWhitelistedToken[tokens[i]] = allWhitelistedTokens.length - 1; } emit AddWhitelistTokens(tokens); } /** @notice Remove whitelist tokens @param tokens address[] Tokens to remove from whitelist */ function removeWhitelistTokens(address[] calldata tokens) external onlyAuthorized { for (uint256 i; i < tokens.length; ++i) { require(isWhitelistedToken(tokens[i]), "Token not whitelisted"); // Perform deletion op for the unordered key set // by swapping the affected row to the end/tail of the list uint256 index = indexOfWhitelistedToken[tokens[i]]; address tail = allWhitelistedTokens[ allWhitelistedTokens.length - 1 ]; allWhitelistedTokens[index] = tail; indexOfWhitelistedToken[tail] = index; delete indexOfWhitelistedToken[tokens[i]]; allWhitelistedTokens.pop(); } emit RemoveWhitelistTokens(tokens); } /** @notice Set a single proposal @param proposal bytes32 Proposal @param deadline uint256 Proposal deadline */ function _setProposal(bytes32 proposal, uint256 deadline) internal { require(proposal != bytes32(0), "Invalid proposal"); require(deadline > block.timestamp, "Deadline must be in the future"); proposalDeadlines[proposal] = deadline; emit SetProposal(proposal, deadline); } /** @notice Generate the BribeVault identifier based on a scheme @param proposal bytes32 Proposal @param proposalDeadline uint256 Proposal deadline @param token address Token @return identifier bytes32 BribeVault identifier */ function generateBribeVaultIdentifier( bytes32 proposal, uint256 proposalDeadline, address token ) public view returns (bytes32 identifier) { return keccak256( abi.encodePacked(PROTOCOL, proposal, proposalDeadline, token) ); } /** @notice Generate the reward identifier based on a scheme @param proposalDeadline uint256 Proposal deadline @param token address Token @return identifier bytes32 Reward identifier */ function generateRewardIdentifier(uint256 proposalDeadline, address token) public view returns (bytes32 identifier) { return keccak256(abi.encodePacked(PROTOCOL, proposalDeadline, token)); } /** @notice Get bribe from BribeVault @param proposal bytes32 Proposal @param proposalDeadline uint256 Proposal deadline @param token address Token @return bribeToken address Token address @return bribeAmount address Token amount */ function getBribe( bytes32 proposal, uint256 proposalDeadline, address token ) external view returns (address bribeToken, uint256 bribeAmount) { return IBribeVault(BRIBE_VAULT).getBribe( generateBribeVaultIdentifier(proposal, proposalDeadline, token) ); } /** @notice Deposit bribe for a proposal (ERC20 tokens only) @param proposal bytes32 Proposal @param token address Token @param amount uint256 Token amount */ function depositBribeERC20( bytes32 proposal, address token, uint256 amount ) external nonReentrant { uint256 proposalDeadline = proposalDeadlines[proposal]; require( proposalDeadlines[proposal] > block.timestamp, "Proposal deadline has passed" ); require(token != address(0), "Invalid token"); require(isWhitelistedToken(token), "Token is not whitelisted"); require(amount != 0, "Bribe amount must be greater than 0"); bytes32 bribeIdentifier = generateBribeVaultIdentifier( proposal, proposalDeadline, token ); bytes32 rewardIdentifier = generateRewardIdentifier( proposalDeadline, token ); IBribeVault(BRIBE_VAULT).depositBribeERC20( bribeIdentifier, rewardIdentifier, token, amount, msg.sender ); emit DepositBribe( proposal, token, amount, bribeIdentifier, rewardIdentifier, msg.sender ); } /** @notice Deposit bribe for a proposal (native token only) @param proposal bytes32 Proposal */ function depositBribe(bytes32 proposal) external payable nonReentrant { uint256 proposalDeadline = proposalDeadlines[proposal]; require( proposalDeadlines[proposal] > block.timestamp, "Proposal deadline has passed" ); require(msg.value != 0, "Bribe amount must be greater than 0"); bytes32 bribeIdentifier = generateBribeVaultIdentifier( proposal, proposalDeadline, BRIBE_VAULT ); bytes32 rewardIdentifier = generateRewardIdentifier( proposalDeadline, BRIBE_VAULT ); // NOTE: Native token bribes have BRIBE_VAULT set as the address IBribeVault(BRIBE_VAULT).depositBribe{value: msg.value}( bribeIdentifier, rewardIdentifier, msg.sender ); emit DepositBribe( proposal, BRIBE_VAULT, msg.value, bribeIdentifier, rewardIdentifier, msg.sender ); } /** @notice Voters can opt in or out of reward-forwarding @notice Opt-in: A voter sets another address to forward rewards to @notice Opt-out: A voter sets their own address or the zero address @param to address Account that rewards will be sent to */ function setRewardForwarding(address to) external { rewardForwarding[msg.sender] = to; emit SetRewardForwarding(msg.sender, to); } } // File contracts/RibbonBribe.sol pragma solidity 0.8.12; contract RibbonBribe is BribeBase { address[] public gauges; uint256[] public voteIds; mapping(address => uint256) public indexOfGauge; mapping(uint256 => uint256) public indexOfVoteId; constructor(address _BRIBE_VAULT) BribeBase(_BRIBE_VAULT, "RIBBON_FINANCE") {} /** @notice Set a single proposal for a liquidity gauge @param gauge address Gauge address @param deadline uint256 Proposal deadline */ function setGaugeProposal(address gauge, uint256 deadline) public onlyAuthorized { require(gauge != address(0), "Invalid gauge"); // Add new gauge to list and track index if ( gauges.length == 0 || (indexOfGauge[gauge] == 0 && gauges[0] != gauge) ) { gauges.push(gauge); indexOfGauge[gauge] = gauges.length - 1; } _setProposal(keccak256(abi.encodePacked(gauge)), deadline); } /** @notice Set multiple proposals for many gauges @param gauges_ address[] Gauge addresses @param deadlines uint256[] Proposal deadlines */ function setGaugeProposals( address[] calldata gauges_, uint256[] calldata deadlines ) external onlyAuthorized { uint256 gaugeLen = gauges_.length; require(gaugeLen != 0, "Invalid gauges_"); require(gaugeLen == deadlines.length, "Arrays length mismatch"); for (uint256 i; i < gaugeLen; ++i) { setGaugeProposal(gauges_[i], deadlines[i]); } } /** @notice Set a single proposal for a DAO voting event @param voteId uint256 DAO vote identifier @param deadline uint256 Proposal deadline */ function setDaoProposal(uint256 voteId, uint256 deadline) external onlyAuthorized { // Add the vote id to the list and track it if it's new if ( voteIds.length == 0 || (indexOfVoteId[voteId] == 0 && voteIds[0] != voteId) ) { voteIds.push(voteId); indexOfVoteId[voteId] = voteIds.length - 1; } _setProposal(keccak256(abi.encodePacked(voteId)), deadline); } /** @notice Get list of gauges */ function getGauges() external view returns (address[] memory) { return gauges; } /** @notice Get list of DAO vote identifiers */ function getVoteIds() external view returns (uint256[] memory) { return voteIds; } }
/ Add the vote id to the list and track it if it's new
function setDaoProposal(uint256 voteId, uint256 deadline) external onlyAuthorized { if ( voteIds.length == 0 || (indexOfVoteId[voteId] == 0 && voteIds[0] != voteId) ) { voteIds.push(voteId); indexOfVoteId[voteId] = voteIds.length - 1; } _setProposal(keccak256(abi.encodePacked(voteId)), deadline); }
14,943,363
./full_match/97/0x20610C85207106d89e43335Cf8DDd7C58D6a3b4c/sources/contracts/StrategyRouter.sol
Rebalance strategies, so that their balances will match their weights. return balances Balances of the strategies after rebalancing. Admin function.
function rebalanceStrategies() external onlyOwner returns (uint256[] memory balances) { return StrategyRouterLib.rebalanceStrategies(exchange, strategies); }
3,273,905
pragma solidity ^0.4.23; // File: contracts/grapevine/crowdsale/BurnableTokenInterface.sol /** * @title Burnable Token Interface, defining one single function to burn tokens. * @dev Grapevine Crowdsale **/ contract BurnableTokenInterface { /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public; } // File: contracts/grapevine/crowdsale/GrapevineWhitelistInterface.sol /** * @title Grapevine Whitelist extends the zeppelin Whitelist and adding off-chain signing capabilities. * @dev Grapevine Crowdsale **/ contract GrapevineWhitelistInterface { /** * @dev Function to check if an address is whitelisted or not * @param _address address The address to be checked. */ function whitelist(address _address) view external returns (bool); /** * @dev Handles the off-chain whitelisting. * @param _addr Address of the sender. * @param _sig signed message provided by the sender. */ function handleOffchainWhitelisted(address _addr, bytes _sig) external returns (bool); } // File: contracts/grapevine/crowdsale/TokenTimelockControllerInterface.sol /** * @title TokenTimelock Controller Interface * @dev This contract allows the crowdsale to create locked bonuses and activate the controller. **/ contract TokenTimelockControllerInterface { /** * @dev Function to activate the controller. * It can be called only by the crowdsale address. */ function activate() external; /** * @dev Creates a lock for the provided _beneficiary with the provided amount * The creation can be peformed only if: * - the sender is the address of the crowdsale; * - the _beneficiary and _tokenHolder are valid addresses; * - the _amount is greater than 0 and was appoved by the _tokenHolder prior to the transaction. * The investors will have a lock with a lock period of 6 months. * @param _beneficiary Address that will own the lock. * @param _amount the amount of the locked tokens. * @param _start when the lock should start. * @param _tokenHolder the account that approved the amount for this contract. */ function createInvestorTokenTimeLock( address _beneficiary, uint256 _amount, uint256 _start, address _tokenHolder ) external returns (bool); } // 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 &#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; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: 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/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/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using &#39;super&#39; where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev Withdraw tokens only after crowdsale ends. */ function withdrawTokens() public { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } // File: openzeppelin-solidity/contracts/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/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/utils/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale&#39;s vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts/grapevine/crowdsale/GrapevineCrowdsale.sol /** * @title Grapevine Crowdsale, combining capped, timed, PostDelivery and refundable crowdsales * while being pausable. * @dev Grapevine Crowdsale **/ contract GrapevineCrowdsale is CappedCrowdsale, TimedCrowdsale, Pausable, RefundableCrowdsale, PostDeliveryCrowdsale { using SafeMath for uint256; TokenTimelockControllerInterface public timelockController; GrapevineWhitelistInterface public authorisedInvestors; GrapevineWhitelistInterface public earlyInvestors; mapping(address => uint256) public bonuses; uint256 deliveryTime; uint256 tokensToBeDelivered; /** * @param _timelockController address of the controller managing the bonus token lock * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time * @param _softCap Funding goal * @param _hardCap Max amount of wei to be contributed */ constructor( TokenTimelockControllerInterface _timelockController, GrapevineWhitelistInterface _authorisedInvestors, GrapevineWhitelistInterface _earlyInvestors, uint256 _rate, address _wallet, ERC20 _token, uint256 _openingTime, uint256 _closingTime, uint256 _softCap, uint256 _hardCap) Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_hardCap) TimedCrowdsale(_openingTime, _closingTime) RefundableCrowdsale(_softCap) public { timelockController = _timelockController; authorisedInvestors = _authorisedInvestors; earlyInvestors = _earlyInvestors; // token delivery starts 5 days after the crowdsale ends. //deliveryTime = _closingTime.add(60*60*24*5); deliveryTime = _closingTime.add(60*5); } /** * @dev low level token purchase * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary, bytes _whitelistSign) public payable { // since the earlyInvestors are by definition autorised, we check first the earlyInvestors. if (!earlyInvestors.handleOffchainWhitelisted(_beneficiary, _whitelistSign)) { authorisedInvestors.handleOffchainWhitelisted(_beneficiary, _whitelistSign); } super.buyTokens(_beneficiary); } /** * @dev Withdraw tokens only after the deliveryTime. */ function withdrawTokens() public { require(goalReached()); // solium-disable-next-line security/no-block-members require(block.timestamp > deliveryTime); super.withdrawTokens(); uint256 _bonusTokens = bonuses[msg.sender]; if (_bonusTokens > 0) { bonuses[msg.sender] = 0; require(token.approve(address(timelockController), _bonusTokens)); require( timelockController.createInvestorTokenTimeLock( msg.sender, _bonusTokens, deliveryTime, this ) ); } } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * It computes the bonus and store it using the timelockController. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { uint256 _totalTokens = _tokenAmount; // solium-disable-next-line security/no-block-members uint256 _bonus = getBonus(block.timestamp, _beneficiary, msg.value); if (_bonus>0) { uint256 _bonusTokens = _tokenAmount.mul(_bonus).div(100); // make sure the crowdsale contract has enough tokens to transfer the purchased tokens and to create the timelock bonus. uint256 _currentBalance = token.balanceOf(this); require(_currentBalance >= _totalTokens.add(_bonusTokens)); bonuses[_beneficiary] = bonuses[_beneficiary].add(_bonusTokens); _totalTokens = _totalTokens.add(_bonusTokens); } tokensToBeDelivered = tokensToBeDelivered.add(_totalTokens); super._processPurchase(_beneficiary, _tokenAmount); } /** * @dev Validation of an incoming purchase. Allowas purchases only when crowdsale is not paused and the _beneficiary is authorized to buy. * The early investors went through the KYC process, so they are authorised by default. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { require(authorisedInvestors.whitelist(_beneficiary) || earlyInvestors.whitelist(_beneficiary)); super._preValidatePurchase(_beneficiary, _weiAmount); } /** * @dev Computes the bonus. The bonus is * - 0 by default * - 30% before reaching the softCap for those whitelisted. * - 15% the first week * - 10% the second week * - 8% the third week * - 6% the remaining time. * @param _time when the purchased happened. * @param _beneficiary Address performing the token purchase. * @param _value Value in wei involved in the purchase. */ function getBonus(uint256 _time, address _beneficiary, uint256 _value) view internal returns (uint256 _bonus) { //default bonus is 0. _bonus = 0; // at this level the amount was added to weiRaised if ( (weiRaised.sub(_value) < goal) && earlyInvestors.whitelist(_beneficiary) ) { _bonus = 30; } else { if (_time < openingTime.add(7 days)) { _bonus = 15; } else if (_time < openingTime.add(14 days)) { _bonus = 10; } else if (_time < openingTime.add(21 days)) { _bonus = 8; } else { _bonus = 6; } } return _bonus; } /** * @dev Performs the finalization tasks: * - if goal reached, activate the controller and burn the remaining tokens * - transfer the ownership of the token contract back to the owner. */ function finalization() internal { // only when the goal is reached we burn the tokens and activate the controller. if (goalReached()) { // activate the controller to enable the investors and team members // to claim their tokens when the time comes. timelockController.activate(); // calculate the quantity of tokens to be burnt. The bonuses are already transfered to the Controller. uint256 balance = token.balanceOf(this); uint256 remainingTokens = balance.sub(tokensToBeDelivered); if (remainingTokens>0) { BurnableTokenInterface(address(token)).burn(remainingTokens); } } Ownable(address(token)).transferOwnership(owner); super.finalization(); } }
Computes the bonus. The bonus is - 0 by default - 30% before reaching the softCap for those whitelisted. - 15% the first week - 10% the second week - 8% the third week - 6% the remaining time. _time when the purchased happened. _beneficiary Address performing the token purchase. _value Value in wei involved in the purchase./default bonus is 0. at this level the amount was added to weiRaised
function getBonus(uint256 _time, address _beneficiary, uint256 _value) view internal returns (uint256 _bonus) { _bonus = 0; if ( (weiRaised.sub(_value) < goal) && earlyInvestors.whitelist(_beneficiary) ) { _bonus = 30; if (_time < openingTime.add(7 days)) { _bonus = 15; _bonus = 10; _bonus = 8; _bonus = 6; } } return _bonus; }
2,370,953
./full_match/1/0x90513700BdccAc963FCbBa2D60CDD002ae0D4817/sources/contracts/UPGRD/Sale.sol
Returns token amount and left over wei amount for given wei amount If there is not enough tokens left, return all tokens left
function getTokensForEthAmount(uint256 weiAmount) public view returns (uint256, uint256) { if (weiAmount == 0) revert InsufficientAmount(weiAmount); uint256 tokens = (weiAmount / meta.price) * 10 ** 18; uint256 left = meta.supply - meta.sold; if(tokens > left) tokens = left; uint256 cost = tokens * meta.price / 10 ** 18; weiAmount -= cost; return (tokens, weiAmount); }
16,509,755
./partial_match/1/0x74C37294407a48Ee3Fb813b80Fc346b1F6E5dB2C/sources/BLASTAR.sol
force Swap back if slippage issues.
function makeManualSwapBack() external onlyOwner { require(balanceOf(address(this)) >= swapTokensAtAmount, "Can only swap when token amount is at or higher than restriction"); swapping = true; swapBack(); swapping = false; emit OwnerForcedSwapBack(block.timestamp); }
2,754,519
// SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.22 <0.9.0; import "../../libs/SafeMath.sol"; import "../../common/IdentityRegistry.sol"; //import "../../common/Token.sol"; import "../../common/IERC20TOKEN.sol"; import "../../common/Whitelistable.sol"; abstract contract DelawareStockToken is IERC20TOKEN, Whitelistable { string public symbol; string public name; string public byLawsHash; uint public decimals; bool public isPrivateCompany = true; uint256 _totalSupply; mapping(address => uint) tokenOwnersIndex; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) private _allowances; address[] public tokenOwners; IdentityRegistry public platformWhitelist; event ChangedCompanyStatus(address authorizedBy, bool newStatus); constructor(string memory _symbol, string memory _name, uint _supply, string memory _hash, address payable _registry) Whitelistable() { symbol = _symbol; name = _name; _totalSupply = _supply; byLawsHash = _hash; balances[msg.sender] = _supply; platformWhitelist = IdentityRegistry(_registry); tokenOwners.push(address(0)); tokenOwners.push(msg.sender); uint index = tokenOwners.length; tokenOwnersIndex[msg.sender] = index - 1; } modifier onlyIfWhitelisted(address _address) { // modifier to restrict access only to whitelisted accounts require(platformWhitelist.isWhitelisted(_address)); if(isPrivateCompany){ require(isWhitelisted(_address), "Address not in private shareholders whitelist"); } _; } function transfer(address _to, uint256 _value) onlyIfWhitelisted(_to) public virtual override returns (bool){ uint index = 0; if(tokenOwnersIndex[_to] == 0) { tokenOwners.push(_to); index = tokenOwners.length - 1; tokenOwnersIndex[_to] = index; } _transfer(msg.sender, _to, _value); if(balanceOf(msg.sender) == 0){ removeTokenOwner(msg.sender); } return true; } function togglePrivateCompany() okOwner() public { isPrivateCompany = !isPrivateCompany; emit ChangedCompanyStatus(msg.sender, isPrivateCompany); } // Return the number of shareholders in the company function ownersCount() public view returns(uint){ return tokenOwners.length - 1; } // Return an array with all the token owners function getTokenOwners() public view returns(address[] memory){ return tokenOwners; } // Removes entry from array at index and resizes the array appropriatly function removeFromTokenOwnersArray(uint index) internal { address lastElement = tokenOwners[tokenOwners.length - 1]; tokenOwners[index] = lastElement; delete tokenOwners[tokenOwners.length - 1]; } function totalSupply() virtual public override view returns (uint) { return _totalSupply; } function setTotalSupply(uint256 amount) public { _totalSupply = amount; } // Removes a token owner from the list of shareholders function removeTokenOwner(address holder) internal { uint i = tokenOwnersIndex[holder]; removeFromTokenOwnersArray(i); tokenOwnersIndex[holder] = 0; } 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) { address owner = msg.sender; _approve(owner, spender, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = msg.sender; _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = msg.sender; _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = msg.sender; uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { balances[from] = fromBalance - amount; } balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
Return an array with all the token owners
function getTokenOwners() public view returns(address[] memory){ return tokenOwners; }
12,787,630
/* * Offer to respond to a proposal. */ contract Offer { /* * The seller who made this offer. */ address public owner; /* * Price offered at the minimum amount. */ uint public price; /* * Minimum amount of products to be bought. */ uint public minimumAmount; /* * Card ID used for payouts */ string public cardId; function setPrice(uint p){ if(tx.origin != owner) return; price = p; } function setMinimumAmount(uint a){ if(tx.origin != owner) return; minimumAmount = a; } function setCardId(string cId){ if(tx.origin != owner) return; cardId = cId; } function Offer(uint p, uint ma, string cId) { owner = tx.origin; price = p; minimumAmount = ma; cardId = cId; } } /* * A sungle buying proposal. */ contract Proposal { /* * Reference to the registry that this proposal is part of, to check the owner. */ ProposalRegistry public registry; /* * Name of the product to be bought. */ string public productName; /* * A description of the product that is unambiguous to all the stakeholders. */ string public productDescription; /* * The SKU (unique identification number) of the product. */ string public productSku; /* * Description of the indivisible unit size. E.g. "box of 12 cans". */ string public productUnitSize; /* * The product category in plain text. Future vevrsions might contain a more * advanced taxonomy of categories. */ string public mainCategory; /* * The product category in plain text. Future vevrsions might contain a more * advanced taxonomy of categories. */ string public subCategory; /* * Maximum price the buyers are willing to pay. */ uint public maxPrice; /* * Date after which this proposal is terminated. It can be terminated by * accepting a valid offer, or */ string public endDate; /* * Ultimate date when the products should be delivered to the buyers. */ string public ultimateDeliveryDate; // COULD DO: make it a contract of its own, so it can have functions. However // the getXXXamount functions still need to live in the Proposal because it // has the percentages. Unless we give the Backing contract a reference of // course... struct Backing { /* * Blockchain address of the buyer */ address buyerAddress; /* * Amount of products the buyer has committed to buy.s */ // TODO: rename to "count". "amount" is reserved for amounts of money. uint amount; /* * Transaction ID of the pledge payment (before closing a deal). * Transaction ID's currently are always 32 bytes. Therefore we * could change them to bytes32. That would allow string compare. * However there's no current need and it would require some code * changes. So sticking with string for now. */ string pledgePaymentTransactionID; /* * Amount of the pledge payment. */ uint pledgePaymentAmount; /* * Transaction ID of the initial payment (at moment of backing). */ string startPaymentTransactionID; /* * Amount of initial payment. */ uint startPaymentAmount; /* * Transaction ID of the final payment (after deliery). */ string endPaymentTransactionID; /* * Amount of the final payment. */ int endPaymentAmount; /* * Indicates whether the delivery has been reported by the backer. */ bool isDeliveryReported; /* * Indicates whether the delivery is correct according to the backer. * Any further details about the nature of what is or isn't correct * are discussed outside of the contract. */ bool isDeliveryCorrect; /* * Uphold card ID used for payments. */ string cardId; } /* * Prospective buyers backing this proposal. */ mapping(uint => Backing) public backers; uint public backerIndex; /* * Prospective buyers backing this proposal. */ mapping(uint => Offer) public offers; uint public offerIndex; /* * Index to help access the backer mapping. */ mapping(address => uint) public offerIndexByAddress; /* * Returns whether the proposal has been closed. */ bool public isClosed; /* * The offer that has been accepted. */ Offer public acceptedOffer; address public owner; function Proposal(string pn, string mc, string sc, uint mp, string ed, string udd) { productName = pn; mainCategory = mc; subCategory = sc; maxPrice = mp; endDate = ed; ultimateDeliveryDate = udd; owner = tx.origin; registry = ProposalRegistry(msg.sender); } function setDetails(string pd, string ps, string pus) { // Only to be called by the proposal owner. if(tx.origin != owner) return; productDescription = pd; productSku = ps; productUnitSize = pus; } // Payment schedule, currently fixed. uint public pledgePaymentPercentage = 5; uint public startPaymentPercentage = 45; // End payment percentage: there's no such thing. The end payment is the rest. // In case of an offer below pledge + start, it can even be a reimbursement. function getBestPrice() constant returns (uint price) { uint bestOfferIndex = getBestOfferIndex(); // Is there a best offer? if(bestOfferIndex == 0) return; price = offers[bestOfferIndex].price(); } function getPledgePaymentAmount(uint backerIndex) constant returns (uint amount) { amount = backers[backerIndex].amount * pledgePaymentPercentage * maxPrice / 100; // For very low prices: force a very low amount. Settled in end payment. if (amount == 0) amount = 1; } function getStartPaymentAmount(uint backerIndex) constant returns (uint amount) { amount = backers[backerIndex].amount * startPaymentPercentage * maxPrice / 100; // For very low prices: force a very low amount. Settled in end payment. if (amount == 0) amount = 1; } function getEndPaymentAmount(uint backerIndex) constant returns (int amount) { // The end payment amount is "the rest". // In case of an offer below pledge + start, it can even be a reimbursement, hence // a negative amount. // We can only compute this once there is an accepted offer. However when // there is none, the end payment will be minus the currently paid amount, // hence a full reimbursement. amount = (int(backers[backerIndex].amount) * int(acceptedOffer.price())) // Total amount to be paid // Minus the amount already paid by this backer. We use the // actually registered amounts to handle any cases where e.g. // a single backer hasn't paid the start payment. - int(backers[backerIndex].pledgePaymentAmount) - int(backers[backerIndex].startPaymentAmount); } /* * Back the proposal, i.e. pledge to buy a certain amount. */ function back(uint am, string cardId) { if(am == 0) return; // No backing after closing. if(isClosed) return; // No checks on multiple backings per buyer. Buyers can buy more later (not less). backerIndex++; backers[backerIndex].amount = am; backers[backerIndex].buyerAddress = tx.origin; backers[backerIndex].cardId = cardId; } /* * Register a payment for a backer. To be called by the registry owner. The * call should only be made after the payment has been verified as having * the correct amount, source and destination. * * @param backerIndex the backer index * @param paymentType 1=pledge, 2=start, 3=end * @param transactionID the external transaction ID of the payment * @param amount the payment amount */ function setPaid(uint backerIndex, uint paymentType, string transactionID, int amount) { // The registry owner is the trusted party to confirm payments. if(tx.origin != registry.owner()) return; // Validate this is an existing backer. // Ideally we would want to verify this from the original backer address. // The backer could send a transaction claiming they paid a certain backing // (checking the address), and then the registry administrator can confirm // this, also checking that the tx ID corresponds to a tx of the right amount // that has been sent to the right address. // So then this would be split into: // - claimPaid(uint backerIndex, uint paymentType, string transactionID, int amount) // -> to be called by the backer // - confirmPaid(uint backerIndex, uint paymentType, string transactionID, int amount) // -> to be called by the registry admin. Or in future cases, by a set of oracles. // - or denyPaid(uint backerIndex, uint paymentType), to be called by the admin/oracles, // leading to a reversion. Could also be used to correct incorrect calls. if(backerIndex == 0) return; Backing b = backers[backerIndex]; if (paymentType == 1) { // Pledge payment // Can only register once if(b.pledgePaymentAmount != 0) return; // Validate correct amount if(amount != int(getPledgePaymentAmount(backerIndex))) return; b.pledgePaymentTransactionID = transactionID; b.pledgePaymentAmount = uint(amount); } else if (paymentType == 2) { // Start payment // Validate that the BuyCo was closed if(!isClosed) return; // Can only register once if(b.startPaymentAmount != 0) return; // There should be an accepted offer. If not, the pledge payments // should be refunded. if(address(acceptedOffer) == 0x0) return; // Validate pledge payment if(b.pledgePaymentAmount == 0) return; if(amount != int(getStartPaymentAmount(backerIndex))) return; b.startPaymentTransactionID = transactionID; b.startPaymentAmount = uint(amount); } else if (paymentType == 3) { // End payment // Validate that start payment was registered if(b.startPaymentAmount == 0) return; // Can only register once if(b.endPaymentAmount != 0) return; // Validate correct amount if(amount != getEndPaymentAmount(backerIndex)) return; b.endPaymentTransactionID = transactionID; b.endPaymentAmount = amount; } } /* * Make an offer */ function offer(uint price, uint minimumAmount, string cardId) returns (Offer o){ // No free offers allowed. Also for safety purposes (empty might end up as 0). if(price == 0) return; if(price > maxPrice) return; if(minimumAmount == 0) return; if(isClosed) return; // Check for an existing offer of this seller if(offerIndexByAddress[tx.origin] > 0) { // Because this is a related contract, we can't set public properties. // TODO: check if there are default setters, maybe set_price() or similar? offers[offerIndexByAddress[tx.origin]].setPrice(price); offers[offerIndexByAddress[tx.origin]].setMinimumAmount(minimumAmount); offers[offerIndexByAddress[tx.origin]].setCardId(cardId); return; } offerIndex++; offerIndexByAddress[tx.origin] = offerIndex; o = new Offer(price, minimumAmount, cardId); offers[offerIndex] = o; return o; } /* * Cancel the offer of a seller if the proposal is still open. */ function cancelOffer(){ // TODO } function getTotalBackedAmount() constant returns (uint amount){ for (uint i = 1; i <= backerIndex; i++) { var b = backers[i]; // Only count backers that have paid the pledge payment. if(b.pledgePaymentAmount == 0) continue; amount += b.amount; } return amount; } function getBestOfferIndex() constant returns (uint bestOfferIndex) { uint totalBackedAmount = getTotalBackedAmount(); uint lowestPrice = maxPrice; // Find the matching offer with the best price. for (uint i = 1; i <= offerIndex; i++) { var o = offers[i]; if (o.price() <= lowestPrice && o.minimumAmount() <= totalBackedAmount) { // This is a better offer than previously found. bestOfferIndex = i; } } } /* * Attempt to close the proposal if the closing conditions are met: * - the end date has been reached (this can not be checked yet) * - a valid offer has been made */ function close() { // To be called by the registry owner. if(tx.origin != registry.owner()) return; // Checking whether the end time is the responsibility of the registry // owner. We currently have no way to deal with time within the contract. // The proposal gets closed no matter whether there's a valid offer or // not. // Get the best offer. uint bestOfferIndex = getBestOfferIndex(); // Did we find a valid offer? if (bestOfferIndex > 0) { acceptedOffer = offers[bestOfferIndex]; } isClosed = true; } /* * Returns whether all the start (and pledge) payments have been received * from the backers. */ function isStartPaymentComplete() constant public returns (bool isComplete) { // No backers? Then not complete. if(getTotalBackedAmount() == 0) return; for (uint i = 1; i <= backerIndex; i++) { // Only consider real backers. if(backers[i].pledgePaymentAmount == 0) continue; if(backers[i].startPaymentAmount == 0) return; } isComplete = true; } /* * Returns whether all the payments have been received from the backers. */ function isPaymentComplete() constant public returns (bool isComplete) { // Start payment not complete? Then end payment surely not complete. if(!isStartPaymentComplete()) return; for (uint i = 1; i <= backerIndex; i++) { // Only consider real backers. if(backers[i].pledgePaymentAmount == 0) continue; if(backers[i].endPaymentAmount == 0) return; } isComplete = true; } /* * Report on the delivery of the goods. To be called by the backer. */ function reportDelivery(uint backerIndex, bool isCorrect) { Backing b = backers[backerIndex]; // There has to be an accepted offer to report any delivery. if(address(acceptedOffer) == 0x0) return; // To be called by the backer. if(b.buyerAddress != tx.origin) return; // Is it a real backer? if(b.pledgePaymentAmount == 0) return; // A delivery reported as correct cannot be unreported. if(b.isDeliveryReported && b.isDeliveryCorrect) return; b.isDeliveryReported = true; b.isDeliveryCorrect = isCorrect; } /* * The minimum percentage of deliveries reported as correct (calculated by * product count) to consider the delivery complete and ready for final * payout. In future versions this could be a parameter of the proposal. */ uint public minimumReportedCorrectDeliveryPercentage = 50; function getMinimumCorrectDeliveryCount() constant returns (uint count) { count = minimumReportedCorrectDeliveryPercentage * getTotalBackedAmount() / 100; } /* * Returns the total count of products that have been reported as correctly * delivered. */ function getCorrectDeliveryCount() constant returns (uint count) { for (uint i = 1; i <= backerIndex; i++) { if(backers[i].isDeliveryCorrect) count += backers[i].amount; } } /* * Returns whether delivery is complete according to the agreed upon * treshold. */ function isDeliveryComplete() constant returns (bool isComplete) { isComplete = getCorrectDeliveryCount() >= getMinimumCorrectDeliveryCount(); } // Payments to the seller uint public startPayoutAmount; string public startPayoutTransactionID; uint public endPayoutAmount; string public endPayoutTransactionID; /* * Returns whether the start payout to the seller may be done. */ function isReadyForStartPayout() constant returns (bool isReady) { isReady = isClosed && isStartPaymentComplete(); } /* * Returns whether the start payout to the seller may be done. */ function isReadyForEndPayout() constant returns (bool isReady) { isReady = isClosed && isPaymentComplete() && isDeliveryComplete() // Start payout has to be done before end payout. && startPayoutAmount != 0; } function getStartPayoutAmount() constant returns (uint amount) { amount = acceptedOffer.price() * getTotalBackedAmount() * (pledgePaymentPercentage + startPaymentPercentage) / 100; } function getEndPayoutAmount() constant returns (uint amount) { // TODO: Handle refunds. If the ultimateDeliveryDate has passed, there // can be two situations: // 1. isDeliveryComplete == true: end payment should be made to seller // 2. isDeliveryComplete == false: end payout should be negative (refund) // and end payment to backers should be negative (refund). // Currently refunds are not supported; any BuyCo is assumed to be // successfully fulfilled within the ultimateDeliveryDate. amount = acceptedOffer.price() * getTotalBackedAmount() - getStartPayoutAmount(); } /* * Confirm that the start payout sum has been paid to the accepted seller. */ function registerStartPayout(string txId, uint amount) { // Payments are confirmed by the registry owner. if(tx.origin != registry.owner()) return; // Can only register once if(startPayoutAmount != 0) return; if(!isReadyForStartPayout()) return; if(amount != getStartPayoutAmount()) return; startPayoutAmount = amount; startPayoutTransactionID = txId; } /* * Confirm thath the end payout sum has been paid to the accepted seller. */ function registerEndPayout(string txId, uint amount) { // Payments are confirmed by the registry owner. if(tx.origin != registry.owner()) return; // Can only register once if(endPayoutAmount != 0) return; if(!isReadyForEndPayout()) return; if(amount != getEndPayoutAmount()) return; endPayoutAmount = amount; endPayoutTransactionID = txId; } /**************** START STATISTICS **************/ /* * Gets the total amount deposited by backers. */ function getTotalPaymentAmount() constant returns (uint amount) { int computedAmount; for (uint i = 1; i <= backerIndex; i++) { var b = backers[i]; computedAmount += int(b.pledgePaymentAmount); computedAmount += int(b.startPaymentAmount); computedAmount += b.endPaymentAmount; } amount = uint(computedAmount); } /** * Gets the total amount paid out to the seller. */ function getTotalPayoutAmount() constant returns (uint amount) { amount = startPayoutAmount + endPayoutAmount; } /** * Gets the total amount currently held in escrow. */ function getTotalEscrowAmount() constant returns (uint amount) { return getTotalPaymentAmount() - getTotalPayoutAmount(); } /**************** END STATISTICS **************/ } /* * Central registry for buyng proposals. This contract is deployed once. The * contract instance corresponds to one BuyCo service. */ contract ProposalRegistry { /* * Name of the registry, e.g. "BuyCo" */ string public name; /* * The owner of the registry, e.g. BuyCo Ltd */ address public owner; /* * Version of the regstriy for simple version checking. The code is currently * compatible with only a single version of the contracts. After any change, * this number should be increased. The code compares it with a variable in * contractInterfaces. */ string public version = "0.8.6"; function ProposalRegistry(string n){ name = n; owner = tx.origin; } /* * All current and historical proposals. */ mapping (uint=>Proposal) public proposals; uint public proposalIndex; function addProposal(string productName, string productCategory, string productSubCategory, uint maxPrice, string endDate, string ultimateDeliveryDate) returns (Proposal p) { proposalIndex++; p = new Proposal(productName, productCategory, productSubCategory, maxPrice, endDate, ultimateDeliveryDate); proposals[proposalIndex] = p; return p; } }
For very low prices: force a very low amount. Settled in end payment.
function getPledgePaymentAmount(uint backerIndex) constant returns (uint amount) { amount = backers[backerIndex].amount * pledgePaymentPercentage * maxPrice / 100; if (amount == 0) amount = 1; }
14,070,252
./full_match/8453/0x0972892bDa852a6A8C2346Bc552f7782E22D55a9/sources/contracts/providers/TokenVault.sol
getTokenTypes Given a specific key, will return the contract addresses for all ERC20s held in the vault. keyId the key you are using to access the trust return the token registry for that trust/ I really should be taking the arns from the ledger and recoding it to get the contract addresses, but for 20-30 arns thats going to be an expensive call.
function getTokenTypes(uint256 keyId) external view returns(address[] memory) { (,,uint256 trustId,,) = locksmith.inspectKey(keyId); return witnessedTokenAddresses[trustId].values(); }
11,550,911
pragma solidity ^0.5.0; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; /// @Author RickGriff /// EtherSplit dApp contract AgreementFactory { address public factoryOwner; mapping(address => bool) public allAgreements; /// Map user to list of agreements they've created or joined mapping(address => address[]) public userToAgreements; /// Map user to list of agreements they've been invited to mapping(address => address[]) public userToInvites; event AgreementCreated (address from, address agreementAddr); event AgreementAdded (address agreementAddr, bool inAllAgreementsList); constructor() public { factoryOwner = msg.sender; } function createNewAgreement() public { Agreement newAgreement = new Agreement(msg.sender); /// Add agreement addr to allAgreements and user's list address agreementAddress = address(newAgreement); allAgreements[agreementAddress] = true; userToAgreements[msg.sender].push(agreementAddress); emit AgreementCreated(msg.sender, agreementAddress); emit AgreementAdded(agreementAddress, allAgreements[agreementAddress]); } function getUsersAgreements(address _user) public view returns (address[] memory ) { return( userToAgreements[_user] ); } function getMyAgreements() public view returns (address[] memory ) { return( userToAgreements[msg.sender] ); } function getMyInvites() public view returns (address[] memory ) { return( userToInvites[msg.sender] ); } /// Called by a child Agreement when a new user registers on the child. function newRegisteredUser(address _user) public _onlyChildContract { userToAgreements[_user].push(msg.sender); } /// Called by a child Agreement when a new account is invited to the child. function newInvite(address _friend) public _onlyChildContract { userToInvites[_friend].push(msg.sender); } /// Length getters and modifiers function getMyAgreementsCount() public view returns(uint myAgreementsCount) { return userToAgreements[msg.sender].length; } function getMyInvitesCount() public view returns(uint myAgreementsCount) { return userToInvites[msg.sender].length; } function getUsersAgreementsCount(address _user) public view returns(uint usersAgreementsCount) { return userToAgreements[_user].length; } modifier _onlyChildContract { require( allAgreements[msg.sender] == true, 'Sending contract not listed as a child of AgreementFactory'); _; } } contract Agreement { using SafeMath for uint; address public parentFactory; address public parentFactoryOwner; address public user_1; address public invited_friend; address public user_2; string public user_1_name; string public user_2_name; /* The net balance of who owes who, in pennies. Positive if user_2 owes more, negative if user_1 owes more. */ int public balance; uint public txCounter = 0; mapping (uint => Tx) public pendingTxs1; /// Transactions pending confirmation from user_1 uint[] public pendingTxsList1; /// unordered list of user_1's pending Tx IDs mapping (uint => Tx) public pendingTxs2; uint[] public pendingTxsList2; mapping (uint => Tx) public confirmedTxs; uint[] public confirmedTxsList; /// Basic transaction object struct Tx { uint amount; bool split; address creator; address confirmer; address debtor; string description; uint id; uint timestamp; uint index; } /// ****** Constructor and user registration functions ****** constructor(address _creator) public { parentFactory = msg.sender; AgreementFactory factory = AgreementFactory(parentFactory); parentFactoryOwner = factory.factoryOwner(); user_1 = _creator; } event logNewPendingTx (uint id, uint listIndex, uint amount, address creator); event logDeletedTx (uint id, uint listIndex, uint amount, address creator); function setName(string memory _name) onlyUser public { if (msg.sender == user_1) { require(bytes(user_1_name).length == 0, "You already set your name!"); user_1_name = _name; } else if (msg.sender == user_2) { require(bytes(user_2_name).length == 0, "You already set your name!"); user_2_name = _name; } } /// Set the invited friend's address function inviteFriend(address _friend) onlyUser1 onlyUser2NotRegistered public { require(_friend != msg.sender, 'You cant invite yourself!'); require(invited_friend == address(0), 'You have already invited someone!'); invited_friend = _friend; AgreementFactory factory = AgreementFactory(parentFactory); factory.newInvite(_friend); } function registerUser2() onlyInvitedFriend onlyUser2NotRegistered public { user_2 = msg.sender; require(user_2 == msg.sender); /// check user_2 was set /// send the registration data to parent factory AgreementFactory factory = AgreementFactory(parentFactory); factory.newRegisteredUser(user_2); } /// ****** Functions for creating and confirming transactions ****** /// Create a pending Tx, to be confirmed by the other user function createPending(uint _amount, bool _split, address _debtor, string memory _description) onlyUser onlyBothRegistered public { require( _debtor == user_1 || _debtor == user_2, 'debtor must be a registered user' ); require( bytes(_description).length < 35, 'Description too long' ); txCounter = txCounter.add(1); /* since Solidity dislikes initialization inside conditionals, initialize list & mapping for msg.sender == user_1, and reassign if msg.sender == user_2. */ uint[] storage pendingTxsList = pendingTxsList2; mapping (uint => Tx) storage pendingTxs = pendingTxs2; if (msg.sender == user_2) { pendingTxsList = pendingTxsList1; pendingTxs = pendingTxs1; } uint timeNow = timeStamp(); Tx memory newPendingTx; newPendingTx.confirmer = getOtherUser(msg.sender); /// If Tx cost was split, set the amounted owed to half of Tx amount if (_split == true) { newPendingTx.amount = _amount / 2; } else if(_split == false) { newPendingTx.amount = _amount; } /// set remaining Tx struct attributes newPendingTx.split = _split; newPendingTx.creator = msg.sender; newPendingTx.debtor = _debtor; newPendingTx.description = _description; newPendingTx.id = txCounter; newPendingTx.timestamp = timeNow; // push the Tx ID to the list - and assign the corresponding list index to the Tx.index property newPendingTx.index = pendingTxsList.push(newPendingTx.id) - 1; /// insert new Tx to the confirmer's pending Tx mapping pendingTxs[txCounter] = newPendingTx; emit logNewPendingTx(newPendingTx.id, newPendingTx.index, newPendingTx.amount, newPendingTx.creator); } function userDeletePendingTx(uint _id) onlyUser onlyBothRegistered public returns(uint) { /// grab *other* user's pending Txs, and check that msg.sender created it mapping (uint => Tx) storage pendingTxs = pendingTxs2; if (msg.sender == user_2) { pendingTxs = pendingTxs1; } require(msg.sender == pendingTxs[_id].creator, "a user can only delete a pending tx they created" ); address otherUser = getOtherUser(msg.sender); return deletePendingTx(_id, otherUser); // returns id of deleted Tx } function confirmAll() onlyUser onlyBothRegistered public { int balanceChange; uint[] storage pendingTxsList = pendingTxsList1; mapping (uint => Tx) storage pendingTxs = pendingTxs1; if (msg.sender == user_2) { pendingTxsList = pendingTxsList2; pendingTxs = pendingTxs2; } for (uint i = 0; i < pendingTxsList.length; i++) { uint id = pendingTxsList[i]; require(!isConfirmedTx(id), "Tx is already confirmed"); confirmedTxs[id] = pendingTxs[id]; /// insert tx to mapping confirmedTxsList.push(id); /// append tx id to list balanceChange = balanceChange + changeInBalance(pendingTxs[id]); } pendingTxsList.length = 0; balance = balance + balanceChange; } function confirmSingleTx(uint _id) onlyUser onlyBothRegistered public { mapping (uint => Tx) storage pendingTxs = pendingTxs1; if (msg.sender == user_2) { pendingTxs = pendingTxs2; } require(msg.sender == pendingTxs[_id].confirmer, "User can only confirm their own pending Txs" ); require(getOtherUser(msg.sender) == pendingTxs[_id].creator, "User can only confirm pending Txs created by other user " ); Tx memory transaction = pendingTxs[_id]; deletePendingTx(_id, msg.sender); /// Remove tx ID from user's pendingTx list /// Update confirmedTx mapping and ID list require(!isConfirmedTx(_id), "Tx is already confirmed"); confirmedTxs[_id] = transaction; confirmedTxsList.push(_id); balance = balance + changeInBalance(transaction); } /** Calculates balance from scratch from total confirmed Tx history, * and checks it is equal to running balance. */ function balanceHealthCheck() onlyUserOrFactoryOwner public view returns (int _testBal, int _bal, bool) { int testBalance = 0; for (uint i = 0; i < confirmedTxsList.length; i++) { uint tx_id = confirmedTxsList[i]; testBalance = testBalance + changeInBalance(confirmedTxs[tx_id]); } if (testBalance != balance) { return(testBalance, balance, false); } else if (testBalance == balance) { return(testBalance, balance, true); } } /// ****** Helper and getter functions ****** function deletePendingTx (uint _id, address _user) private returns (uint) { require (_user == user_1 || _user == user_2, "deletePendingTx must receive either user_1 or user_2"); uint[] storage pendingTxsList = pendingTxsList2; mapping (uint => Tx) storage pendingTxs = pendingTxs2; if (_user == user_1) { pendingTxsList = pendingTxsList1; pendingTxs = pendingTxs1; require(isPendingTx1(_id), "Tx ID is not in user_1's pending Tx list"); } else if (_user == user_2) { pendingTxsList = pendingTxsList2; pendingTxs = pendingTxs2; require(isPendingTx2(_id), "Tx ID is not in user_2's pending Tx list"); } /* delete the pendingTx from the list. We dont need to remove the mapping - the list of tx IDs is what determines existence. This approach preserves array length, but not order. */ uint indexToDelete = pendingTxs[_id].index; uint txIDToMove = pendingTxsList[pendingTxsList.length - 1]; // grab the last tx in list pendingTxsList[indexToDelete] = txIDToMove; /// move last tx to emtpy slot, replacing the deleted one pendingTxs[txIDToMove].index = indexToDelete; /// in the mapping, update the index pointer of the tx that moved pendingTxsList.length--; emit logDeletedTx(_id, indexToDelete, pendingTxs[_id].amount, pendingTxs[_id].creator ); return indexToDelete; } function isPendingTx1(uint _id) public view returns(bool isIndeed) { if(pendingTxsList1.length == 0) return false; return (pendingTxsList1[pendingTxs1[_id].index] == _id); } function isPendingTx2(uint _id) public view returns(bool isIndeed) { if(pendingTxsList2.length == 0) return false; return (pendingTxsList2[pendingTxs2[_id].index] == _id); } function isConfirmedTx(uint _id) public view returns(bool isIndeed) { if(confirmedTxsList.length == 0) return false; return (confirmedTxsList[confirmedTxs[_id].index] == _id); } /// Return the change to a balance caused by a purchase function changeInBalance(Tx memory _purchase) private view returns (int _change) { int change = 0; if (_purchase.debtor == user_1) { change = -int(_purchase.amount); return change; } else if (_purchase.debtor == user_2) { change = int(_purchase.amount); return change; } } function getOtherUser(address _user) private view returns (address) { require(_user == user_1 || _user == user_2, 'user must be registered'); if (_user == user_1) { return user_2; } else if (_user == user_2) { return user_1; } } function timeStamp() private view returns (uint) { return block.timestamp; } /// Length getters for lists of Txs function getPendingTxsLength1() public view returns(uint) { return pendingTxsList1.length; } function getPendingTxsLength2() public view returns(uint) { return pendingTxsList2.length; } function getConfirmedTxsLength() public view returns(uint) { return confirmedTxsList.length; } /// ****** Modifiers ***** modifier onlyUser { require(msg.sender == user_1 || msg.sender == user_2, 'Must be a registered user'); _; } modifier onlyUserOrFactoryOwner { require(msg.sender == parentFactoryOwner || (msg.sender == user_1 || msg.sender == user_2), 'Must be a registered user'); _; } modifier onlyUser1 { require(msg.sender == user_1, 'Must be registered user 1'); _; } modifier onlyInvitedFriend { require(msg.sender == invited_friend, 'Must be the invited friend'); _; } modifier onlyUser2NotRegistered { require (user_2 == address(0), 'User 2 already registered'); _; } modifier onlyBothRegistered { require (user_1 != address(0) && user_2 != address(0), 'Two users must be registered'); _; } }
Set the invited friend's address
function inviteFriend(address _friend) onlyUser1 onlyUser2NotRegistered public { require(_friend != msg.sender, 'You cant invite yourself!'); require(invited_friend == address(0), 'You have already invited someone!'); invited_friend = _friend; AgreementFactory factory = AgreementFactory(parentFactory); factory.newInvite(_friend); }
14,112,353
pragma solidity ^0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint256 private enabled; uint256 private counter; struct Airline { bool isRegistered; bool isFunded; uint256 existingFund; } struct Insurance { //address passenger; uint256 amount; uint256 credit; bool isCredited; } mapping(address => bool) private authorizedContracts; mapping(address => Airline) private airlines; uint256 activeAirlines; address[] multiCalls = new address[](0); address[] airlineVotes = new address[](0); uint constant M = 2; struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; string flight; mapping(address => Insurance) insurees; address[] insureesAddresses; } mapping(bytes32 => Flight) private flights; mapping(address => bytes32[]) private allRefunds; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( address firstAirline ) public { contractOwner = msg.sender; authorizedContracts[firstAirline] = true; activeAirlines = 0; airlines[firstAirline] = Airline({isRegistered: true, isFunded: false, existingFund: 0 ether}); enabled = block.timestamp; counter = 1; } event StatusChange(bool newStatus, uint256 votesNum); event AirlineRegistered(address airline, uint256 votesNum); event AirlineActivated(address airline, uint256 existingFund); event FlightRegistered(address airline, string flight, uint256 timestamp); event InsuranceBought(address caller, uint256 amount, address airline, string flight, uint256 timestamp); event InsureesCredited(uint arrayLength, address airline, string flight, uint256 timestamp); event PassengerPaid(address passenger, uint256 amount); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } modifier requireIsFunded() { require(airlines[msg.sender].isFunded, "Airline is currently not funded"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireIsCallerAuthorized() { require(authorizedContracts[msg.sender], "Caller is not authorized"); _; } modifier rateLimit(uint time) { require(block.timestamp>=enabled, "Rate Limiting is in effect"); enabled = enabled.add(time); _; } modifier entrancyGuard(){ counter = counter.add(1); uint256 guard = counter; _; require(guard == counter,"Re-entrancy is not allowed."); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } function getActiveAirlines() public view returns(uint256) { return activeAirlines; } function isAirline(address airline) public view returns(bool) { return airlines[airline].isRegistered; } function isFunded(address airline) public view returns(bool) { return airlines[airline].isFunded; } function isAuthorized(address airline) public view returns(bool) { return authorizedContracts[airline]; } function isFlightRegistered(address airline, string flight, uint256 timestamp) public view returns(bool) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); return flights[flightKey].isRegistered; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireIsFunded { require(mode != operational, "New mode must be different from existing mode"); bool isDuplicate = false; for(uint c=0; c<multiCalls.length; c++) { if (multiCalls[c] == msg.sender) { isDuplicate = true; break; } } require(!isDuplicate, "Caller has already called this function."); multiCalls.push(msg.sender); uint threshold = 1; if(activeAirlines>4){ threshold = M; } if (multiCalls.length >= threshold) { operational = mode; emit StatusChange(operational, multiCalls.length); multiCalls = new address[](0); } } function authorizeCaller ( address contractAddress ) external requireContractOwner { authorizedContracts[contractAddress] = true; } function deauthorizeCaller ( address contractAddress ) external requireContractOwner { delete authorizedContracts[contractAddress]; } /*function getFlightDetails ( address airline, string flight, uint256 timestamp ) external requireIsCallerAuthorized requireIsOperational returns(Flight flightDetails) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); require(flights[flightKey].isRegistered, "Flight is not registered."); return flights[flightKey]; }*/ /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airline, address caller, uint256 _votes ) external //requireIsFunded already checked at the app contract requireIsCallerAuthorized requireIsOperational returns(bool success, uint256 votes) { airlines[airline] = Airline({isRegistered: true, isFunded: false, existingFund: 0 ether}); emit AirlineRegistered(airline, _votes); return (true, _votes); } /** * @dev Buy insurance for a flight * */ function buy ( address caller, address airline, string flight, uint256 timestamp ) external payable requireIsCallerAuthorized requireIsOperational { bytes32 flightKey = getFlightKey(airline, flight, timestamp); require(flights[flightKey].isRegistered, "Flight is not registered."); require(block.timestamp<=timestamp, "Flight have already passed."); require(flights[flightKey].statusCode == STATUS_CODE_UNKNOWN, "Flight status is already known."); require(flights[flightKey].insurees[caller].amount <= 0, "Already bought insurance."); require(msg.value<=1 ether, "Cannot insure for more than 1 ether"); flights[flightKey].insurees[caller] = Insurance({amount: msg.value, credit: 0, isCredited: false}); flights[flightKey].insureesAddresses.push(caller); emit InsuranceBought(caller, msg.value, airline, flight, timestamp); } /** * @dev Credits payouts to insurees */ function creditInsurees ( address airline, string flight, uint256 timestamp, uint256 percentage ) external requireIsCallerAuthorized requireIsOperational { bytes32 flightKey = getFlightKey(airline, flight, timestamp); require(flights[flightKey].isRegistered, "Flight is not registered."); uint arrayLength = flights[flightKey].insureesAddresses.length; for (uint i=0; i<arrayLength; i++) { address passenger = flights[flightKey].insureesAddresses[i]; if(flights[flightKey].insurees[passenger].amount > 0 && !flights[flightKey].insurees[passenger].isCredited){ flights[flightKey].insurees[passenger].credit = flights[flightKey].insurees[passenger].amount.mul(percentage).div(100); flights[flightKey].insurees[passenger].isCredited = true; allRefunds[passenger].push(flightKey); } } emit InsureesCredited(arrayLength, airline, flight, timestamp); } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address passenger ) external requireIsCallerAuthorized requireIsOperational rateLimit(1 minutes) entrancyGuard() { uint arrayLength = allRefunds[passenger].length; uint256 totalRefund = 0; for (uint i=0; i<arrayLength; i++) { totalRefund = totalRefund.add(flights[allRefunds[passenger][i]].insurees[passenger].credit); flights[allRefunds[passenger][i]].insurees[passenger].credit = 0; } delete allRefunds[passenger]; require(totalRefund>0, 'No money to refund'); passenger.transfer(totalRefund); emit PassengerPaid(passenger, totalRefund); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( address caller ) public payable requireIsCallerAuthorized requireIsOperational { airlines[caller].existingFund = airlines[caller].existingFund.add(msg.value); if(!airlines[caller].isFunded){ airlines[caller].isFunded = true; activeAirlines = activeAirlines.add(1); emit AirlineActivated(caller, airlines[caller].existingFund); } } /** * @dev Register a future flight for insuring. * */ function registerFlight ( address _airline, string _flight, uint256 _timestamp ) external requireIsCallerAuthorized requireIsOperational { bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp); require(!flights[flightKey].isRegistered, "Flight is already registered."); flights[flightKey] = Flight({ isRegistered: true, updatedTimestamp: _timestamp, airline: _airline, flight: _flight, statusCode: STATUS_CODE_UNKNOWN, insureesAddresses: new address[](0) }); emit FlightRegistered(_airline, _flight, _timestamp); } function updateFlightStatus ( address airline, string flight, uint256 timestamp, uint8 statusCode ) external requireIsCallerAuthorized requireIsOperational { // Save the flight information for posterity bytes32 flightKey = getFlightKey(airline, flight, timestamp); require(flights[flightKey].statusCode != statusCode, "New status must be different from existing status"); flights[flightKey].statusCode = statusCode; } // Query the status of any flight function viewFlightStatus ( address airline, string flight, uint256 timestamp ) external view returns(uint8) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); //require(flights[flightKey].hasStatus, "Flight status not available"); return flights[flightKey].statusCode; } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(msg.sender); } }
Initial funding for the insurance. Unless there are too many delayed flights resulting in insurance payouts, the contract should be self-sustaining/
function fund ( address caller ) public payable requireIsCallerAuthorized requireIsOperational { airlines[caller].existingFund = airlines[caller].existingFund.add(msg.value); if(!airlines[caller].isFunded){ airlines[caller].isFunded = true; activeAirlines = activeAirlines.add(1); emit AirlineActivated(caller, airlines[caller].existingFund); } }
5,477,925
./partial_match/3/0xD4Bcc3f1C483Ea10fDb97523357CA660E6B3c71E/sources/IERC721.sol
Required interface of an ERC721 compliant contract./
interface IERC721 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function totalSupply() external view returns (uint256 total); function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function ownerOf(uint256 tokenId) external view returns (address owner); function transfer(address to, uint256 tokenId) external; function approve(address _approved, uint256 _tokenId) external; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; }
5,083,842
pragma solidity 0.6.12; 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); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () 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; } } 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 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)); } } 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"); } } } 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); } 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 { } } // Bcdc with Governance. contract BCDC is ERC20("BCDC", "BCDC"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (BCDCPool). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "BCDC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "BCDC::delegateBySig: invalid nonce"); require(now <= expiry, "BCDC::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "BCDC::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BCDCs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "BCDC::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } interface IMigratorBCDCPool { // Perform LP token migration from legacy UniswapV2 to BCDC. // 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. // BCDC must mint EXACTLY the same amount of BCDC LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // BCDCPool is the Bcdc. He can make Bcdc 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 BCDC is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract BCDCPool is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of BCDCs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBcdcPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBcdcPerShare` (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. BCDCs to distribute per block. uint256 lastRewardBlock; // Last block number that BCDCs distribution occurs. uint256 accBcdcPerShare; // Accumulated BCDCs per share, times 1e12. See below. } // The BCDC TOKEN! BCDC public bcdc; // Dev address. address public devaddr; // Block number when bonus BCDC period ends. uint256 public bonusEndBlock; // BCDC tokens created per block. uint256 public bcdcPerBlock; // Bonus muliplier for early bcdc makers. uint256 public constant BONUS_MULTIPLIER = 2; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorBCDCPool 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 BCDC mining starts. uint256 public startBlock; uint256 public totalBlock = 6000; 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( BCDC _bcdc, address _devaddr, uint256 _bcdcPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { bcdc = _bcdc; devaddr = _devaddr; bcdcPerBlock = _bcdcPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accBcdcPerShare: 0 })); } // Update the given pool's BCDC allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorBCDCPool _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 BCDCs on frontend. function pendingBcdc(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBcdcPerShare = pool.accBcdcPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 bcdcReward = multiplier.mul(bcdcPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accBcdcPerShare = accBcdcPerShare.add(bcdcReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accBcdcPerShare).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; } if (pool.lastRewardBlock == (startBlock+totalBlock)){ return; } if (block.number > (startBlock+totalBlock)){ uint256 multiplier = getMultiplier(pool.lastRewardBlock, (startBlock+totalBlock)); uint256 bcdcReward = multiplier.mul(bcdcPerBlock).mul(pool.allocPoint).div(totalAllocPoint); bcdc.mint(devaddr, bcdcReward.div(10)); bcdc.mint(address(this), bcdcReward); pool.accBcdcPerShare = pool.accBcdcPerShare.add(bcdcReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = (startBlock+totalBlock); return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 bcdcReward = multiplier.mul(bcdcPerBlock).mul(pool.allocPoint).div(totalAllocPoint); bcdc.mint(devaddr, bcdcReward.div(10)); bcdc.mint(address(this), bcdcReward); pool.accBcdcPerShare = pool.accBcdcPerShare.add(bcdcReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to BCDCPool for BCDC 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.accBcdcPerShare).div(1e12).sub(user.rewardDebt); safeBcdcTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accBcdcPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // DepositFor LP tokens to BCDCPool for BCDC allocation. function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accBcdcPerShare).div(1e12).sub(user.rewardDebt); safeBcdcTransfer(depositFor, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accBcdcPerShare).div(1e12); emit Deposit(depositFor, _pid, _amount); } // Withdraw LP tokens from BCDCPool. 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.accBcdcPerShare).div(1e12).sub(user.rewardDebt); safeBcdcTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accBcdcPerShare).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 bcdc transfer function, just in case if rounding error causes pool to not have enough BCDCs. function safeBcdcTransfer(address _to, uint256 _amount) internal { uint256 bcdcBal = bcdc.balanceOf(address(this)); if (_amount > bcdcBal) { bcdc.transfer(_to, bcdcBal); } else { bcdc.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
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 onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accBcdcPerShare: 0 })); }
59,438
./full_match/100/0xEd469d6aa0658b71B9dE75c2fe401924FCf0534d/sources/src/BzzRouter.sol
ERC677 transfer callback function for use with honeyswap or similar ERC677 transfer and call function amount the amount of bzz tokens that were sent to be evenly distributed data the data to be used for determining which batch to topUp should only be able to call this from the erc677 contract
function onTokenTransfer(address, uint256 amount, bytes memory data) external returns (bool) { require(msg.sender == address(bzz) && data.length != 0, "erc677/invalid-tx"); execute(amount, data); return true; }
14,279,983
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./base/EternalStorage.sol"; import "./base/IMarketCoreFacet.sol"; import "./base/IMarketObserver.sol"; import "./base/IMarketOfferStates.sol"; import "./base/IParent.sol"; import "./base/IChild.sol"; import "./base/IDiamondFacet.sol"; import "./base/Controller.sol"; import "./base/SafeMath.sol"; import "./base/IERC20.sol"; import "./base/ReentrancyGuard.sol"; import "./MarketFacetBase.sol"; /** * Forked from https://github.com/nayms/maker-otc/blob/master/contracts/matching_market.sol */ contract MarketCoreFacet is EternalStorage, Controller, MarketFacetBase, IDiamondFacet, IMarketCoreFacet, IMarketOfferStates, ReentrancyGuard { using SafeMath for uint256; modifier assertIsActive (uint256 _offerId) { require(dataUint256[__i(_offerId, "state")] == OFFER_STATE_ACTIVE, "offer not active"); _; } /** * Constructor */ constructor (address _settings) Controller(_settings) public { } // IDiamondFacet function getSelectors () public pure override returns (bytes memory) { return abi.encodePacked( IMarketCoreFacet.executeLimitOffer.selector, IMarketCoreFacet.executeLimitOfferWithObserver.selector, IMarketCoreFacet.executeMarketOffer.selector, IMarketCoreFacet.buy.selector, IMarketCoreFacet.cancel.selector ); } // IMarketCoreFacet function cancel(uint256 _offerId) assertIsActive(_offerId) nonReentrant external override { address creator = dataAddress[__i(_offerId, "creator")]; require(creator == msg.sender, "only creator can cancel"); dataUint256[__i(_offerId, "state")] = OFFER_STATE_CANCELLED; _cancel(_offerId); } function buy(uint256 _offerId, uint256 _amount) assertIsActive(_offerId) nonReentrant external override { _buy(_offerId, _amount); } function executeLimitOffer( address _sellToken, uint256 _sellAmount, address _buyToken, uint256 _buyAmount, uint256 _feeSchedule ) external override returns (uint256) { return executeLimitOfferWithObserver( _sellToken, _sellAmount, _buyToken, _buyAmount, _feeSchedule, address(0), "" ); } function executeLimitOfferWithObserver( address _sellToken, uint256 _sellAmount, address _buyToken, uint256 _buyAmount, uint256 _feeSchedule, address _notify, bytes memory _notifyData ) nonReentrant public override returns (uint256) { _assertValidOffer( _sellToken, _sellAmount, _buyToken, _buyAmount, _feeSchedule ); _calculateFee( _sellToken, _sellAmount, _buyToken, _buyAmount, _feeSchedule ); uint256 remainingBuyAmount_; uint256 remainingSellAmount_; (remainingBuyAmount_, remainingSellAmount_) = _matchToExistingOffers( _sellToken, _sellAmount, _buyToken, _buyAmount, _notify, _notifyData ); // if still some left if (remainingBuyAmount_ > 0 && remainingSellAmount_ > 0 && remainingSellAmount_ >= dataUint256["dust"] ) { // new offer should be created uint256 id = _createLimitOffer( _sellToken, remainingSellAmount_, _buyToken, remainingBuyAmount_, _feeSchedule, _notify, _notifyData ); // ensure it's in the right position in the list _insertOfferIntoSortedList(id); return id; } return 0; // no limit offer created, fully matched } function executeMarketOffer(address _sellToken, uint256 _sellAmount, address _buyToken) nonReentrant external override { _assertValidOffer( _sellToken, _sellAmount, _buyToken, 1, FEE_SCHEDULE_STANDARD ); uint256 sellAmount = _sellAmount; uint256 id; uint256 soldAmount; while (sellAmount > 0) { id = _getBestOfferId(_buyToken, _sellToken); require(id != 0, "not enough orders in market"); uint256 offerBuyAmount = dataUint256[__i(id, "buyAmount")]; uint256 offerSellAmount = dataUint256[__i(id, "sellAmount")]; // There is a chance that pay_amt is smaller than 1 wei of the other token if (sellAmount * 1 ether < wdiv(offerBuyAmount, offerSellAmount)) { break; // We consider that all amount is sold } // if sell amount >= offer buy amount then lets buy the whole offer if (sellAmount >= offerBuyAmount) { //If amount to sell is higher or equal than current offer amount to buy _buy(id, offerBuyAmount); soldAmount = soldAmount.add(offerBuyAmount); sellAmount = sellAmount.sub(offerBuyAmount); } // otherwise, let's just buy what we can else { _buy(id, sellAmount); soldAmount = soldAmount.add(sellAmount); sellAmount = 0; } } // check that everything got sold require(soldAmount >= _sellAmount, "sale not fulfilled"); } // Private function _insertOfferIntoSortedList(uint256 _offerId) private { // check that offer is NOT in the sorted list require(!_isOfferInSortedList(_offerId), "offer not in sorted list"); address sellToken = dataAddress[__i(_offerId, "sellToken")]; address buyToken = dataAddress[__i(_offerId, "buyToken")]; uint256 prevId; // find position of next highest offer uint256 top = dataUint256[__iaa(0, sellToken, buyToken, "bestOfferId")]; uint256 oldTop = 0; while (top != 0 && _isOfferPricedLtOrEq(_offerId, top)) { oldTop = top; top = dataUint256[__i(top, "rankPrev")]; } uint256 pos = oldTop; // insert offer at position if (pos != 0) { prevId = dataUint256[__i(pos, "rankPrev")]; dataUint256[__i(pos, "rankPrev")] = _offerId; dataUint256[__i(_offerId, "rankNext")] = pos; } // else this is the new best offer, so insert at top else { prevId = dataUint256[__iaa(0, sellToken, buyToken, "bestOfferId")]; dataUint256[__iaa(0, sellToken, buyToken, "bestOfferId")] = _offerId; } if (prevId != 0) { // requirement below is satisfied by statements above // require(!_isOfferPricedLtOrEq(_offerId, prevId)); dataUint256[__i(prevId, "rankNext")] = _offerId; dataUint256[__i(_offerId, "rankPrev")] = prevId; } dataUint256[__iaa(0, sellToken, buyToken, "span")] += 1; } function _removeOfferFromSortedList(uint256 _offerId) private { // check that offer is in the sorted list require(_isOfferInSortedList(_offerId), "offer not in sorted list"); address sellToken = dataAddress[__i(_offerId, "sellToken")]; address buyToken = dataAddress[__i(_offerId, "buyToken")]; require(dataUint256[__iaa(0, sellToken, buyToken, "span")] > 0, "token pair sorted list does not exist"); // if offer is not the highest offer if (_offerId != dataUint256[__iaa(0, sellToken, buyToken, "bestOfferId")]) { uint256 nextId = dataUint256[__i(_offerId, "rankNext")]; require(dataUint256[__i(nextId, "rankPrev")] == _offerId, "sort check failed"); dataUint256[__i(nextId, "rankPrev")] = dataUint256[__i(_offerId, "rankPrev")]; } // if offer is the highest offer else { dataUint256[__iaa(0, sellToken, buyToken, "bestOfferId")] = dataUint256[__i(_offerId, "rankPrev")]; } // if offer is not the lowest offer if (dataUint256[__i(_offerId, "rankPrev")] != 0) { uint256 prevId = dataUint256[__i(_offerId, "rankPrev")]; require(dataUint256[__i(prevId, "rankNext")] == _offerId, "sort check failed"); dataUint256[__i(prevId, "rankNext")] = dataUint256[__i(_offerId, "rankNext")]; } // nullify dataUint256[__i(_offerId, "rankNext")] = 0; dataUint256[__i(_offerId, "rankPrev")] = 0; dataUint256[__iaa(0, sellToken, buyToken, "span")] -= 1; } function _isOfferPricedLtOrEq(uint256 _lowOfferId, uint256 _highOfferId) private view returns (bool) { uint256 lowSellAmount = dataUint256[__i(_lowOfferId, "sellAmount")]; uint256 lowBuyAmount = dataUint256[__i(_lowOfferId, "buyAmount")]; uint256 highSellAmount = dataUint256[__i(_highOfferId, "sellAmount")]; uint256 highBuyAmount = dataUint256[__i(_highOfferId, "buyAmount")]; return lowBuyAmount.mul(highSellAmount) >= highBuyAmount.mul(lowSellAmount); } function _isOfferInSortedList(uint _offerId) private view returns(bool) { address sellToken = dataAddress[__i(_offerId, "sellToken")]; address buyToken = dataAddress[__i(_offerId, "buyToken")]; return dataUint256[__i(_offerId, "rankNext")] != 0 || dataUint256[__i(_offerId, "rankPrev")] != 0 || dataUint256[__iaa(0, sellToken, buyToken, "bestOfferId")] == _offerId; } function _matchToExistingOffers( address _sellToken, uint256 _sellAmount, address _buyToken, uint256 _buyAmount, address _notify, bytes memory _notifyData ) private returns (uint256 remainingBuyAmount_, uint256 remainingSellAmount_) { remainingBuyAmount_ = _buyAmount; remainingSellAmount_ = _sellAmount; // there is at least one offer stored for token pair uint256 bestOfferId = dataUint256[__iaa(0, _buyToken, _sellToken, "bestOfferId")]; while (bestOfferId > 0) { uint256 bestBuyAmount = dataUint256[__i(bestOfferId, "buyAmount")]; uint256 bestSellAmount = dataUint256[__i(bestOfferId, "sellAmount")]; // Ugly hack to work around rounding errors. Based on the idea that // the furthest the amounts can stray from their "true" values is 1. // Ergo the worst case has `sellAmount` and `bestSellAmount` at +1 away from // their "correct" values and `bestBuyAmount` and `buyAmount` at -1. // Since (c - 1) * (d - 1) > (a + 1) * (b + 1) is equivalent to // c * d > a * b + a + b + c + d, we write... // // (For detailed breakdown see https://hiddentao.com/archives/2019/09/08/maker-otc-on-chain-orderbook-deep-dive) // if (bestBuyAmount.mul(remainingBuyAmount_) > remainingSellAmount_.mul(bestSellAmount).add(bestBuyAmount).add(remainingBuyAmount_).add(remainingSellAmount_).add(bestSellAmount)) { break; } // ^ The `rounding` parameter is a compromise borne of a couple days // of discussion. // avoid stack-too-deep { // do the buy uint256 finalSellAmount = min(bestBuyAmount, remainingSellAmount_); _buyWithObserver( bestOfferId, finalSellAmount, _notify, _notifyData ); // calculate how much is left to buy/sell uint256 sellAmountOld = remainingSellAmount_; remainingSellAmount_ = remainingSellAmount_.sub(finalSellAmount); remainingBuyAmount_ = remainingSellAmount_.mul(remainingBuyAmount_).div(sellAmountOld); } // if nothing left to sell or buy then we're done if (remainingSellAmount_ == 0 || remainingBuyAmount_ == 0) { break; } bestOfferId = dataUint256[__iaa(0, _buyToken, _sellToken, "bestOfferId")]; } } function _createLimitOffer( address _sellToken, uint256 _sellAmount, address _buyToken, uint256 _buyAmount, uint256 _feeSchedule, address _notify, bytes memory _notifyData ) private returns (uint256) { dataUint256["lastOfferId"] += 1; uint256 id = dataUint256["lastOfferId"]; dataAddress[__i(id, "creator")] = msg.sender; dataAddress[__i(id, "sellToken")] = _sellToken; dataUint256[__i(id, "sellAmount")] = _sellAmount; dataUint256[__i(id, "sellAmountInitial")] = _sellAmount; dataAddress[__i(id, "buyToken")] = _buyToken; dataUint256[__i(id, "buyAmount")] = _buyAmount; dataUint256[__i(id, "buyAmountInitial")] = _buyAmount; dataUint256[__i(id, "feeSchedule")] = _feeSchedule; dataAddress[__i(id, "notify")] = _notify; dataBytes[__i(id, "notifyData")] = _notifyData; dataUint256[__i(id, "state")] = OFFER_STATE_ACTIVE; // escrow the tokens require(IERC20(_sellToken).transferFrom(msg.sender, address(this), _sellAmount), "unable to escrow tokens"); return id; } function _buy(uint256 _offerId, uint256 _requestedBuyAmount) private { _buyWithObserver( _offerId, _requestedBuyAmount, address(0), "" ); } function _buyWithObserver( uint256 _offerId, uint256 _requestedBuyAmount, address _buyNotify, bytes memory _buyNotifyData ) private { (TokenAmount memory offerSell, TokenAmount memory offerBuy) = _getOfferTokenAmounts(_offerId); // (a / b) * c = c * a / b -> do multiplication first to avoid underflow uint256 thisSaleSellAmount = _requestedBuyAmount.mul(offerSell.amount).div(offerBuy.amount); // check bounds and update balances _checkBoundsAndUpdateBalances(_offerId, thisSaleSellAmount, _requestedBuyAmount); // calculate and take out fees ( uint256 finalSellAmount, TokenAmount memory fee ) = _takeFees( offerBuy.token, _requestedBuyAmount, offerSell.token, thisSaleSellAmount, dataUint256[__i(_offerId, "feeSchedule")] ); // do the transfer require(IERC20(offerBuy.token).transferFrom(msg.sender, dataAddress[__i(_offerId, "creator")], _requestedBuyAmount), "sender -> creator transfer failed"); require(IERC20(offerSell.token).transfer(msg.sender, finalSellAmount), "market -> sender transfer failed"); // notify observers _notifyObserversOfTrade( _offerId, thisSaleSellAmount, _requestedBuyAmount, fee, _buyNotify, _buyNotifyData ); // cancel offer if it has become dust if (dataUint256[__i(_offerId, "sellAmount")] < dataUint256["dust"]) { dataUint256[__i(_offerId, "state")] = OFFER_STATE_FULFILLED; _cancel(_offerId); } } function _checkBoundsAndUpdateBalances(uint256 _offerId, uint256 _sellAmount, uint256 _buyAmount) private { (TokenAmount memory offerSell, TokenAmount memory offerBuy) = _getOfferTokenAmounts(_offerId); require(uint128(_buyAmount) == _buyAmount, "buy amount exceeds int limit"); require(uint128(_sellAmount) == _sellAmount, "sell amount exceeds int limit"); require(_buyAmount > 0, "requested buy amount is 0"); require(_buyAmount <= offerBuy.amount, "requested buy amount too large"); require(_sellAmount > 0, "calculated sell amount is 0"); require(_sellAmount <= offerSell.amount, "calculated sell amount too large"); // update balances dataUint256[__i(_offerId, "sellAmount")] = offerSell.amount.sub(_sellAmount); dataUint256[__i(_offerId, "buyAmount")] = offerBuy.amount.sub(_buyAmount); } function _takeFees( address _buyToken, uint256 _buyAmount, address _sellToken, uint256 _sellAmount, uint256 _feeSchedule ) private returns (uint256 finalSellAmount_, TokenAmount memory fee_) { address feeBank = _getFeeBank(); finalSellAmount_ = _sellAmount; fee_ = _calculateFee(_buyToken, _buyAmount, _sellToken, _sellAmount, _feeSchedule); if (fee_.token == _buyToken) { // if fee is to be paid in the buy token then it must be paid on top of buy amount require(IERC20(_buyToken).transferFrom(msg.sender, feeBank, fee_.amount), "sender -> feebank fee transfer failed"); } else { // if fee is to be paid in the sell token then it must be paid from the received amount finalSellAmount_ = finalSellAmount_.sub(fee_.amount); require(IERC20(_sellToken).transfer(feeBank, fee_.amount), "market -> feebank fee transfer failed"); } } function _notifyObserversOfTrade( uint256 _offerId, uint256 _soldAmount, uint256 _boughtAmount, TokenAmount memory _fee, address _buyNotify, bytes memory _buyNotifyData ) private { address offerNotify = dataAddress[__i(_offerId, "notify")]; bytes memory offerNotifyData = dataBytes[__i(_offerId, "notifyData")]; if (_buyNotify != address(0)) { IMarketObserver(_buyNotify).handleTrade( _offerId, _soldAmount, _boughtAmount, _fee.token, _fee.amount, msg.sender, _buyNotifyData ); } if (offerNotify != address(0)) { IMarketObserver(offerNotify).handleTrade( _offerId, _soldAmount, _boughtAmount, _fee.token, _fee.amount, msg.sender, offerNotifyData ); } } function _cancel(uint256 _offerId) private { if (_isOfferInSortedList(_offerId)) { _removeOfferFromSortedList(_offerId); } address creator = dataAddress[__i(_offerId, "creator")]; address sellToken = dataAddress[__i(_offerId, "sellToken")]; uint256 sellAmount = dataUint256[__i(_offerId, "sellAmount")]; uint256 buyAmount = dataUint256[__i(_offerId, "buyAmount")]; address notify = dataAddress[__i(_offerId, "notify")]; bytes memory notifyData = dataBytes[__i(_offerId, "notifyData")]; // transfer remaining sell amount back to creator if (sellAmount > 0) { require(IERC20(sellToken).transfer(creator, sellAmount), "refund creator failed"); } // notify observers if (notify != address(0)) { IMarketObserver(notify).handleClosure( _offerId, sellAmount, buyAmount, notifyData ); } } function _assertValidOffer(address _sellToken, uint256 _sellAmount, address _buyToken, uint256 _buyAmount, uint256 _feeSchedule) private view { require(uint128(_sellAmount) == _sellAmount, "sell amount must be uint128"); require(uint128(_buyAmount) == _buyAmount, "buy amount must be uint128"); require(_sellAmount > 0, "sell amount must be >0"); require(_sellToken != address(0), "sell token must be valid"); require(_buyAmount > 0, "buy amount must be >0"); require(_buyToken != address(0), "buy token must be valid"); require(_sellToken != _buyToken, "cannot sell and buy same token"); // if caller requested the 'platform action' fee schedule then check that they're allowed to do so if (_feeSchedule == FEE_SCHEDULE_PLATFORM_ACTION) { // get and check parent address parent = IChild(msg.sender).getParent(); require(IParent(parent).hasChild(msg.sender), "fee schedule: bad parent"); // get entity deployer address entityDeployer = settings().getRootAddress(SETTING_ENTITY_DEPLOYER); // if parent is NOT the entity deployer then the grandparent must be if (parent != entityDeployer) { // the caller must be a policy, in which case let's goto the grandparent address grandparent = IChild(parent).getParent(); require(IParent(grandparent).hasChild(parent), "fee schedule: bad grandparent"); require(grandparent == entityDeployer, "fee schedule: bad deployment"); } } } function min(uint x, uint y) private pure returns (uint z) { z = (x < y ? x : y); } }
(a / b) c = c a / b -> do multiplication first to avoid underflow check bounds and update balances calculate and take out fees do the transfer notify observers cancel offer if it has become dust
) private { (TokenAmount memory offerSell, TokenAmount memory offerBuy) = _getOfferTokenAmounts(_offerId); uint256 thisSaleSellAmount = _requestedBuyAmount.mul(offerSell.amount).div(offerBuy.amount); _checkBoundsAndUpdateBalances(_offerId, thisSaleSellAmount, _requestedBuyAmount); ( uint256 finalSellAmount, TokenAmount memory fee ) = _takeFees( offerBuy.token, _requestedBuyAmount, offerSell.token, thisSaleSellAmount, dataUint256[__i(_offerId, "feeSchedule")] ); require(IERC20(offerBuy.token).transferFrom(msg.sender, dataAddress[__i(_offerId, "creator")], _requestedBuyAmount), "sender -> creator transfer failed"); require(IERC20(offerSell.token).transfer(msg.sender, finalSellAmount), "market -> sender transfer failed"); _notifyObserversOfTrade( _offerId, thisSaleSellAmount, _requestedBuyAmount, fee, _buyNotify, _buyNotifyData ); function _createLimitOffer( address _sellToken, uint256 _sellAmount, address _buyToken, uint256 _buyAmount, uint256 _feeSchedule, address _notify, bytes memory _notifyData ) private returns (uint256) } } function _buyWithObserver( uint256 _offerId, uint256 _requestedBuyAmount, address _buyNotify, bytes memory _buyNotifyData if (dataUint256[__i(_offerId, "sellAmount")] < dataUint256["dust"]) { dataUint256[__i(_offerId, "state")] = OFFER_STATE_FULFILLED; _cancel(_offerId); } }
12,560,192
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity 0.5.9; import "../Land/erc721/LandBaseToken.sol"; import "../contracts_common/Interfaces/ERC721MandatoryTokenReceiver.sol"; import "../BaseWithStorage/ERC2771Handler.sol"; import "../contracts_common/BaseWithStorage/PausableWithAdmin.sol"; contract LandSwapV2 is ERC721MandatoryTokenReceiver, ERC2771Handler, PausableWithAdmin { bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02; bytes4 internal constant _ERC721_BATCH_RECEIVED = 0x4b808c46; LandBaseToken public _oldLand; LandBaseToken public _newLand; bool internal _initialized; address public _batchMigration; modifier initializer() { require(!_initialized, "LandSwap: Contract already initialized"); _; } function initialize (address admin, address trustedForwarder, address oldLand, address newLand, address batchMigration) public initializer { _admin = admin; __ERC2771Handler_initialize(trustedForwarder); _oldLand = LandBaseToken(oldLand); _newLand = LandBaseToken(newLand); _batchMigration = batchMigration; _initialized = true; } function onERC721BatchReceived(address, address, uint256[] calldata, bytes calldata) external returns (bytes4) { require(msg.sender == address(_oldLand), "NOT_OLD_LAND"); return _ERC721_BATCH_RECEIVED; } function onERC721Received(address, address, uint256, bytes calldata) external returns (bytes4) { require(msg.sender == address(_oldLand), "NOT_OLD_LAND"); return _ERC721_RECEIVED; } function swap(uint256[] calldata sizes, uint256[] calldata xs, uint256[] calldata ys, bytes calldata data) external whenNotPaused { address from = _msgSender(); _oldLand.batchTransferQuad(from, address(this), sizes, xs, ys, data); for (uint256 i = 0; i < sizes.length; i++) { _newLand.mintQuad(from, sizes[i], xs[i], ys[i], data); } } function migrate(uint256[] calldata sizes, uint256[] calldata xs, uint256[] calldata ys, bytes calldata data) external whenNotPaused { require(msg.sender == _batchMigration, "LandSwap.migrate: NOT_BATCH_MIGRATION"); address from = _oldLand.ownerOf(xs[0] + ys[0] * 408); for (uint256 index = 0; index < sizes.length; index++) { for (uint256 i = 0; i < sizes[index]; i++) { for (uint256 j = 0; j < sizes[index]; j++) { uint256 x = xs[index] + i; uint256 y = ys[index] + j; uint256 id = x + y * 408; require(from == _oldLand.ownerOf(id), "LandSwap.migrate: NOT_OWNER"); } } } _oldLand.batchTransferQuad(from, address(this), sizes, xs, ys, data); for (uint256 i = 0; i < sizes.length; i++) { _newLand.mintQuad(from, sizes[i], xs[i], ys[i], data); } } function burn(uint256[] calldata ids) external whenNotPaused { for (uint256 i = 0; i < ids.length; i++) { _oldLand.burn(ids[i]); } } function supportsInterface(bytes4 id) external pure returns (bool) { return id == 0x01ffc9a7 || id == 0x5e8bf644; } function setBatchMigration(address batchMigration) external onlyAdmin { _batchMigration = batchMigration; } // Empty storage space in contracts for future enhancements // ref: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/issues/13) uint256[49] private __gap; } /* solhint-disable func-order, code-complexity */ pragma solidity 0.5.9; import "./ERC721BaseToken.sol"; contract LandBaseToken is ERC721BaseToken { // Our grid is 408 x 408 lands uint256 internal constant GRID_SIZE = 408; uint256 internal constant LAYER = 0xFF00000000000000000000000000000000000000000000000000000000000000; uint256 internal constant LAYER_1x1 = 0x0000000000000000000000000000000000000000000000000000000000000000; uint256 internal constant LAYER_3x3 = 0x0100000000000000000000000000000000000000000000000000000000000000; uint256 internal constant LAYER_6x6 = 0x0200000000000000000000000000000000000000000000000000000000000000; uint256 internal constant LAYER_12x12 = 0x0300000000000000000000000000000000000000000000000000000000000000; uint256 internal constant LAYER_24x24 = 0x0400000000000000000000000000000000000000000000000000000000000000; mapping(address => bool) internal _minters; event Minter(address superOperator, bool enabled); /// @notice Enable or disable the ability of `minter` to mint tokens /// @param minter address that will be given/removed minter right. /// @param enabled set whether the minter is enabled or disabled. function setMinter(address minter, bool enabled) external { require( msg.sender == _admin, "only admin is allowed to add minters" ); _minters[minter] = enabled; emit Minter(minter, enabled); } /// @notice check whether address `who` is given minter rights. /// @param who The address to query. /// @return whether the address has minter rights. function isMinter(address who) public view returns (bool) { return _minters[who]; } /// @notice total width of the map /// @return width function width() external returns(uint256) { return GRID_SIZE; } /// @notice total height of the map /// @return height function height() external returns(uint256) { return GRID_SIZE; } /// @notice x coordinate of Land token /// @param id tokenId /// @return the x coordinates function x(uint256 id) external returns(uint256) { require(_ownerOf(id) != address(0), "token does not exist"); return id % GRID_SIZE; } /// @notice y coordinate of Land token /// @param id tokenId /// @return the y coordinates function y(uint256 id) external returns(uint256) { require(_ownerOf(id) != address(0), "token does not exist"); return id / GRID_SIZE; } /** * @notice Mint a new quad (aligned to a quad tree with size 3, 6, 12 or 24 only) * @param to The recipient of the new quad * @param size The size of the new quad * @param x The top left x coordinate of the new quad * @param y The top left y coordinate of the new quad * @param data extra data to pass to the transfer */ function mintQuad(address to, uint256 size, uint256 x, uint256 y, bytes calldata data) external { require(to != address(0), "to is zero address"); require( isMinter(msg.sender), "Only a minter can mint" ); require(x % size == 0 && y % size == 0, "Invalid coordinates"); require(x <= GRID_SIZE - size && y <= GRID_SIZE - size, "Out of bounds"); uint256 quadId; uint256 id = x + y * GRID_SIZE; if (size == 1) { quadId = id; } else if (size == 3) { quadId = LAYER_3x3 + id; } else if (size == 6) { quadId = LAYER_6x6 + id; } else if (size == 12) { quadId = LAYER_12x12 + id; } else if (size == 24) { quadId = LAYER_24x24 + id; } else { require(false, "Invalid size"); } require(_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == 0, "Already minted as 24x24"); uint256 toX = x+size; uint256 toY = y+size; if (size <= 12) { require( _owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE] == 0, "Already minted as 12x12" ); } else { for (uint256 x12i = x; x12i < toX; x12i += 12) { for (uint256 y12i = y; y12i < toY; y12i += 12) { uint256 id12x12 = LAYER_12x12 + x12i + y12i * GRID_SIZE; require(_owners[id12x12] == 0, "Already minted as 12x12"); } } } if (size <= 6) { require(_owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE] == 0, "Already minted as 6x6"); } else { for (uint256 x6i = x; x6i < toX; x6i += 6) { for (uint256 y6i = y; y6i < toY; y6i += 6) { uint256 id6x6 = LAYER_6x6 + x6i + y6i * GRID_SIZE; require(_owners[id6x6] == 0, "Already minted as 6x6"); } } } if (size <= 3) { require(_owners[LAYER_3x3 + (x/3) * 3 + ((y/3) * 3) * GRID_SIZE] == 0, "Already minted as 3x3"); } else { for (uint256 x3i = x; x3i < toX; x3i += 3) { for (uint256 y3i = y; y3i < toY; y3i += 3) { uint256 id3x3 = LAYER_3x3 + x3i + y3i * GRID_SIZE; require(_owners[id3x3] == 0, "Already minted as 3x3"); } } } for (uint256 i = 0; i < size*size; i++) { uint256 id = _idInPath(i, size, x, y); require(_owners[id] == 0, "Already minted"); emit Transfer(address(0), to, id); } _owners[quadId] = uint256(to); _numNFTPerAddress[to] += size * size; _checkBatchReceiverAcceptQuad(msg.sender, address(0), to, size, x, y, data); } function _idInPath(uint256 i, uint256 size, uint256 x, uint256 y) internal pure returns(uint256) { uint256 row = i / size; if(row % 2 == 0) { // alow ids to follow a path in a quad return (x + (i%size)) + ((y + row) * GRID_SIZE); } else { return ((x + size) - (1 + i%size)) + ((y + row) * GRID_SIZE); } } /// @notice transfer one quad (aligned to a quad tree with size 3, 6, 12 or 24 only) /// @param from current owner of the quad /// @param to destination /// @param size size of the quad /// @param x The top left x coordinate of the quad /// @param y The top left y coordinate of the quad /// @param data additional data function transferQuad(address from, address to, uint256 size, uint256 x, uint256 y, bytes calldata data) external { require(from != address(0), "from is zero address"); require(to != address(0), "can't send to zero address"); bool metaTx = msg.sender != from && _metaTransactionContracts[msg.sender]; if (msg.sender != from && !metaTx) { require( _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "not authorized to transferQuad" ); } _transferQuad(from, to, size, x, y); _numNFTPerAddress[from] -= size * size; _numNFTPerAddress[to] += size * size; _checkBatchReceiverAcceptQuad(metaTx ? from : msg.sender, from, to, size, x, y, data); } function _checkBatchReceiverAcceptQuad( address operator, address from, address to, uint256 size, uint256 x, uint256 y, bytes memory data ) internal { if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) { uint256[] memory ids = new uint256[](size*size); for (uint256 i = 0; i < size*size; i++) { ids[i] = _idInPath(i, size, x, y); } require( _checkOnERC721BatchReceived(operator, from, to, ids, data), "erc721 batch transfer rejected by to" ); } } /// @notice transfer multiple quad (aligned to a quad tree with size 3, 6, 12 or 24 only) /// @param from current owner of the quad /// @param to destination /// @param sizes list of sizes for each quad /// @param xs list of top left x coordinates for each quad /// @param ys list of top left y coordinates for each quad /// @param data additional data function batchTransferQuad( address from, address to, uint256[] calldata sizes, uint256[] calldata xs, uint256[] calldata ys, bytes calldata data ) external { require(from != address(0), "from is zero address"); require(to != address(0), "can't send to zero address"); require(sizes.length == xs.length && xs.length == ys.length, "invalid data"); bool metaTx = msg.sender != from && _metaTransactionContracts[msg.sender]; if (msg.sender != from && !metaTx) { require( _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "not authorized to transferMultiQuads" ); } uint256 numTokensTransfered = 0; for (uint256 i = 0; i < sizes.length; i++) { uint256 size = sizes[i]; _transferQuad(from, to, size, xs[i], ys[i]); numTokensTransfered += size * size; } _numNFTPerAddress[from] -= numTokensTransfered; _numNFTPerAddress[to] += numTokensTransfered; if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) { uint256[] memory ids = new uint256[](numTokensTransfered); uint256 counter = 0; for (uint256 j = 0; j < sizes.length; j++) { uint256 size = sizes[j]; for (uint256 i = 0; i < size*size; i++) { ids[counter] = _idInPath(i, size, xs[j], ys[j]); counter++; } } require( _checkOnERC721BatchReceived(metaTx ? from : msg.sender, from, to, ids, data), "erc721 batch transfer rejected by to" ); } } function _transferQuad(address from, address to, uint256 size, uint256 x, uint256 y) internal { if (size == 1) { uint256 id1x1 = x + y * GRID_SIZE; address owner = _ownerOf(id1x1); require(owner != address(0), "token does not exist"); require(owner == from, "not owner in _transferQuad"); _owners[id1x1] = uint256(to); } else { _regroup(from, to, size, x, y); } for (uint256 i = 0; i < size*size; i++) { emit Transfer(from, to, _idInPath(i, size, x, y)); } } function _checkAndClear(address from, uint256 id) internal returns(bool) { uint256 owner = _owners[id]; if (owner != 0) { require(address(owner) == from, "not owner"); _owners[id] = 0; return true; } return false; } function _regroup(address from, address to, uint256 size, uint256 x, uint256 y) internal { require(x % size == 0 && y % size == 0, "Invalid coordinates"); require(x <= GRID_SIZE - size && y <= GRID_SIZE - size, "Out of bounds"); if (size == 3) { _regroup3x3(from, to, x, y, true); } else if (size == 6) { _regroup6x6(from, to, x, y, true); } else if (size == 12) { _regroup12x12(from, to, x, y, true); } else if (size == 24) { _regroup24x24(from, to, x, y, true); } else { require(false, "Invalid size"); } } function _regroup3x3(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) { uint256 id = x + y * GRID_SIZE; uint256 quadId = LAYER_3x3 + id; bool ownerOfAll = true; for (uint256 xi = x; xi < x+3; xi++) { for (uint256 yi = y; yi < y+3; yi++) { ownerOfAll = _checkAndClear(from, xi + yi * GRID_SIZE) && ownerOfAll; } } if(set) { if(!ownerOfAll) { require( _owners[quadId] == uint256(from) || _owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE] == uint256(from) || _owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE] == uint256(from) || _owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == uint256(from), "not owner of all sub quads nor parent quads" ); } _owners[quadId] = uint256(to); return true; } return ownerOfAll; } function _regroup6x6(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) { uint256 id = x + y * GRID_SIZE; uint256 quadId = LAYER_6x6 + id; bool ownerOfAll = true; for (uint256 xi = x; xi < x+6; xi += 3) { for (uint256 yi = y; yi < y+6; yi += 3) { bool ownAllIndividual = _regroup3x3(from, to, xi, yi, false); uint256 id3x3 = LAYER_3x3 + xi + yi * GRID_SIZE; uint256 owner3x3 = _owners[id3x3]; if (owner3x3 != 0) { if(!ownAllIndividual) { require(owner3x3 == uint256(from), "not owner of 3x3 quad"); } _owners[id3x3] = 0; } ownerOfAll = (ownAllIndividual || owner3x3 != 0) && ownerOfAll; } } if(set) { if(!ownerOfAll) { require( _owners[quadId] == uint256(from) || _owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE] == uint256(from) || _owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == uint256(from), "not owner of all sub quads nor parent quads" ); } _owners[quadId] = uint256(to); return true; } return ownerOfAll; } function _regroup12x12(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) { uint256 id = x + y * GRID_SIZE; uint256 quadId = LAYER_12x12 + id; bool ownerOfAll = true; for (uint256 xi = x; xi < x+12; xi += 6) { for (uint256 yi = y; yi < y+12; yi += 6) { bool ownAllIndividual = _regroup6x6(from, to, xi, yi, false); uint256 id6x6 = LAYER_6x6 + xi + yi * GRID_SIZE; uint256 owner6x6 = _owners[id6x6]; if (owner6x6 != 0) { if(!ownAllIndividual) { require(owner6x6 == uint256(from), "not owner of 6x6 quad"); } _owners[id6x6] = 0; } ownerOfAll = (ownAllIndividual || owner6x6 != 0) && ownerOfAll; } } if(set) { if(!ownerOfAll) { require( _owners[quadId] == uint256(from) || _owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == uint256(from), "not owner of all sub quads nor parent quads" ); } _owners[quadId] = uint256(to); return true; } return ownerOfAll; } function _regroup24x24(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) { uint256 id = x + y * GRID_SIZE; uint256 quadId = LAYER_24x24 + id; bool ownerOfAll = true; for (uint256 xi = x; xi < x+24; xi += 12) { for (uint256 yi = y; yi < y+24; yi += 12) { bool ownAllIndividual = _regroup12x12(from, to, xi, yi, false); uint256 id12x12 = LAYER_12x12 + xi + yi * GRID_SIZE; uint256 owner12x12 = _owners[id12x12]; if (owner12x12 != 0) { if(!ownAllIndividual) { require(owner12x12 == uint256(from), "not owner of 12x12 quad"); } _owners[id12x12] = 0; } ownerOfAll = (ownAllIndividual || owner12x12 != 0) && ownerOfAll; } } if(set) { if(!ownerOfAll) { require( _owners[quadId] == uint256(from), "not owner of all sub quads not parent quad" ); } _owners[quadId] = uint256(to); return true; } return ownerOfAll || _owners[quadId] == uint256(from); } function _ownerOf(uint256 id) internal view returns (address) { require(id & LAYER == 0, "Invalid token id"); uint256 x = id % GRID_SIZE; uint256 y = id / GRID_SIZE; uint256 owner1x1 = _owners[id]; if (owner1x1 != 0) { return address(owner1x1); // cast to zero } else { address owner3x3 = address(_owners[LAYER_3x3 + (x/3) * 3 + ((y/3) * 3) * GRID_SIZE]); if (owner3x3 != address(0)) { return owner3x3; } else { address owner6x6 = address(_owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE]); if (owner6x6 != address(0)) { return owner6x6; } else { address owner12x12 = address(_owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE]); if (owner12x12 != address(0)) { return owner12x12; } else { return address(_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE]); } } } } } function _ownerAndOperatorEnabledOf(uint256 id) internal view returns (address owner, bool operatorEnabled) { require(id & LAYER == 0, "Invalid token id"); uint256 x = id % GRID_SIZE; uint256 y = id / GRID_SIZE; uint256 owner1x1 = _owners[id]; if (owner1x1 != 0) { owner = address(owner1x1); operatorEnabled = (owner1x1 / 2**255) == 1; } else { address owner3x3 = address(_owners[LAYER_3x3 + (x/3) * 3 + ((y/3) * 3) * GRID_SIZE]); if (owner3x3 != address(0)) { owner = owner3x3; operatorEnabled = false; } else { address owner6x6 = address(_owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE]); if (owner6x6 != address(0)) { owner = owner6x6; operatorEnabled = false; } else { address owner12x12 = address(_owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE]); if (owner12x12 != address(0)) { owner = owner12x12; operatorEnabled = false; } else { owner = address(_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE]); operatorEnabled = false; } } } } } } pragma solidity ^0.5.2; /** Note: The ERC-165 identifier for this interface is 0x5e8bf644. */ interface ERC721MandatoryTokenReceiver { function onERC721BatchReceived( address operator, address from, uint256[] calldata ids, bytes calldata data ) external returns (bytes4); // needs to return 0x4b808c46 function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); // needs to return 0x150b7a02 // needs to implements EIP-165 // function supportsInterface(bytes4 interfaceId) // external // view // returns (bool); } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity 0.5.9; /// @dev minimal ERC2771 handler to keep bytecode-size down. /// based on: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/metatx/ERC2771Context.sol contract ERC2771Handler { address internal _trustedForwarder; function __ERC2771Handler_initialize(address forwarder) internal { _trustedForwarder = forwarder; } function isTrustedForwarder(address forwarder) public view returns (bool) { return forwarder == _trustedForwarder; } function getTrustedForwarder() external view returns (address trustedForwarder) { return _trustedForwarder; } function _msgSender() internal view returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. // solhint-disable-next-line no-inline-assembly assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return msg.sender; } } } pragma solidity ^0.5.2; import "./Admin.sol"; /** * @title PausableWithAdmin * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract PausableWithAdmin is Admin { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the admin to pause, triggers stopped state */ function pause() public onlyAdmin whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the admin to unpause, returns to normal state */ function unpause() public onlyAdmin whenPaused { paused = false; emit Unpause(); } } /* solhint-disable func-order, code-complexity */ pragma solidity 0.5.9; import "../../contracts_common/Libraries/AddressUtils.sol"; import "../../contracts_common/Interfaces/ERC721TokenReceiver.sol"; import "../../contracts_common/Interfaces/ERC721Events.sol"; import "../../contracts_common/BaseWithStorage/SuperOperators.sol"; import "../../contracts_common/BaseWithStorage/MetaTransactionReceiver.sol"; import "../../contracts_common/Interfaces/ERC721MandatoryTokenReceiver.sol"; contract ERC721BaseToken is ERC721Events, SuperOperators, MetaTransactionReceiver { using AddressUtils for address; bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02; bytes4 internal constant _ERC721_BATCH_RECEIVED = 0x4b808c46; bytes4 internal constant ERC165ID = 0x01ffc9a7; bytes4 internal constant ERC721_MANDATORY_RECEIVER = 0x5e8bf644; mapping (address => uint256) public _numNFTPerAddress; mapping (uint256 => uint256) public _owners; mapping (address => mapping(address => bool)) public _operatorsForAll; mapping (uint256 => address) public _operators; bool internal _initialized; modifier initializer() { require(!_initialized, "ERC721BaseToken: Contract already initialized"); _; } function initialize ( address metaTransactionContract, address admin ) public initializer { _admin = admin; _setMetaTransactionProcessor(metaTransactionContract, true); _initialized = true; } function _transferFrom(address from, address to, uint256 id) internal { _numNFTPerAddress[from]--; _numNFTPerAddress[to]++; _owners[id] = uint256(to); emit Transfer(from, to, id); } /** * @notice Return the number of Land owned by an address * @param owner The address to look for * @return The number of Land token owned by the address */ function balanceOf(address owner) external view returns (uint256) { require(owner != address(0), "owner is zero address"); return _numNFTPerAddress[owner]; } function _ownerOf(uint256 id) internal view returns (address) { return address(_owners[id]); } function _ownerAndOperatorEnabledOf(uint256 id) internal view returns (address owner, bool operatorEnabled) { uint256 data = _owners[id]; owner = address(data); operatorEnabled = (data / 2**255) == 1; } /** * @notice Return the owner of a Land * @param id The id of the Land * @return The address of the owner */ function ownerOf(uint256 id) external view returns (address owner) { owner = _ownerOf(id); require(owner != address(0), "token does not exist"); } function _approveFor(address owner, address operator, uint256 id) internal { if(operator == address(0)) { _owners[id] = uint256(owner); // no need to resset the operator, it will be overriden next time } else { _owners[id] = uint256(owner) + 2**255; _operators[id] = operator; } emit Approval(owner, operator, id); } /** * @notice Approve an operator to spend tokens on the sender behalf * @param sender The address giving the approval * @param operator The address receiving the approval * @param id The id of the token */ function approveFor( address sender, address operator, uint256 id ) external { address owner = _ownerOf(id); require(sender != address(0), "sender is zero address"); require( msg.sender == sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender] || _operatorsForAll[sender][msg.sender], "not authorized to approve" ); require(owner == sender, "owner != sender"); _approveFor(owner, operator, id); } /** * @notice Approve an operator to spend tokens on the sender behalf * @param operator The address receiving the approval * @param id The id of the token */ function approve(address operator, uint256 id) external { address owner = _ownerOf(id); require(owner != address(0), "token does not exist"); require( owner == msg.sender || _superOperators[msg.sender] || _operatorsForAll[owner][msg.sender], "not authorized to approve" ); _approveFor(owner, operator, id); } /** * @notice Get the approved operator for a specific token * @param id The id of the token * @return The address of the operator */ function getApproved(uint256 id) external view returns (address) { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "token does not exist"); if (operatorEnabled) { return _operators[id]; } else { return address(0); } } function _checkTransfer(address from, address to, uint256 id) internal view returns (bool isMetaTx) { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "token does not exist"); require(owner == from, "not owner in _checkTransfer"); require(to != address(0), "can't send to zero address"); isMetaTx = msg.sender != from && _metaTransactionContracts[msg.sender]; if (msg.sender != from && !isMetaTx) { require( _superOperators[msg.sender] || _operatorsForAll[from][msg.sender] || (operatorEnabled && _operators[id] == msg.sender), "not approved to transfer" ); } } function _checkInterfaceWith10000Gas(address _contract, bytes4 interfaceId) internal view returns (bool) { bool success; bool result; bytes memory call_data = abi.encodeWithSelector( ERC165ID, interfaceId ); // solium-disable-next-line security/no-inline-assembly assembly { let call_ptr := add(0x20, call_data) let call_size := mload(call_data) let output := mload(0x40) // Find empty storage location using "free memory pointer" mstore(output, 0x0) success := staticcall( 10000, _contract, call_ptr, call_size, output, 0x20 ) // 32 bytes result := mload(output) } // (10000 / 63) "not enough for supportsInterface(...)" // consume all gas, so caller can potentially know that there was not enough gas assert(gasleft() > 158); return success && result; } /** * @notice Transfer a token between 2 addresses * @param from The sender of the token * @param to The recipient of the token * @param id The id of the token */ function transferFrom(address from, address to, uint256 id) external { bool metaTx = _checkTransfer(from, to, id); _transferFrom(from, to, id); if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) { require( _checkOnERC721Received(metaTx ? from : msg.sender, from, to, id, ""), "erc721 transfer rejected by to" ); } } /** * @notice Transfer a token between 2 addresses letting the receiver knows of the transfer * @param from The sender of the token * @param to The recipient of the token * @param id The id of the token * @param data Additional data */ function safeTransferFrom(address from, address to, uint256 id, bytes memory data) public { bool metaTx = _checkTransfer(from, to, id); _transferFrom(from, to, id); if (to.isContract()) { require( _checkOnERC721Received(metaTx ? from : msg.sender, from, to, id, data), "ERC721: transfer rejected by to" ); } } /** * @notice Transfer a token between 2 addresses letting the receiver knows of the transfer * @param from The send of the token * @param to The recipient of the token * @param id The id of the token */ function safeTransferFrom(address from, address to, uint256 id) external { safeTransferFrom(from, to, id, ""); } /** * @notice Transfer many tokens between 2 addresses * @param from The sender of the token * @param to The recipient of the token * @param ids The ids of the tokens * @param data additional data */ function batchTransferFrom(address from, address to, uint256[] calldata ids, bytes calldata data) external { _batchTransferFrom(from, to, ids, data, false); } function _batchTransferFrom(address from, address to, uint256[] memory ids, bytes memory data, bool safe) internal { bool metaTx = msg.sender != from && _metaTransactionContracts[msg.sender]; bool authorized = msg.sender == from || metaTx || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender]; require(from != address(0), "from is zero address"); require(to != address(0), "can't send to zero address"); uint256 numTokens = ids.length; for(uint256 i = 0; i < numTokens; i ++) { uint256 id = ids[i]; (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner == from, "not owner in batchTransferFrom"); require(authorized || (operatorEnabled && _operators[id] == msg.sender), "not authorized"); _owners[id] = uint256(to); emit Transfer(from, to, id); } if (from != to) { _numNFTPerAddress[from] -= numTokens; _numNFTPerAddress[to] += numTokens; } if (to.isContract() && (safe || _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER))) { require( _checkOnERC721BatchReceived(metaTx ? from : msg.sender, from, to, ids, data), "erc721 batch transfer rejected by to" ); } } /** * @notice Transfer many tokens between 2 addresses ensuring the receiving contract has a receiver method * @param from The sender of the token * @param to The recipient of the token * @param ids The ids of the tokens * @param data additional data */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, bytes calldata data) external { _batchTransferFrom(from, to, ids, data, true); } /** * @notice Check if the contract supports an interface * 0x01ffc9a7 is ERC-165 * 0x80ac58cd is ERC-721 * @param id The id of the interface * @return True if the interface is supported */ function supportsInterface(bytes4 id) external pure returns (bool) { return id == 0x01ffc9a7 || id == 0x80ac58cd; } /** * @notice Set the approval for an operator to manage all the tokens of the sender * @param sender The address giving the approval * @param operator The address receiving the approval * @param approved The determination of the approval */ function setApprovalForAllFor( address sender, address operator, bool approved ) external { require(sender != address(0), "Invalid sender address"); require( msg.sender == sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender], "not authorized to approve for all" ); _setApprovalForAll(sender, operator, approved); } /** * @notice Set the approval for an operator to manage all the tokens of the sender * @param operator The address receiving the approval * @param approved The determination of the approval */ function setApprovalForAll(address operator, bool approved) external { _setApprovalForAll(msg.sender, operator, approved); } function _setApprovalForAll( address sender, address operator, bool approved ) internal { require( !_superOperators[operator], "super operator can't have their approvalForAll changed" ); _operatorsForAll[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } /** * @notice Check if the sender approved the operator * @param owner The address of the owner * @param operator The address of the operator * @return The status of the approval */ function isApprovedForAll(address owner, address operator) external view returns (bool isOperator) { return _operatorsForAll[owner][operator] || _superOperators[operator]; } function _burn(address from, address owner, uint256 id) internal { require(from == owner, "not owner"); _owners[id] = 2**160; // cannot mint it again _numNFTPerAddress[from]--; emit Transfer(from, address(0), id); } /// @notice Burns token `id`. /// @param id token which will be burnt. function burn(uint256 id) external { _burn(msg.sender, _ownerOf(id), id); } /// @notice Burn token`id` from `from`. /// @param from address whose token is to be burnt. /// @param id token which will be burnt. function burnFrom(address from, uint256 id) external { require(from != address(0), "Invalid sender address"); (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require( msg.sender == from || _metaTransactionContracts[msg.sender] || (operatorEnabled && _operators[id] == msg.sender) || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "not authorized to burn" ); _burn(from, owner, id); } function _checkOnERC721Received(address operator, address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { bytes4 retval = ERC721TokenReceiver(to).onERC721Received(operator, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } function _checkOnERC721BatchReceived(address operator, address from, address to, uint256[] memory ids, bytes memory _data) internal returns (bool) { bytes4 retval = ERC721MandatoryTokenReceiver(to).onERC721BatchReceived(operator, from, ids, _data); return (retval == _ERC721_BATCH_RECEIVED); } // Empty storage space in contracts for future enhancements // ref: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/issues/13) uint256[49] private __gap; } pragma solidity ^0.5.2; library AddressUtils { function toPayable(address _address) internal pure returns (address payable _payable) { return address(uint160(_address)); } function isContract(address addr) internal view returns (bool) { // for accounts without code, i.e. `keccak256('')`: bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 codehash; // solium-disable-next-line security/no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != accountHash); } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ // solhint-disable-next-line compiler-fixed pragma solidity ^0.5.2; interface ERC721TokenReceiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } pragma solidity ^0.5.2; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://eips.ethereum.org/EIPS/eip-721 */ interface ERC721Events { 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 ); } pragma solidity ^0.5.2; import "./Admin.sol"; contract SuperOperators is Admin { mapping(address => bool) internal _superOperators; event SuperOperator(address superOperator, bool enabled); /// @notice Enable or disable the ability of `superOperator` to transfer tokens of all (superOperator rights). /// @param superOperator address that will be given/removed superOperator right. /// @param enabled set whether the superOperator is enabled or disabled. function setSuperOperator(address superOperator, bool enabled) external { require( msg.sender == _admin, "only admin is allowed to add super operators" ); _superOperators[superOperator] = enabled; emit SuperOperator(superOperator, enabled); } /// @notice check whether address `who` is given superOperator rights. /// @param who The address to query. /// @return whether the address has superOperator rights. function isSuperOperator(address who) public view returns (bool) { return _superOperators[who]; } } pragma solidity ^0.5.2; import "./Admin.sol"; contract MetaTransactionReceiver is Admin{ mapping(address => bool) internal _metaTransactionContracts; event MetaTransactionProcessor(address metaTransactionProcessor, bool enabled); /// @notice Enable or disable the ability of `metaTransactionProcessor` to perform meta-tx (metaTransactionProcessor rights). /// @param metaTransactionProcessor address that will be given/removed metaTransactionProcessor rights. /// @param enabled set whether the metaTransactionProcessor is enabled or disabled. function setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) public { require( msg.sender == _admin, "only admin can setup metaTransactionProcessors" ); _setMetaTransactionProcessor(metaTransactionProcessor, enabled); } function _setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) internal { _metaTransactionContracts[metaTransactionProcessor] = enabled; emit MetaTransactionProcessor(metaTransactionProcessor, enabled); } /// @notice check whether address `who` is given meta-transaction execution rights. /// @param who The address to query. /// @return whether the address has meta-transaction execution rights. function isMetaTransactionProcessor(address who) external view returns(bool) { return _metaTransactionContracts[who]; } } pragma solidity ^0.5.2; contract Admin { address internal _admin; event AdminChanged(address oldAdmin, address newAdmin); /// @notice gives the current administrator of this contract. /// @return the current administrator of this contract. function getAdmin() external view returns (address) { return _admin; } /// @notice change the administrator to be `newAdmin`. /// @param newAdmin address of the new administrator. function changeAdmin(address newAdmin) external { require(msg.sender == _admin, "only admin can change admin"); emit AdminChanged(_admin, newAdmin); _admin = newAdmin; } modifier onlyAdmin() { require (msg.sender == _admin, "only admin allowed"); _; } }
total width of the map return width
function width() external returns(uint256) { return GRID_SIZE; }
1,471,357
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Part: AddressUpgradeable /** * @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 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); } } } } // Part: ICVXBribes interface ICVXBribes { function getReward(address _account, address _token) external; function getRewards(address _account, address[] calldata _tokens) external; } // Part: IController interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // Part: ICvxLocker interface ICvxLocker { function maximumBoostPayment() external view returns (uint256); function lock( address _account, uint256 _amount, uint256 _spendRatio ) external; function getReward(address _account, bool _stake) external; //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount); // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount); // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks( bool _relock, uint256 _spendRatio, address _withdrawTo ) external; // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external; } // Part: IDelegateRegistry ///@dev Snapshot Delegate registry so we can delegate voting to XYZ interface IDelegateRegistry { function setDelegate(bytes32 id, address delegate) external; function delegation(address, bytes32) external returns (address); } // Part: IERC20Upgradeable /** * @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 ); } // Part: ISettV4 interface ISettV4 { function deposit(uint256 _amount) external; function depositFor(address _recipient, uint256 _amount) external; function withdraw(uint256 _amount) external; function balance() external view returns (uint256); function getPricePerFullShare() external view returns (uint256); function balanceOf(address) external view returns (uint256); } // Part: IUniswapRouterV2 interface IUniswapRouterV2 { function factory() external view 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 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); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); 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); } // Part: IVotiumBribes interface IVotiumBribes { struct claimParam { address token; uint256 index; uint256 amount; bytes32[] merkleProof; } function claimMulti(address account, claimParam[] calldata claims) external; function claim(address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external; } // Part: Initializable /** * @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) { // 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // Part: MathUpgradeable /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } } // Part: SafeMathUpgradeable /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: ContextUpgradeable /* * @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; } // Part: SafeERC20Upgradeable /** * @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" ); } } } // Part: SettAccessControl /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require( msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist" ); } function _onlyAuthorizedActors() internal view { require( msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors" ); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // Part: PausableUpgradeable /** * @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 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 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; } // Part: BaseStrategy /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require( msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController" ); } function _onlyAuthorizedPausers() internal view { require( msg.sender == guardian || msg.sender == governance, "onlyPausers" ); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public view virtual returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public view virtual returns (bool) { return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require( _withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee" ); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require( _performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee" ); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require( _performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee" ); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require( _threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold" ); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require( diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold" ); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer( IController(controller).rewards(), fee ); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens( balance, 0, path, address(this), now ); } function _swapEthIn(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}( 0, path, address(this), now ); } function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH( balance, 0, path, address(this), now ); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_uniswap(address token0, address token1) internal virtual { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity( token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp ); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _amount) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() external view virtual returns (address[] memory); /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external pure virtual returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view virtual returns (uint256); uint256[49] private __gap; } // File: MyStrategy.sol /** * CHANGELOG * V1.0 Initial Release, can lock * V1.1 Update to handle rewards which are sent to a multisig * V1.2 Update to emit badger, all other rewards are sent to multisig * V1.3 Updated Address to claim CVX Rewards * V1.4 Updated Claiming mechanism to allow claiming any token (using difference in balances) */ contract MyStrategy is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; uint256 public constant MAX_BPS = 10_000; // address public want // Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow address public lpComponent; // Token we provide liquidity with address public reward; // Token we farm and swap to want / lpComponent address public constant BADGER_TREE = 0x660802Fc641b154aBA66a62137e71f331B6d787A; IDelegateRegistry public constant SNAPSHOT = IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446); // The initial DELEGATE for the strategy // NOTE we can change it by using manualSetDelegate below address public constant DELEGATE = 0x14F83fF95D4Ec5E8812DDf42DA1232b0ba1015e6; bytes32 public constant DELEGATED_SPACE = 0x6376782e65746800000000000000000000000000000000000000000000000000; ISettV4 public constant CVXCRV_VAULT = ISettV4(0x2B5455aac8d64C14786c3a29858E43b5945819C0); // NOTE: At time of publishing, this contract is under audit ICvxLocker public constant LOCKER = ICvxLocker(0xD18140b4B819b895A3dba5442F959fA44994AF50); ICVXBribes public constant CVX_EXTRA_REWARDS = ICVXBribes(0xDecc7d761496d30F30b92Bdf764fb8803c79360D); IVotiumBribes public constant VOTIUM_BRIBE_CLAIMER = IVotiumBribes(0x378Ba9B73309bE80BF4C2c027aAD799766a7ED5A); // We hardcode, an upgrade is required to change this as it's a meaningful change address public constant BRIBES_RECEIVER = 0x6F76C6A1059093E21D8B1C13C4e20D8335e2909F; // We emit badger through the tree to the vault holders address public constant BADGER = 0x3472A5A71965499acd81997a54BBA8D852C6E53d; bool public withdrawalSafetyCheck = false; bool public harvestOnRebalance = false; // If nothing is unlocked, processExpiredLocks will revert bool public processLocksOnReinvest = false; bool public processLocksOnRebalance = false; // Used to signal to the Badger Tree that rewards where sent to it event TreeDistribution( address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event RewardsCollected( address token, uint256 amount ); event PerformanceFeeGovernance( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event PerformanceFeeStrategist( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[3] memory _wantConfig, uint256[3] memory _feeConfig ) public initializer { __BaseStrategy_init( _governance, _strategist, _controller, _keeper, _guardian ); /// @dev Add config here want = _wantConfig[0]; lpComponent = _wantConfig[1]; reward = _wantConfig[2]; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; IERC20Upgradeable(reward).safeApprove(address(CVXCRV_VAULT), type(uint256).max); /// @dev do one off approvals here // Permissions for Locker IERC20Upgradeable(want).safeApprove(address(LOCKER), type(uint256).max); // Delegate voting to DELEGATE SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE); } /// ===== Extra Functions ===== /// @dev Change Delegation to another address function manualSetDelegate(address delegate) external { _onlyGovernance(); // Set delegate is enough as it will clear previous delegate automatically SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate); } ///@dev Should we check if the amount requested is more than what we can return on withdrawal? function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external { _onlyGovernance(); withdrawalSafetyCheck = newWithdrawalSafetyCheck; } ///@dev Should we harvest before doing manual rebalancing ///@notice you most likely want to skip harvest if everything is unlocked, or there's something wrong and you just want out function setHarvestOnRebalance(bool newHarvestOnRebalance) external { _onlyGovernance(); harvestOnRebalance = newHarvestOnRebalance; } ///@dev Should we processExpiredLocks during reinvest? function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) external { _onlyGovernance(); processLocksOnReinvest = newProcessLocksOnReinvest; } ///@dev Should we processExpiredLocks during manualRebalance? function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance) external { _onlyGovernance(); processLocksOnRebalance = newProcessLocksOnRebalance; } /// *** Bribe Claiming *** /// @dev given a token address, claim that as reward from CVX Extra Rewards /// @notice funds are transfered to the hardcoded address BRIBES_RECEIVER function claimBribeFromConvex (address token) external { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforeBalance = IERC20Upgradeable(token).balanceOf(address(this)); // Claim reward for token CVX_EXTRA_REWARDS.getReward(address(this), token); uint256 afterBalance = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, afterBalance.sub(beforeBalance)); require(beforeVaultBalance == _getBalance(), "Balance can't change"); } /// @dev given a list of token addresses, claim that as reward from CVX Extra Rewards /// @notice funds are transfered to the hardcoded address BRIBES_RECEIVER function claimBribesFromConvex(address[] calldata tokens) external { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); // Revert if you try to claim a protected token, this is to avoid rugging // Also checks balance diff uint256 length = tokens.length; uint256[] memory beforeBalance = new uint256[](length); for(uint i = 0; i < length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } // NOTE: If we end up getting bribes in form or protected tokens, we'll have to change // Claim reward for tokens CVX_EXTRA_REWARDS.getRewards(address(this), tokens); // Send reward to Multisig for(uint x = 0; x < length; x++){ _handleRewardTransfer(tokens[x], IERC20Upgradeable(tokens[x]).balanceOf(address(this)).sub(beforeBalance[x])); } require(beforeVaultBalance == _getBalance(), "Balance can't change"); } /// @dev given the votium data (available at: https://github.com/oo-00/Votium/tree/main/merkle) /// @dev allows claiming of rewards, badger is sent to tree function claimBribeFromVotium( address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); // Revert if you try to claim a protected token, this is to avoid rugging // NOTE: If we end up getting bribes in form or protected tokens, we'll have to change uint256 beforeBalance = IERC20Upgradeable(token).balanceOf(address(this)); VOTIUM_BRIBE_CLAIMER.claim(token, index, account, amount, merkleProof); uint256 afterBalance = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, afterBalance.sub(beforeBalance)); require(beforeVaultBalance == _getBalance(), "Balance can't change"); } /// @dev given the votium data (available at: https://github.com/oo-00/Votium/tree/main/merkle) /// @dev allows claiming of multiple rewards rewards, badger is sent to tree function claimBribesFromVotium( address account, address[] calldata tokens, uint256[] calldata indexes, uint256[] calldata amounts, bytes32[][] calldata merkleProofs ) external { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); // Revert if you try to claim a protected token, this is to avoid rugging require(tokens.length == indexes.length && tokens.length == amounts.length && tokens.length == merkleProofs.length, "Length Mismatch"); // tokens.length = length, can't declare var as stack too deep uint256[] memory beforeBalance = new uint256[](tokens.length); for(uint i = 0; i < tokens.length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } // NOTE: If we end up getting bribes in form or protected tokens, we'll have to change IVotiumBribes.claimParam[] memory request = new IVotiumBribes.claimParam[](tokens.length); for(uint x = 0; x < tokens.length; x++){ request[x] = IVotiumBribes.claimParam({ token: tokens[x], index: indexes[x], amount: amounts[x], merkleProof: merkleProofs[x] }); } VOTIUM_BRIBE_CLAIMER.claimMulti(account, request); for(uint i = 0; i < tokens.length; i++){ _handleRewardTransfer(tokens[i], IERC20Upgradeable(tokens[i]).balanceOf(address(this)).sub(beforeBalance[i])); } require(beforeVaultBalance == _getBalance(), "Balance can't change"); } /// @dev Function to move rewards that are not protected /// @notice Only not protected, moves the whole amount using _handleRewardTransfer /// @notice because token paths are harcoded, this function is safe to be called by anyone function sweepRewardToken(address token) public { _onlyGovernanceOrStrategist(); _onlyNotProtectedTokens(token); uint256 toSend = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, toSend); } /// @dev Bulk function for sweepRewardToken function sweepRewards(address[] calldata tokens) external { uint256 length = tokens.length; for(uint i = 0; i < length; i++){ sweepRewardToken(tokens[i]); } } /// *** Handling of rewards *** function _handleRewardTransfer(address token, uint256 amount) internal { // NOTE: BADGER is emitted through the tree if (token == BADGER){ _sendBadgerToTree(amount); } else { // NOTE: All other tokens are sent to multisig _sentTokenToBribesReceiver(token, amount); } } /// @dev Send funds to the bribes receiver function _sentTokenToBribesReceiver(address token, uint256 amount) internal { IERC20Upgradeable(token).safeTransfer(BRIBES_RECEIVER, amount); emit RewardsCollected(token, amount); } /// @dev Send the BADGER token to the badgerTree function _sendBadgerToTree(uint256 amount) internal { IERC20Upgradeable(BADGER).safeTransfer(BADGER_TREE, amount); emit TreeDistribution(BADGER, amount, block.number, block.timestamp); } /// @dev Get the current Vault.balance /// @notice this is reflexive, a change in the strat will change the balance in the vault function _getBalance() internal returns (uint256) { ISettV4 vault = ISettV4(IController(controller).vaults(want)); return vault.balance(); } /// ===== View Functions ===== function getBoostPayment() public view returns(uint256){ uint256 maximumBoostPayment = LOCKER.maximumBoostPayment(); require(maximumBoostPayment <= 1500, "over max payment"); //max 15% return maximumBoostPayment; } /// @dev Specify the name of the strategy function getName() external pure override returns (string memory) { return "veCVX Voting Strategy"; } /// @dev Specify the version of the Strategy, for upgrades function version() external pure returns (string memory) { return "1.4"; } /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view override returns (uint256) { // Return the balance in locker return LOCKER.lockedBalanceOf(address(this)); } /// @dev Returns true if this strategy requires tending function isTendable() public view override returns (bool) { return false; } // @dev These are the tokens that cannot be moved except by the vault function getProtectedTokens() public view override returns (address[] memory) { address[] memory protectedTokens = new address[](3); protectedTokens[0] = want; protectedTokens[1] = lpComponent; protectedTokens[2] = reward; return protectedTokens; } /// ===== Internal Core Implementations ===== /// @dev security check to avoid moving tokens that would cause a rugpull, edit based on strat function _onlyNotProtectedTokens(address _asset) internal override { address[] memory protectedTokens = getProtectedTokens(); for (uint256 x = 0; x < protectedTokens.length; x++) { require( address(protectedTokens[x]) != _asset, "Asset is protected" ); } } /// @dev invest the amount of want /// @notice When this function is called, the controller has already sent want to this /// @notice Just get the current balance and then invest accordingly function _deposit(uint256 _amount) internal override { // Lock tokens for 16 weeks, send credit to strat, always use max boost cause why not? LOCKER.lock(address(this), _amount, getBoostPayment()); } /// @dev utility function to withdraw all CVX that we can from the lock function prepareWithdrawAll() external { manualProcessExpiredLocks(); } /// @dev utility function to withdraw everything for migration /// @dev NOTE: You cannot call this unless you have rebalanced to have only CVX left in the vault function _withdrawAll() internal override { //NOTE: This probably will always fail unless we have all tokens expired require( LOCKER.lockedBalanceOf(address(this)) == 0 && LOCKER.balanceOf(address(this)) == 0, "You have to wait for unlock or have to manually rebalance out of it" ); // Make sure to call prepareWithdrawAll before _withdrawAll } /// @dev withdraw the specified amount of want, liquidate from lpComponent to want, paying off any necessary debt for the conversion function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = balanceOfWant(); if(_amount > max){ // Try to unlock, as much as possible // @notice Reverts if no locks expired LOCKER.processExpiredLocks(false); max = balanceOfWant(); } if (withdrawalSafetyCheck) { require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" ); // 20 BP of slippage } if (_amount > max) { return max; } return _amount; } /// @dev Harvest from strategy mechanics, realizing increase in underlying position function harvest() public whenNotPaused returns (uint256) { _onlyAuthorizedActors(); uint256 _beforeReward = IERC20Upgradeable(reward).balanceOf(address(this)); // Get cvxCRV LOCKER.getReward(address(this), false); // Rewards Math uint256 earnedReward = IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeReward); uint256 cvxCrvToGovernance = earnedReward.mul(performanceFeeGovernance).div(MAX_FEE); if(cvxCrvToGovernance > 0){ CVXCRV_VAULT.depositFor(IController(controller).rewards(), cvxCrvToGovernance); emit PerformanceFeeGovernance(IController(controller).rewards(), address(CVXCRV_VAULT), cvxCrvToGovernance, block.number, block.timestamp); } uint256 cvxCrvToStrategist = earnedReward.mul(performanceFeeStrategist).div(MAX_FEE); if(cvxCrvToStrategist > 0){ CVXCRV_VAULT.depositFor(strategist, cvxCrvToStrategist); emit PerformanceFeeStrategist(strategist, address(CVXCRV_VAULT), cvxCrvToStrategist, block.number, block.timestamp); } // Send rest of earned to tree //We send all rest to avoid dust and avoid protecting the token uint256 cvxCrvToTree = IERC20Upgradeable(reward).balanceOf(address(this)); CVXCRV_VAULT.depositFor(BADGER_TREE, cvxCrvToTree); emit TreeDistribution(address(CVXCRV_VAULT), cvxCrvToTree, block.number, block.timestamp); /// @dev Harvest event that every strategy MUST have, see BaseStrategy emit Harvest(earnedReward, block.number); /// @dev Harvest must return the amount of want increased return earnedReward; } /// @dev Rebalance, Compound or Pay off debt here function tend() external whenNotPaused { revert("no op"); // NOTE: For now tend is replaced by manualRebalance } /// MANUAL FUNCTIONS /// /// @dev manual function to reinvest all CVX that was locked function reinvest() external whenNotPaused returns (uint256) { _onlyGovernance(); if (processLocksOnReinvest) { // Withdraw all we can LOCKER.processExpiredLocks(false); } // Redeposit all into veCVX uint256 toDeposit = IERC20Upgradeable(want).balanceOf(address(this)); // Redeposit into veCVX _deposit(toDeposit); return toDeposit; } /// @dev process all locks, to redeem function manualProcessExpiredLocks() public whenNotPaused { _onlyGovernance(); LOCKER.processExpiredLocks(false); // Unlock veCVX that is expired and redeem CVX back to this strat } /// @dev Send all available CVX to the Vault /// @notice you can do this so you can earn again (re-lock), or just to add to the redemption pool function manualSendCVXToVault() external whenNotPaused { _onlyGovernance(); uint256 cvxAmount = IERC20Upgradeable(want).balanceOf(address(this)); _transferToVault(cvxAmount); } /// @dev use the currently available CVX to lock /// @notice toLock = 0, lock nothing, deposit in CVX as much as you can /// @notice toLock = 10_000, lock everything (CVX) you have function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { // manualRebalance will revert if you have no expired locks LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } // Token that is highly liquid uint256 balanceOfWant = IERC20Upgradeable(want).balanceOf(address(this)); // Locked CVX in the locker uint256 balanceInLock = LOCKER.balanceOf(address(this)); uint256 totalCVXBalance = balanceOfWant.add(balanceInLock); // Amount we want to have in lock uint256 newLockAmount = totalCVXBalance.mul(toLock).div(MAX_BPS); // We can't unlock enough, no-op if (newLockAmount <= balanceInLock) { return; } // If we're continuing, then we are going to lock something uint256 cvxToLock = newLockAmount.sub(balanceInLock); // We only lock up to the available CVX uint256 maxCVX = IERC20Upgradeable(want).balanceOf(address(this)); if (cvxToLock > maxCVX) { // Just lock what we can LOCKER.lock(address(this), maxCVX, getBoostPayment()); } else { // Lock proper LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } // If anything left, send to vault uint256 cvxLeft = IERC20Upgradeable(want).balanceOf(address(this)); if(cvxLeft > 0){ _transferToVault(cvxLeft); } } }
invest the amount of want When this function is called, the controller has already sent want to this Just get the current balance and then invest accordingly Lock tokens for 16 weeks, send credit to strat, always use max boost cause why not?
function _deposit(uint256 _amount) internal override { LOCKER.lock(address(this), _amount, getBoostPayment()); }
2,045,362
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @artist: Anna Ridler /// @author: manifold.xyz import "@prb/math/contracts/PRBMathSD59x18.sol"; import "./libraries/Trigonometry.sol"; import "./libraries/BokkyPooBahsDateTimeLibrary.sol"; import "./dynamic/DynamicArweaveHash.sol"; import "./extensions/ERC721/IERC721CreatorExtensionApproveTransfer.sol"; contract AnnoOxypetalum is DynamicArweaveHash, IERC721CreatorExtensionApproveTransfer { using PRBMathSD59x18 for int256; uint256 private _baseTokenId; uint8 private _seasonOnLastTransfer; // Seasons uint8 constant private _WINTER = 0; uint8 constant private _SPRING = 1; uint8 constant private _SUMMER = 2; uint8 constant private _FALL = 3; // Constants int256 constant private _DAY_IN_SECONDS = 86400000000000000000000; int256 constant private _JULIAN_EPOCH = 2440587500000000000000000; int256 constant private _JULIAN_2000 = 2451545000000000000000000; int256 constant private _JULIAN_CENTURY = 36525000000000000000000; int256 immutable _D2R = PRBMathSD59x18.pi().div(180000000000000000000); // In-memory Arrays function _springConstants() private pure returns (int256[5] memory) { int256[5] memory constants = [int(2451623809840000000000000), 365242374040000000000000, 51690000000000000, -4110000000000000, -570000000000000]; return constants; } function _summerConstants() private pure returns (int256[5] memory) { int256[5] memory constants = [int(2451716567670000000000000), 365241626030000000000000, 3250000000000000, 8880000000000000, -300000000000000]; return constants; } function _fallConstants() private pure returns (int256[5] memory) { int256[5] memory constants = [int(2451810217150000000000000), 365242017670000000000000, -115750000000000000, 3370000000000000, 780000000000000]; return constants; } function _winterConstants() private pure returns (int256[5] memory) { int256[5] memory constants = [int(2451900059520000000000000), 365242740490000000000000, -62230000000000000, -8230000000000000, 320000000000000]; return constants; } function _termsConstants() private pure returns (int256[3][24] memory) { int256[3][24] memory constants = [ [int(485000000000000000000), 324960000000000000000, 1934136000000000000000], [int(203000000000000000000), 337230000000000000000, 32964467000000000000000], [int(199000000000000000000), 342080000000000000000, 20186000000000000000], [int(182000000000000000000), 27850000000000000000, 445267112000000000000000], [int(156000000000000000000), 73140000000000000000, 45036886000000000000000], [int(136000000000000000000), 171520000000000000000, 22518443000000000000000], [int(77000000000000000000), 222540000000000000000, 65928934000000000000000], [int(74000000000000000000), 296720000000000000000, 3034906000000000000000], [int(70000000000000000000), 243580000000000000000, 9037513000000000000000], [int(58000000000000000000), 119810000000000000000, 33718147000000000000000], [int(52000000000000000000), 297170000000000000000, 150678000000000000000], [int(50000000000000000000), 21020000000000000000, 2281226000000000000000], [int(45000000000000000000), 247540000000000000000, 29929562000000000000000], [int(44000000000000000000), 325150000000000000000, 31555956000000000000000], [int(29000000000000000000), 60930000000000000000, 4443417000000000000000], [int(18000000000000000000), 155120000000000000000, 67555328000000000000000], [int(17000000000000000000), 288790000000000000000, 4562452000000000000000], [int(16000000000000000000), 198040000000000000000, 62894029000000000000000], [int(14000000000000000000), 199760000000000000000, 31436921000000000000000], [int(12000000000000000000), 95390000000000000000, 14577848000000000000000], [int(12000000000000000000), 287110000000000000000, 31931756000000000000000], [int(12000000000000000000), 320810000000000000000, 34777259000000000000000], [int(9000000000000000000), 227730000000000000000, 1222114000000000000000], [int(8000000000000000000), 15450000000000000000, 16859074000000000000000] ]; return constants; } constructor(address creator) ERC721SingleCreatorExtension(creator) {} function supportsInterface(bytes4 interfaceId) public view virtual override(DynamicArweaveHash, IERC165) returns (bool) { return interfaceId == type(IERC721CreatorExtensionApproveTransfer).interfaceId || super.supportsInterface(interfaceId); } function mint(address to) public virtual onlyOwner returns(uint256) { require(_baseTokenId == 0, "Already minted"); _baseTokenId = _mint(to); return _baseTokenId; } function setApproveTransfer(address creator, bool enabled) public override onlyOwner { IERC721CreatorCore(creator).setApproveTransferExtension(enabled); } function approveTransfer(address, address, uint256) public override returns (bool) { require(msg.sender == _creator, "Invalid requester"); _seasonOnLastTransfer = _currentSeason(); return true; } function tokenURI(address, uint256 tokenId) external view override returns (string memory) { return string(abi.encodePacked( 'data:application/json;utf8,{"name":"',_getName(), '", "description":"',_getDescription(), '", "image":"https://arweave.net/',_getImageHash(tokenId), '", "animation_url":"https://arweave.net/',_getAnimationHash(tokenId), '", "attributes":[', _wrapTrait("Artist", "Anna Ridler"), ']', '}')); } function _getName() internal pure override returns(string memory) { return "Anno oxypetalum"; } function _getDescription() internal pure override returns(string memory) { return "Anno oxypetalum (literally \\\"the year of the pointed petals\\\") is a clock made of the flowers of " "night-blooming cacti, tracking the amount of light across one year. Each flower represents 10 minutes, " "each second approximately 2 days. Over the course of the piece the flowers fade in and out as the light " "ebbs and flows across the seasons. The timing of dawn and dusk is precisely accurate for London starting " "at the 2021 winter solstice. A third level of time is also incorporated into the work - when the piece " "is sold, the smart contract is programmed to start the video at the beginning of the season in which it " "was sold. The smart contract is able to accurately compute the solstices and equinoxes until the year " "3000. It is inspired by plants\' chrono-biological clocks, by which they bloom and close at fixed times " "of day. Plants behave this way regardless of external stimuli - a night-blooming cactus, for example, " "will only bloom at night, even if it is exposed to darkness during the daytime and light at night; a " "morning glory moved into permanent darkness will still flower in the mornings. The work call backs to " "Carl Linnaeus\' idea of a horologium florae or floral clock, proposed in his Philosophia Botanica in " "1751 after observing the phenomenon of certain flowers opening and closing at set times of the day, " "and harkens back to an earlier, medieval way of delineating time according to the amount of daylight " "present, before the advent of modern timekeeping."; } function _getImageHash(uint256) internal view override returns(string memory) { return imageArweaveHashes[_seasonOnLastTransfer]; } function _getAnimationHash(uint256) internal view override returns(string memory) { return animationArweaveHashes[_seasonOnLastTransfer]; } function _wrapTrait(string memory trait, string memory value) internal pure returns(string memory) { return string(abi.encodePacked( '{"trait_type":"', trait, '","value":"', value, '"}' )); } function _currentSeason() private view returns (uint8) { int256 year = _timestampToYear(block.timestamp); int256 month = _timestampToMonth(block.timestamp); int256 julianDay = _timestampToJulianDay(block.timestamp); int256[3][24] memory terms = _termsConstants(); if (month < 3) { return _WINTER; } else if (month == 3) { return julianDay < _springEquinox(year, terms) ? _WINTER : _SPRING; } else if (month < 6) { return _SPRING; } else if (month == 6) { return julianDay < _summerSolstice(year, terms) ? _SPRING : _SUMMER; } else if (month < 9) { return _SUMMER; } else if (month == 9) { return julianDay < _fallEquinox(year, terms) ? _SUMMER : _FALL; } else if (month < 12) { return _FALL; } return julianDay < _winterSolstice(year, terms) ? _FALL : _WINTER; } function _springEquinox(int256 year, int256[3][24] memory terms) private view returns (int256) { return _eventJulianDay(year - 2000000000000000000000, _springConstants(), terms); } function _summerSolstice(int256 year, int256[3][24] memory terms) private view returns (int256) { return _eventJulianDay(year - 2000000000000000000000, _summerConstants(), terms); } function _fallEquinox(int256 year, int256[3][24] memory terms) private view returns (int256) { return _eventJulianDay(year - 2000000000000000000000, _fallConstants(), terms); } function _winterSolstice(int256 year, int256[3][24] memory terms) private view returns (int256) { return _eventJulianDay(year - 2000000000000000000000, _winterConstants(), terms); } function _eventJulianDay(int256 year, int256[5] memory eventConstants, int256[3][24] memory terms) private view returns (int256) { int256 J0 = _horner(year.mul(1000000000000000), eventConstants); int256 T = _J2000Century(J0); int256 W = _D2R.mul(T).mul(35999373000000000000000) - _D2R.mul(2470000000000000000); int256 dL = 1000000000000000000 + Trigonometry.cos(uint(W)).mul(33400000000000000) + Trigonometry.cos(uint(W.mul(2000000000000000000))).mul(700000000000000); int256 S = 0; for (uint256 i = 24; i > 0; i--) { int256[3] memory t = terms[i-1]; S += t[0].mul(Trigonometry.cos(uint((t[1] + T.mul(t[2])).mul(_D2R)))); } return J0 + S.div(dL).mul(10000000000000); } function _horner(int256 x, int256[5] memory c) private pure returns (int256) { uint256 i = c.length - 1; int256 y = c[i]; while (i > 0) { i--; y = y.mul(x) + c[i]; } return y; } function _J2000Century(int256 jde) private pure returns (int256) { return (jde - _JULIAN_2000).div(_JULIAN_CENTURY); } function _timestampToYear(uint256 timestamp) private pure returns (int256) { return PRBMathSD59x18.fromInt(int(BokkyPooBahsDateTimeLibrary.getYear(timestamp))); } function _timestampToMonth(uint256 timestamp) private pure returns (int256) { return int(BokkyPooBahsDateTimeLibrary.getMonth(timestamp)); } function _timestampToJulianDay(uint256 timestamp) private pure returns (int256) { return PRBMathSD59x18.fromInt(int(timestamp)).div(_DAY_IN_SECONDS) + _JULIAN_EPOCH; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * Implement this if you want your extension to approve a transfer */ interface IERC721CreatorExtensionApproveTransfer is IERC165 { /** * @dev Set whether or not the creator will check the extension for approval of token transfer */ function setApproveTransfer(address creator, bool enabled) external; /** * @dev Called by creator contract to approve a transfer */ function approveTransfer(address from, address to, uint256 tokenId) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/CreatorExtension.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/ICreatorExtensionTokenURI.sol"; import "../libraries/single-creator/ERC721/ERC721SingleCreatorExtension.sol"; /** * Extension which allows for the creation of NFTs with dynamically changing image/animation metadata */ abstract contract DynamicArweaveHash is ERC721SingleCreatorExtension, CreatorExtension, Ownable, ICreatorExtensionTokenURI { using Strings for uint256; string[] public imageArweaveHashes; string[] public animationArweaveHashes; function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorExtension, IERC165) returns (bool) { return interfaceId == type(ICreatorExtensionTokenURI).interfaceId || super.supportsInterface(interfaceId); } function tokenURI(address, uint256 tokenId) external view virtual override returns (string memory) { string memory uri = string(abi.encodePacked('data:application/json;utf8,{"name":"', _getName(), '","description":"', _getDescription())); if (imageArweaveHashes.length > 0) { uri = string(abi.encodePacked(uri, '", "image":"https://arweave.net/', _getImageHash(tokenId))); } if (animationArweaveHashes.length > 0) { uri = string(abi.encodePacked(uri, '", "animation_url":"https://arweave.net/', _getAnimationHash(tokenId))); } uri = string(abi.encodePacked(uri, '"}')); return uri; } function _mint(address to) internal returns(uint256) { return IERC721CreatorCore(_creator).mintExtension(to); } function _getName() internal view virtual returns(string memory); function _getDescription() internal view virtual returns(string memory); function _getImageHash(uint256 tokenId) internal view virtual returns(string memory); function _getAnimationHash(uint256 tokenId) internal view virtual returns(string memory); function setImageArweaveHashes(string[] memory _arweaveHashes) external virtual onlyOwner { imageArweaveHashes = _arweaveHashes; } function setAnimationAreaveHashes(string[] memory _arweaveHashes) external virtual onlyOwner { animationArweaveHashes = _arweaveHashes; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // https://aa.usno.navy.mil/faq/JD_formula.html // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @notice Solidity library offering basic trigonometry functions where inputs and outputs are * integers. Inputs are specified in radians scaled by 1e18, and similarly outputs are scaled by 1e18. * * This implementation is based off the Solidity trigonometry library written by Lefteris Karapetsas * which can be found here: https://github.com/Sikorkaio/sikorka/blob/e75c91925c914beaedf4841c0336a806f2b5f66d/contracts/trigonometry.sol * * Compared to Lefteris' implementation, this version makes the following changes: * - Uses a 32 bits instead of 16 bits for improved accuracy * - Updated for Solidity 0.8.x * - Various gas optimizations * - Change inputs/outputs to standard trig format (scaled by 1e18) instead of requiring the * integer format used by the algorithm * * Lefertis' implementation is based off Dave Dribin's trigint C library * http://www.dribin.org/dave/trigint/ * * Which in turn is based from a now deleted article which can be found in the Wayback Machine: * http://web.archive.org/web/20120301144605/http://www.dattalo.com/technical/software/pic/picsine.html */ library Trigonometry { // Table index into the trigonometric table uint256 constant INDEX_WIDTH = 8; // Interpolation between successive entries in the table uint256 constant INTERP_WIDTH = 16; uint256 constant INDEX_OFFSET = 28 - INDEX_WIDTH; uint256 constant INTERP_OFFSET = INDEX_OFFSET - INTERP_WIDTH; uint32 constant ANGLES_IN_CYCLE = 1073741824; uint32 constant QUADRANT_HIGH_MASK = 536870912; uint32 constant QUADRANT_LOW_MASK = 268435456; uint256 constant SINE_TABLE_SIZE = 256; // Pi as an 18 decimal value, which is plenty of accuracy: "For JPL's highest accuracy calculations, which are for // interplanetary navigation, we use 3.141592653589793: https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/ uint256 constant PI = 3141592653589793238; uint256 constant TWO_PI = 2 * PI; uint256 constant PI_OVER_TWO = PI / 2; // The constant sine lookup table was generated by generate_trigonometry.py. We must use a constant // bytes array because constant arrays are not supported in Solidity. Each entry in the lookup // table is 4 bytes. Since we're using 32-bit parameters for the lookup table, we get a table size // of 2^(32/4) + 1 = 257, where the first and last entries are equivalent (hence the table size of // 256 defined above) uint8 constant entry_bytes = 4; // each entry in the lookup table is 4 bytes uint256 constant entry_mask = ((1 << 8*entry_bytes) - 1); // mask used to cast bytes32 -> lookup table entry bytes constant sin_table = hex"00_00_00_00_00_c9_0f_88_01_92_1d_20_02_5b_26_d7_03_24_2a_bf_03_ed_26_e6_04_b6_19_5d_05_7f_00_35_06_47_d9_7c_07_10_a3_45_07_d9_5b_9e_08_a2_00_9a_09_6a_90_49_0a_33_08_bc_0a_fb_68_05_0b_c3_ac_35_0c_8b_d3_5e_0d_53_db_92_0e_1b_c2_e4_0e_e3_87_66_0f_ab_27_2b_10_72_a0_48_11_39_f0_cf_12_01_16_d5_12_c8_10_6e_13_8e_db_b1_14_55_76_b1_15_1b_df_85_15_e2_14_44_16_a8_13_05_17_6d_d9_de_18_33_66_e8_18_f8_b8_3c_19_bd_cb_f3_1a_82_a0_25_1b_47_32_ef_1c_0b_82_6a_1c_cf_8c_b3_1d_93_4f_e5_1e_56_ca_1e_1f_19_f9_7b_1f_dc_dc_1b_20_9f_70_1c_21_61_b3_9f_22_23_a4_c5_22_e5_41_af_23_a6_88_7e_24_67_77_57_25_28_0c_5d_25_e8_45_b6_26_a8_21_85_27_67_9d_f4_28_26_b9_28_28_e5_71_4a_29_a3_c4_85_2a_61_b1_01_2b_1f_34_eb_2b_dc_4e_6f_2c_98_fb_ba_2d_55_3a_fb_2e_11_0a_62_2e_cc_68_1e_2f_87_52_62_30_41_c7_60_30_fb_c5_4d_31_b5_4a_5d_32_6e_54_c7_33_26_e2_c2_33_de_f2_87_34_96_82_4f_35_4d_90_56_36_04_1a_d9_36_ba_20_13_37_6f_9e_46_38_24_93_b0_38_d8_fe_93_39_8c_dd_32_3a_40_2d_d1_3a_f2_ee_b7_3b_a5_1e_29_3c_56_ba_70_3d_07_c1_d5_3d_b8_32_a5_3e_68_0b_2c_3f_17_49_b7_3f_c5_ec_97_40_73_f2_1d_41_21_58_9a_41_ce_1e_64_42_7a_41_d0_43_25_c1_35_43_d0_9a_ec_44_7a_cd_50_45_24_56_bc_45_cd_35_8f_46_75_68_27_47_1c_ec_e6_47_c3_c2_2e_48_69_e6_64_49_0f_57_ee_49_b4_15_33_4a_58_1c_9d_4a_fb_6c_97_4b_9e_03_8f_4c_3f_df_f3_4c_e1_00_34_4d_81_62_c3_4e_21_06_17_4e_bf_e8_a4_4f_5e_08_e2_4f_fb_65_4c_50_97_fc_5e_51_33_cc_94_51_ce_d4_6e_52_69_12_6e_53_02_85_17_53_9b_2a_ef_54_33_02_7d_54_ca_0a_4a_55_60_40_e2_55_f5_a4_d2_56_8a_34_a9_57_1d_ee_f9_57_b0_d2_55_58_42_dd_54_58_d4_0e_8c_59_64_64_97_59_f3_de_12_5a_82_79_99_5b_10_35_ce_5b_9d_11_53_5c_29_0a_cc_5c_b4_20_df_5d_3e_52_36_5d_c7_9d_7b_5e_50_01_5d_5e_d7_7c_89_5f_5e_0d_b2_5f_e3_b3_8d_60_68_6c_ce_60_ec_38_2f_61_6f_14_6b_61_f1_00_3e_62_71_fa_68_62_f2_01_ac_63_71_14_cc_63_ef_32_8f_64_6c_59_bf_64_e8_89_25_65_63_bf_91_65_dd_fb_d2_66_57_3c_bb_66_cf_81_1f_67_46_c7_d7_67_bd_0f_bc_68_32_57_aa_68_a6_9e_80_69_19_e3_1f_69_8c_24_6b_69_fd_61_4a_6a_6d_98_a3_6a_dc_c9_64_6b_4a_f2_78_6b_b8_12_d0_6c_24_29_5f_6c_8f_35_1b_6c_f9_34_fb_6d_62_27_f9_6d_ca_0d_14_6e_30_e3_49_6e_96_a9_9c_6e_fb_5f_11_6f_5f_02_b1_6f_c1_93_84_70_23_10_99_70_83_78_fe_70_e2_cb_c5_71_41_08_04_71_9e_2c_d1_71_fa_39_48_72_55_2c_84_72_af_05_a6_73_07_c3_cf_73_5f_66_25_73_b5_eb_d0_74_0b_53_fa_74_5f_9d_d0_74_b2_c8_83_75_04_d3_44_75_55_bd_4b_75_a5_85_ce_75_f4_2c_0a_76_41_af_3c_76_8e_0e_a5_76_d9_49_88_77_23_5f_2c_77_6c_4e_da_77_b4_17_df_77_fa_b9_88_78_40_33_28_78_84_84_13_78_c7_ab_a1_79_09_a9_2c_79_4a_7c_11_79_8a_23_b0_79_c8_9f_6d_7a_05_ee_ac_7a_42_10_d8_7a_7d_05_5a_7a_b6_cb_a3_7a_ef_63_23_7b_26_cb_4e_7b_5d_03_9d_7b_92_0b_88_7b_c5_e2_8f_7b_f8_88_2f_7c_29_fb_ed_7c_5a_3d_4f_7c_89_4b_dd_7c_b7_27_23_7c_e3_ce_b1_7d_0f_42_17_7d_39_80_eb_7d_62_8a_c5_7d_8a_5f_3f_7d_b0_fd_f7_7d_d6_66_8e_7d_fa_98_a7_7e_1d_93_e9_7e_3f_57_fe_7e_5f_e4_92_7e_7f_39_56_7e_9d_55_fb_7e_ba_3a_38_7e_d5_e5_c5_7e_f0_58_5f_7f_09_91_c3_7f_21_91_b3_7f_38_57_f5_7f_4d_e4_50_7f_62_36_8e_7f_75_4e_7f_7f_87_2b_f2_7f_97_ce_bc_7f_a7_36_b3_7f_b5_63_b2_7f_c2_55_95_7f_ce_0c_3d_7f_d8_87_8d_7f_e1_c7_6a_7f_e9_cb_bf_7f_f0_94_77_7f_f6_21_81_7f_fa_72_d0_7f_fd_88_59_7f_ff_62_15_7f_ff_ff_ff"; /** * @notice Return the sine of a value, specified in radians scaled by 1e18 * @dev This algorithm for converting sine only uses integer values, and it works by dividing the * circle into 30 bit angles, i.e. there are 1,073,741,824 (2^30) angle units, instead of the * standard 360 degrees (2pi radians). From there, we get an output in range -2,147,483,647 to * 2,147,483,647, (which is the max value of an int32) which is then converted back to the standard * range of -1 to 1, again scaled by 1e18 * @param _angle Angle to convert * @return Result scaled by 1e18 */ function sin(uint256 _angle) internal pure returns (int256) { unchecked { // Convert angle from from arbitrary radian value (range of 0 to 2pi) to the algorithm's range // of 0 to 1,073,741,824 _angle = ANGLES_IN_CYCLE * (_angle % TWO_PI) / TWO_PI; // Apply a mask on an integer to extract a certain number of bits, where angle is the integer // whose bits we want to get, the width is the width of the bits (in bits) we want to extract, // and the offset is the offset of the bits (in bits) we want to extract. The result is an // integer containing _width bits of _value starting at the offset bit uint256 interp = (_angle >> INTERP_OFFSET) & ((1 << INTERP_WIDTH) - 1); uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1); // The lookup table only contains data for one quadrant (since sin is symmetric around both // axes), so here we figure out which quadrant we're in, then we lookup the values in the // table then modify values accordingly bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0; bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0; if (!is_odd_quadrant) { index = SINE_TABLE_SIZE - 1 - index; } bytes memory table = sin_table; // We are looking for two consecutive indices in our lookup table // Since EVM is left aligned, to read n bytes of data from idx i, we must read from `i * data_len` + `n` // therefore, to read two entries of size entry_bytes `index * entry_bytes` + `entry_bytes * 2` uint256 offset1_2 = (index + 2) * entry_bytes; // This following snippet will function for any entry_bytes <= 15 uint256 x1_2; assembly { // mload will grab one word worth of bytes (32), as that is the minimum size in EVM x1_2 := mload(add(table, offset1_2)) } // We now read the last two numbers of size entry_bytes from x1_2 // in example: entry_bytes = 4; x1_2 = 0x00...12345678abcdefgh // therefore: entry_mask = 0xFFFFFFFF // 0x00...12345678abcdefgh >> 8*4 = 0x00...12345678 // 0x00...12345678 & 0xFFFFFFFF = 0x12345678 uint256 x1 = x1_2 >> 8*entry_bytes & entry_mask; // 0x00...12345678abcdefgh & 0xFFFFFFFF = 0xabcdefgh uint256 x2 = x1_2 & entry_mask; // Approximate angle by interpolating in the table, accounting for the quadrant uint256 approximation = ((x2 - x1) * interp) >> INTERP_WIDTH; int256 sine = is_odd_quadrant ? int256(x1) + int256(approximation) : int256(x2) - int256(approximation); if (is_negative_quadrant) { sine *= -1; } // Bring result from the range of -2,147,483,647 through 2,147,483,647 to -1e18 through 1e18. // This can never overflow because sine is bounded by the above values return sine * 1e18 / 2_147_483_647; } } /** * @notice Return the cosine of a value, specified in radians scaled by 1e18 * @dev This is identical to the sin() method, and just computes the value by delegating to the * sin() method using the identity cos(x) = sin(x + pi/2) * @dev Overflow when `angle + PI_OVER_TWO > type(uint256).max` is ok, results are still accurate * @param _angle Angle to convert * @return Result scaled by 1e18 */ function cos(uint256 _angle) internal pure returns (int256) { unchecked { return sin(_angle + PI_OVER_TWO); } } } // SPDX-License-Identifier: Unlicense pragma solidity >=0.8.4; import "./PRBMath.sol"; /// @title PRBMathSD59x18 /// @author Paul Razvan Berg /// @notice Smart contract library for advanced fixed-point math that works with int256 numbers considered to have 18 /// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have /// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers /// are bound by the minimum and the maximum values permitted by the Solidity type int256. library PRBMathSD59x18 { /// @dev log2(e) as a signed 59.18-decimal fixed-point number. int256 internal constant LOG2_E = 1_442695040888963407; /// @dev Half the SCALE number. int256 internal constant HALF_SCALE = 5e17; /// @dev The maximum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967; /// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000; /// @dev The minimum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968; /// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000; /// @dev How many trailing decimals can be represented. int256 internal constant SCALE = 1e18; /// INTERNAL FUNCTIONS /// /// @notice Calculate the absolute value of x. /// /// @dev Requirements: /// - x must be greater than MIN_SD59x18. /// /// @param x The number to calculate the absolute value for. /// @param result The absolute value of x. function abs(int256 x) internal pure returns (int256 result) { unchecked { if (x == MIN_SD59x18) { revert PRBMathSD59x18__AbsInputTooSmall(); } result = x < 0 ? -x : x; } } /// @notice Calculates the arithmetic average of x and y, rounding down. /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The arithmetic average as a signed 59.18-decimal fixed-point number. function avg(int256 x, int256 y) internal pure returns (int256 result) { // The operations can never overflow. unchecked { int256 sum = (x >> 1) + (y >> 1); if (sum < 0) { // If at least one of x and y is odd, we add 1 to the result. This is because shifting negative numbers to the // right rounds down to infinity. assembly { result := add(sum, and(or(x, y), 1)) } } else { // If both x and y are odd, we add 1 to the result. This is because if both numbers are odd, the 0.5 // remainder gets truncated twice. result = sum + (x & y & 1); } } } /// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to MAX_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to ceil. /// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number. function ceil(int256 x) internal pure returns (int256 result) { if (x > MAX_WHOLE_SD59x18) { revert PRBMathSD59x18__CeilOverflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x > 0) { result += SCALE; } } } } /// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - All from "PRBMath.mulDiv". /// - None of the inputs can be MIN_SD59x18. /// - The denominator cannot be zero. /// - The result must fit within int256. /// /// Caveats: /// - All from "PRBMath.mulDiv". /// /// @param x The numerator as a signed 59.18-decimal fixed-point number. /// @param y The denominator as a signed 59.18-decimal fixed-point number. /// @param result The quotient as a signed 59.18-decimal fixed-point number. function div(int256 x, int256 y) internal pure returns (int256 result) { if (x == MIN_SD59x18 || y == MIN_SD59x18) { revert PRBMathSD59x18__DivInputTooSmall(); } // Get hold of the absolute values of x and y. uint256 ax; uint256 ay; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); } // Compute the absolute value of (x*SCALE)÷y. The result must fit within int256. uint256 rAbs = PRBMath.mulDiv(ax, uint256(SCALE), ay); if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__DivOverflow(rAbs); } // Get the signs of x and y. uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } // XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result // should be positive. Otherwise, it should be negative. result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs); } /// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number. /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant). function e() internal pure returns (int256 result) { result = 2_718281828459045235; } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the insight that e^x = 2^(x * log2(e)). /// /// Requirements: /// - All from "log2". /// - x must be less than 133.084258667509499441. /// /// Caveats: /// - All from "exp2". /// - For any x less than -41.446531673892822322, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp(int256 x) internal pure returns (int256 result) { // Without this check, the value passed to "exp2" would be less than -59.794705707972522261. if (x < -41_446531673892822322) { return 0; } // Without this check, the value passed to "exp2" would be greater than 192. if (x >= 133_084258667509499441) { revert PRBMathSD59x18__ExpInputTooBig(x); } // Do the fixed-point multiplication inline to save gas. unchecked { int256 doubleScaleProduct = x * LOG2_E; result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Requirements: /// - x must be 192 or less. /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - For any x less than -59.794705707972522261, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp2(int256 x) internal pure returns (int256 result) { // This works because 2^(-x) = 1/2^x. if (x < 0) { // 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero. if (x < -59_794705707972522261) { return 0; } // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. unchecked { result = 1e36 / exp2(-x); } } else { // 2^192 doesn't fit within the 192.64-bit format used internally in this function. if (x >= 192e18) { revert PRBMathSD59x18__Exp2InputTooBig(x); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE); // Safe to convert the result to int256 directly because the maximum input allowed is 192. result = int256(PRBMath.exp2(x192x64)); } } } /// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be greater than or equal to MIN_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to floor. /// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number. function floor(int256 x) internal pure returns (int256 result) { if (x < MIN_WHOLE_SD59x18) { revert PRBMathSD59x18__FloorUnderflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x < 0) { result -= SCALE; } } } } /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right /// of the radix point for negative numbers. /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part /// @param x The signed 59.18-decimal fixed-point number to get the fractional part of. /// @param result The fractional part of x as a signed 59.18-decimal fixed-point number. function frac(int256 x) internal pure returns (int256 result) { unchecked { result = x % SCALE; } } /// @notice Converts a number from basic integer form to signed 59.18-decimal fixed-point representation. /// /// @dev Requirements: /// - x must be greater than or equal to MIN_SD59x18 divided by SCALE. /// - x must be less than or equal to MAX_SD59x18 divided by SCALE. /// /// @param x The basic integer to convert. /// @param result The same number in signed 59.18-decimal fixed-point representation. function fromInt(int256 x) internal pure returns (int256 result) { unchecked { if (x < MIN_SD59x18 / SCALE) { revert PRBMathSD59x18__FromIntUnderflow(x); } if (x > MAX_SD59x18 / SCALE) { revert PRBMathSD59x18__FromIntOverflow(x); } result = x * SCALE; } } /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down. /// /// @dev Requirements: /// - x * y must fit within MAX_SD59x18, lest it overflows. /// - x * y cannot be negative. /// /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function gm(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { return 0; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. int256 xy = x * y; if (xy / x != y) { revert PRBMathSD59x18__GmOverflow(x, y); } // The product cannot be negative. if (xy < 0) { revert PRBMathSD59x18__GmNegativeProduct(x, y); } // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE // during multiplication. See the comments within the "sqrt" function. result = int256(PRBMath.sqrt(uint256(xy))); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse. /// @return result The inverse as a signed 59.18-decimal fixed-point number. function inv(int256 x) internal pure returns (int256 result) { unchecked { // 1e36 is SCALE * SCALE. result = 1e36 / x; } } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the insight that ln(x) = log2(x) / log2(e). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm. /// @return result The natural logarithm as a signed 59.18-decimal fixed-point number. function ln(int256 x) internal pure returns (int256 result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 195205294292027477728. unchecked { result = (log2(x) * SCALE) / LOG2_E; } } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the insight that log10(x) = log2(x) / log2(10). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm. /// @return result The common logarithm as a signed 59.18-decimal fixed-point number. function log10(int256 x) internal pure returns (int256 result) { if (x <= 0) { revert PRBMathSD59x18__LogInputTooSmall(x); } // Note that the "mul" in this block is the assembly mul operation, not the "mul" function defined in this contract. // prettier-ignore assembly { switch x case 1 { result := mul(SCALE, sub(0, 18)) } case 10 { result := mul(SCALE, sub(1, 18)) } case 100 { result := mul(SCALE, sub(2, 18)) } case 1000 { result := mul(SCALE, sub(3, 18)) } case 10000 { result := mul(SCALE, sub(4, 18)) } case 100000 { result := mul(SCALE, sub(5, 18)) } case 1000000 { result := mul(SCALE, sub(6, 18)) } case 10000000 { result := mul(SCALE, sub(7, 18)) } case 100000000 { result := mul(SCALE, sub(8, 18)) } case 1000000000 { result := mul(SCALE, sub(9, 18)) } case 10000000000 { result := mul(SCALE, sub(10, 18)) } case 100000000000 { result := mul(SCALE, sub(11, 18)) } case 1000000000000 { result := mul(SCALE, sub(12, 18)) } case 10000000000000 { result := mul(SCALE, sub(13, 18)) } case 100000000000000 { result := mul(SCALE, sub(14, 18)) } case 1000000000000000 { result := mul(SCALE, sub(15, 18)) } case 10000000000000000 { result := mul(SCALE, sub(16, 18)) } case 100000000000000000 { result := mul(SCALE, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := SCALE } case 100000000000000000000 { result := mul(SCALE, 2) } case 1000000000000000000000 { result := mul(SCALE, 3) } case 10000000000000000000000 { result := mul(SCALE, 4) } case 100000000000000000000000 { result := mul(SCALE, 5) } case 1000000000000000000000000 { result := mul(SCALE, 6) } case 10000000000000000000000000 { result := mul(SCALE, 7) } case 100000000000000000000000000 { result := mul(SCALE, 8) } case 1000000000000000000000000000 { result := mul(SCALE, 9) } case 10000000000000000000000000000 { result := mul(SCALE, 10) } case 100000000000000000000000000000 { result := mul(SCALE, 11) } case 1000000000000000000000000000000 { result := mul(SCALE, 12) } case 10000000000000000000000000000000 { result := mul(SCALE, 13) } case 100000000000000000000000000000000 { result := mul(SCALE, 14) } case 1000000000000000000000000000000000 { result := mul(SCALE, 15) } case 10000000000000000000000000000000000 { result := mul(SCALE, 16) } case 100000000000000000000000000000000000 { result := mul(SCALE, 17) } case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) } case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) } case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) } case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) } case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) } case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) } case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) } case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) } case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) } default { result := MAX_SD59x18 } } if (result == MAX_SD59x18) { // Do the fixed-point division inline to save gas. The denominator is log2(10). unchecked { result = (log2(x) * SCALE) / 3_321928094887362347; } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than zero. /// /// Caveats: /// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as a signed 59.18-decimal fixed-point number. function log2(int256 x) internal pure returns (int256 result) { if (x <= 0) { revert PRBMathSD59x18__LogInputTooSmall(x); } unchecked { // This works because log2(x) = -log2(1/x). int256 sign; if (x >= SCALE) { sign = 1; } else { sign = -1; // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. assembly { x := div(1000000000000000000000000000000000000, x) } } // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE)); // The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1. result = int256(n) * SCALE; // This is y = x * 2^(-n). int256 y = x >> n; // If y = 1, the fractional part is zero. if (y == SCALE) { return result * sign; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) { y = (y * y) / SCALE; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * SCALE) { // Add the 2^(-m) factor to the logarithm. result += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } result *= sign; } } /// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal /// fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers and employs constant folding, i.e. the denominator is /// always 1e18. /// /// Requirements: /// - All from "PRBMath.mulDivFixedPoint". /// - None of the inputs can be MIN_SD59x18 /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// /// @param x The multiplicand as a signed 59.18-decimal fixed-point number. /// @param y The multiplier as a signed 59.18-decimal fixed-point number. /// @return result The product as a signed 59.18-decimal fixed-point number. function mul(int256 x, int256 y) internal pure returns (int256 result) { if (x == MIN_SD59x18 || y == MIN_SD59x18) { revert PRBMathSD59x18__MulInputTooSmall(); } unchecked { uint256 ax; uint256 ay; ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); uint256 rAbs = PRBMath.mulDivFixedPoint(ax, ay); if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__MulOverflow(rAbs); } uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs); } } /// @notice Returns PI as a signed 59.18-decimal fixed-point number. function pi() internal pure returns (int256 result) { result = 3_141592653589793238; } /// @notice Raises x to the power of y. /// /// @dev Based on the insight that x^y = 2^(log2(x) * y). /// /// Requirements: /// - All from "exp2", "log2" and "mul". /// - z cannot be zero. /// /// Caveats: /// - All from "exp2", "log2" and "mul". /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, as a signed 59.18-decimal fixed-point number. /// @param y Exponent to raise x to, as a signed 59.18-decimal fixed-point number. /// @return result x raised to power y, as a signed 59.18-decimal fixed-point number. function pow(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { result = y == 0 ? SCALE : int256(0); } else { result = exp2(mul(log2(x), y)); } } /// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the /// famous algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - All from "abs" and "PRBMath.mulDivFixedPoint". /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - All from "PRBMath.mulDivFixedPoint". /// - Assumes 0^0 is 1. /// /// @param x The base as a signed 59.18-decimal fixed-point number. /// @param y The exponent as an uint256. /// @return result The result as a signed 59.18-decimal fixed-point number. function powu(int256 x, uint256 y) internal pure returns (int256 result) { uint256 xAbs = uint256(abs(x)); // Calculate the first iteration of the loop in advance. uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE); // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. uint256 yAux = y; for (yAux >>= 1; yAux > 0; yAux >>= 1) { xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs); // Equivalent to "y % 2 == 1" but faster. if (yAux & 1 > 0) { rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs); } } // The result must fit within the 59.18-decimal fixed-point representation. if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__PowuOverflow(rAbs); } // Is the base negative and the exponent an odd number? bool isNegative = x < 0 && y & 1 == 1; result = isNegative ? -int256(rAbs) : int256(rAbs); } /// @notice Returns 1 as a signed 59.18-decimal fixed-point number. function scale() internal pure returns (int256 result) { result = SCALE; } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x cannot be negative. /// - x must be less than MAX_SD59x18 / SCALE. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root. /// @return result The result as a signed 59.18-decimal fixed-point . function sqrt(int256 x) internal pure returns (int256 result) { unchecked { if (x < 0) { revert PRBMathSD59x18__SqrtNegativeInput(x); } if (x > MAX_SD59x18 / SCALE) { revert PRBMathSD59x18__SqrtOverflow(x); } // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed // 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root). result = int256(PRBMath.sqrt(uint256(x * SCALE))); } } /// @notice Converts a signed 59.18-decimal fixed-point number to basic integer form, rounding down in the process. /// @param x The signed 59.18-decimal fixed-point number to convert. /// @return result The same number in basic integer form. function toInt(int256 x) internal pure returns (int256 result) { unchecked { result = x / SCALE; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ERC721SingleCreatorExtensionBase.sol"; /** * @dev Extension that only uses a single creator contract instance */ abstract contract ERC721SingleCreatorExtension is ERC721SingleCreatorExtensionBase { constructor(address creator) { _setCreator(creator); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your extension to have overloadable URI's */ interface ICreatorExtensionTokenURI is IERC165 { /** * Get the uri for a given creator/tokenId */ function tokenURI(address creator, uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Base creator extension variables */ abstract contract CreatorExtension is ERC165 { /** * @dev Legacy extension interface identifiers * * {IERC165-supportsInterface} needs to return 'true' for this interface * in order backwards compatible with older creator contracts */ bytes4 constant internal LEGACY_EXTENSION_INTERFACE = 0x7005caad; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) { return interfaceId == LEGACY_EXTENSION_INTERFACE || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ICreatorCore.sol"; /** * @dev Core ERC721 creator interface */ interface IERC721CreatorCore is ICreatorCore { /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to) external returns (uint256); /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to) external returns (uint256); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenIds minted */ function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered extension's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: Unlicense pragma solidity >=0.8.4; /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivFixedPointOverflow(uint256 prod1); /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator); /// @notice Emitted when one of the inputs is type(int256).min. error PRBMath__MulDivSignedInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows int256. error PRBMath__MulDivSignedOverflow(uint256 rAbs); /// @notice Emitted when the input is MIN_SD59x18. error PRBMathSD59x18__AbsInputTooSmall(); /// @notice Emitted when ceiling a number overflows SD59x18. error PRBMathSD59x18__CeilOverflow(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__DivInputTooSmall(); /// @notice Emitted when one of the intermediary unsigned results overflows SD59x18. error PRBMathSD59x18__DivOverflow(uint256 rAbs); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathSD59x18__ExpInputTooBig(int256 x); /// @notice Emitted when the input is greater than 192. error PRBMathSD59x18__Exp2InputTooBig(int256 x); /// @notice Emitted when flooring a number underflows SD59x18. error PRBMathSD59x18__FloorUnderflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18. error PRBMathSD59x18__FromIntOverflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18. error PRBMathSD59x18__FromIntUnderflow(int256 x); /// @notice Emitted when the product of the inputs is negative. error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y); /// @notice Emitted when multiplying the inputs overflows SD59x18. error PRBMathSD59x18__GmOverflow(int256 x, int256 y); /// @notice Emitted when the input is less than or equal to zero. error PRBMathSD59x18__LogInputTooSmall(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__MulInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__MulOverflow(uint256 rAbs); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__PowuOverflow(uint256 rAbs); /// @notice Emitted when the input is negative. error PRBMathSD59x18__SqrtNegativeInput(int256 x); /// @notice Emitted when the calculating the square root overflows SD59x18. error PRBMathSD59x18__SqrtOverflow(int256 x); /// @notice Emitted when addition overflows UD60x18. error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y); /// @notice Emitted when ceiling a number overflows UD60x18. error PRBMathUD60x18__CeilOverflow(uint256 x); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathUD60x18__ExpInputTooBig(uint256 x); /// @notice Emitted when the input is greater than 192. error PRBMathUD60x18__Exp2InputTooBig(uint256 x); /// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18. error PRBMathUD60x18__FromUintOverflow(uint256 x); /// @notice Emitted when multiplying the inputs overflows UD60x18. error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y); /// @notice Emitted when the input is less than 1. error PRBMathUD60x18__LogInputTooSmall(uint256 x); /// @notice Emitted when the calculating the square root overflows UD60x18. error PRBMathUD60x18__SqrtOverflow(uint256 x); /// @notice Emitted when subtraction underflows UD60x18. error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y); /// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library /// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point /// representation. When it does not, it is explicitly mentioned in the NatSpec documentation. library PRBMath { /// STRUCTS /// struct SD59x18 { int256 value; } struct UD60x18 { uint256 value; } /// STORAGE /// /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @dev Largest power of two divisor of SCALE. uint256 internal constant SCALE_LPOTD = 262144; /// @dev SCALE inverted mod 2^256. uint256 internal constant SCALE_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281; /// FUNCTIONS /// /// @notice Calculates the binary exponent of x using the binary fraction method. /// @dev Has to use 192.64-bit fixed-point numbers. /// See https://ethereum.stackexchange.com/a/96594/24693. /// @param x The exponent as an unsigned 192.64-bit fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp2(uint256 x) internal pure returns (uint256 result) { unchecked { // Start from 0.5 in the 192.64-bit fixed-point format. result = 0x800000000000000000000000000000000000000000000000; // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows // because the initial result is 2^191 and all magic factors are less than 2^65. if (x & 0x8000000000000000 > 0) { result = (result * 0x16A09E667F3BCC909) >> 64; } if (x & 0x4000000000000000 > 0) { result = (result * 0x1306FE0A31B7152DF) >> 64; } if (x & 0x2000000000000000 > 0) { result = (result * 0x1172B83C7D517ADCE) >> 64; } if (x & 0x1000000000000000 > 0) { result = (result * 0x10B5586CF9890F62A) >> 64; } if (x & 0x800000000000000 > 0) { result = (result * 0x1059B0D31585743AE) >> 64; } if (x & 0x400000000000000 > 0) { result = (result * 0x102C9A3E778060EE7) >> 64; } if (x & 0x200000000000000 > 0) { result = (result * 0x10163DA9FB33356D8) >> 64; } if (x & 0x100000000000000 > 0) { result = (result * 0x100B1AFA5ABCBED61) >> 64; } if (x & 0x80000000000000 > 0) { result = (result * 0x10058C86DA1C09EA2) >> 64; } if (x & 0x40000000000000 > 0) { result = (result * 0x1002C605E2E8CEC50) >> 64; } if (x & 0x20000000000000 > 0) { result = (result * 0x100162F3904051FA1) >> 64; } if (x & 0x10000000000000 > 0) { result = (result * 0x1000B175EFFDC76BA) >> 64; } if (x & 0x8000000000000 > 0) { result = (result * 0x100058BA01FB9F96D) >> 64; } if (x & 0x4000000000000 > 0) { result = (result * 0x10002C5CC37DA9492) >> 64; } if (x & 0x2000000000000 > 0) { result = (result * 0x1000162E525EE0547) >> 64; } if (x & 0x1000000000000 > 0) { result = (result * 0x10000B17255775C04) >> 64; } if (x & 0x800000000000 > 0) { result = (result * 0x1000058B91B5BC9AE) >> 64; } if (x & 0x400000000000 > 0) { result = (result * 0x100002C5C89D5EC6D) >> 64; } if (x & 0x200000000000 > 0) { result = (result * 0x10000162E43F4F831) >> 64; } if (x & 0x100000000000 > 0) { result = (result * 0x100000B1721BCFC9A) >> 64; } if (x & 0x80000000000 > 0) { result = (result * 0x10000058B90CF1E6E) >> 64; } if (x & 0x40000000000 > 0) { result = (result * 0x1000002C5C863B73F) >> 64; } if (x & 0x20000000000 > 0) { result = (result * 0x100000162E430E5A2) >> 64; } if (x & 0x10000000000 > 0) { result = (result * 0x1000000B172183551) >> 64; } if (x & 0x8000000000 > 0) { result = (result * 0x100000058B90C0B49) >> 64; } if (x & 0x4000000000 > 0) { result = (result * 0x10000002C5C8601CC) >> 64; } if (x & 0x2000000000 > 0) { result = (result * 0x1000000162E42FFF0) >> 64; } if (x & 0x1000000000 > 0) { result = (result * 0x10000000B17217FBB) >> 64; } if (x & 0x800000000 > 0) { result = (result * 0x1000000058B90BFCE) >> 64; } if (x & 0x400000000 > 0) { result = (result * 0x100000002C5C85FE3) >> 64; } if (x & 0x200000000 > 0) { result = (result * 0x10000000162E42FF1) >> 64; } if (x & 0x100000000 > 0) { result = (result * 0x100000000B17217F8) >> 64; } if (x & 0x80000000 > 0) { result = (result * 0x10000000058B90BFC) >> 64; } if (x & 0x40000000 > 0) { result = (result * 0x1000000002C5C85FE) >> 64; } if (x & 0x20000000 > 0) { result = (result * 0x100000000162E42FF) >> 64; } if (x & 0x10000000 > 0) { result = (result * 0x1000000000B17217F) >> 64; } if (x & 0x8000000 > 0) { result = (result * 0x100000000058B90C0) >> 64; } if (x & 0x4000000 > 0) { result = (result * 0x10000000002C5C860) >> 64; } if (x & 0x2000000 > 0) { result = (result * 0x1000000000162E430) >> 64; } if (x & 0x1000000 > 0) { result = (result * 0x10000000000B17218) >> 64; } if (x & 0x800000 > 0) { result = (result * 0x1000000000058B90C) >> 64; } if (x & 0x400000 > 0) { result = (result * 0x100000000002C5C86) >> 64; } if (x & 0x200000 > 0) { result = (result * 0x10000000000162E43) >> 64; } if (x & 0x100000 > 0) { result = (result * 0x100000000000B1721) >> 64; } if (x & 0x80000 > 0) { result = (result * 0x10000000000058B91) >> 64; } if (x & 0x40000 > 0) { result = (result * 0x1000000000002C5C8) >> 64; } if (x & 0x20000 > 0) { result = (result * 0x100000000000162E4) >> 64; } if (x & 0x10000 > 0) { result = (result * 0x1000000000000B172) >> 64; } if (x & 0x8000 > 0) { result = (result * 0x100000000000058B9) >> 64; } if (x & 0x4000 > 0) { result = (result * 0x10000000000002C5D) >> 64; } if (x & 0x2000 > 0) { result = (result * 0x1000000000000162E) >> 64; } if (x & 0x1000 > 0) { result = (result * 0x10000000000000B17) >> 64; } if (x & 0x800 > 0) { result = (result * 0x1000000000000058C) >> 64; } if (x & 0x400 > 0) { result = (result * 0x100000000000002C6) >> 64; } if (x & 0x200 > 0) { result = (result * 0x10000000000000163) >> 64; } if (x & 0x100 > 0) { result = (result * 0x100000000000000B1) >> 64; } if (x & 0x80 > 0) { result = (result * 0x10000000000000059) >> 64; } if (x & 0x40 > 0) { result = (result * 0x1000000000000002C) >> 64; } if (x & 0x20 > 0) { result = (result * 0x10000000000000016) >> 64; } if (x & 0x10 > 0) { result = (result * 0x1000000000000000B) >> 64; } if (x & 0x8 > 0) { result = (result * 0x10000000000000006) >> 64; } if (x & 0x4 > 0) { result = (result * 0x10000000000000003) >> 64; } if (x & 0x2 > 0) { result = (result * 0x10000000000000001) >> 64; } if (x & 0x1 > 0) { result = (result * 0x10000000000000001) >> 64; } // We're doing two things at the same time: // // 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for // the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191 // rather than 192. // 2. Convert the result to the unsigned 60.18-decimal fixed-point format. // // This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n". result *= SCALE; result >>= (191 - (x >> 64)); } } /// @notice Finds the zero-based index of the first one in the binary representation of x. /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set /// @param x The uint256 number for which to find the index of the most significant bit. /// @return msb The index of the most significant bit as an uint256. function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; } if (x >= 2**16) { x >>= 16; msb += 16; } if (x >= 2**8) { x >>= 8; msb += 8; } if (x >= 2**4) { x >>= 4; msb += 4; } if (x >= 2**2) { x >>= 2; msb += 2; } if (x >= 2**1) { // No need to shift x any more. msb += 1; } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Requirements: /// - The denominator cannot be zero. /// - The result must fit within uint256. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The multiplicand as an uint256. /// @param y The multiplier as an uint256. /// @param denominator The divisor as an uint256. /// @return result The result as an uint256. function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { unchecked { result = prod0 / denominator; } return result; } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (prod1 >= denominator) { revert PRBMath__MulDivOverflow(prod1, denominator); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. unchecked { // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 lpotdod = denominator & (~denominator + 1); assembly { // Divide denominator by lpotdod. denominator := div(denominator, lpotdod) // Divide [prod1 prod0] by lpotdod. prod0 := div(prod0, lpotdod) // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one. lpotdod := add(div(sub(0, lpotdod), lpotdod), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * lpotdod; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /// @notice Calculates floor(x*y÷1e18) with full precision. /// /// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the /// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of /// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717. /// /// Requirements: /// - The result must fit within uint256. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations: /// 1. x * y = type(uint256).max * SCALE /// 2. (x * y) % SCALE >= SCALE / 2 /// /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) { uint256 prod0; uint256 prod1; assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 >= SCALE) { revert PRBMath__MulDivFixedPointOverflow(prod1); } uint256 remainder; uint256 roundUpUnit; assembly { remainder := mulmod(x, y, SCALE) roundUpUnit := gt(remainder, 499999999999999999) } if (prod1 == 0) { unchecked { result = (prod0 / SCALE) + roundUpUnit; return result; } } assembly { result := add( mul( or( div(sub(prod0, remainder), SCALE_LPOTD), mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1)) ), SCALE_INVERSE ), roundUpUnit ) } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - None of the inputs can be type(int256).min. /// - The result must fit within int256. /// /// @param x The multiplicand as an int256. /// @param y The multiplier as an int256. /// @param denominator The divisor as an int256. /// @return result The result as an int256. function mulDivSigned( int256 x, int256 y, int256 denominator ) internal pure returns (int256 result) { if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) { revert PRBMath__MulDivSignedInputTooSmall(); } // Get hold of the absolute values of x, y and the denominator. uint256 ax; uint256 ay; uint256 ad; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); ad = denominator < 0 ? uint256(-denominator) : uint256(denominator); } // Compute the absolute value of (x*y)÷denominator. The result must fit within int256. uint256 rAbs = mulDiv(ax, ay, ad); if (rAbs > uint256(type(int256).max)) { revert PRBMath__MulDivSignedOverflow(rAbs); } // Get the signs of x, y and the denominator. uint256 sx; uint256 sy; uint256 sd; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) sd := sgt(denominator, sub(0, 1)) } // XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs. // If yes, the result should be negative. result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs); } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as an uint256. function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Set the initial guess to the least power of two that is greater than or equal to sqrt(x). uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol"; import "../../LegacyInterfaces.sol"; import "../SingleCreatorExtensionBase.sol"; /** * @dev Extension that only uses a single creator contract instance */ abstract contract ERC721SingleCreatorExtensionBase is SingleCreatorExtensionBase { function _setCreator(address creator) internal override { require(ERC165Checker.supportsInterface(creator, type(IERC721CreatorCore).interfaceId) || ERC165Checker.supportsInterface(creator, LegacyInterfaces.IERC721CreatorCore_v1), "Creator contract must implement IERC721CreatorCore"); super._setCreator(creator); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Core creator interface */ interface ICreatorCore is IERC165 { event ExtensionRegistered(address indexed extension, address indexed sender); event ExtensionUnregistered(address indexed extension, address indexed sender); event ExtensionBlacklisted(address indexed extension, address indexed sender); event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints); event ExtensionApproveTransferUpdated(address indexed extension, bool enabled); /** * @dev gets address of all extensions */ function getExtensions() external view returns (address[] memory); /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI) external; /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external; /** * @dev add an extension. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterExtension(address extension) external; /** * @dev blacklist an extension. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified extension. It will also unregister the extension if needed. * Returns True if removed, False if already removed. */ function blacklistExtension(address extension) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. */ function setBaseTokenURIExtension(string calldata uri) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURIExtension(string calldata uri, bool identical) external; /** * @dev set the common prefix of an extension. Can only be called by extension. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefixExtension(string calldata prefix) external; /** * @dev set the tokenURI of a token extension. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no extension. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an extension. Used to control minting. */ function setMintPermissions(address extension, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be extension) gets approval * from the extension before transferring */ function setApproveTransferExtension(bool enabled) external; /** * @dev get the extension of a given token */ function tokenExtension(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of an extension */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz /** * @dev Extension that only uses a single creator contract instance */ abstract contract SingleCreatorExtensionBase { address internal _creator; /** * @dev Override with appropriate interface checks if necessary */ function _setCreator(address creator) internal virtual { _creator = creator; } function creatorContract() public view returns(address) { return _creator; } } // SPDX-License-Identifier: BSD-4-Clause pragma solidity ^0.8.0; /// @author: manifold.xyz /** * Library of legacy interface constants */ library LegacyInterfaces { // LEGACY ERC721CreatorCore interface bytes4 internal constant IERC721CreatorCore_v1 = 0x478c8530; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } }
Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x. Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. Requirements: - x must be less than or equal to MAX_WHOLE_SD59x18. x The signed 59.18-decimal fixed-point number to ceil. result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number. Solidity uses C fmod style, which returns a modulus with the same sign as x.
function ceil(int256 x) internal pure returns (int256 result) { if (x > MAX_WHOLE_SD59x18) { revert PRBMathSD59x18__CeilOverflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; result = x - remainder; if (x > 0) { result += SCALE; } } } }
10,297,495
pragma solidity 0.6.4; interface IBEP20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address _owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } 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; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract 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) { // 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } contract BEP20Token is Context, IBEP20, Initializable { 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; address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); bool private _mintable; bool private _burnable; address private teamWallet; bool private pauseTx = false; uint256 public _taxFee = 0; uint256 private _previousTaxFee = _taxFee; constructor() public { } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev sets initials supply and the owner */ function initialize(string memory name, string memory symbol, uint8 decimals, uint256 amount, bool mintable, bool burnable, address owner, address _teamWallet) public initializer { _owner = owner; _name = name; _symbol = symbol; _decimals = decimals; _mintable = mintable; _burnable = burnable; teamWallet = _teamWallet; _mint(owner, amount); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Returns if the token is mintable or not */ function mintable() external view returns (bool) { return _mintable; } /** * @dev Returns if the token is burnable or not */ function burnable() external view returns (bool) { return _burnable; } /** * @dev Returns the bep token owner. */ function getOwner() external override view returns (address) { return _owner; } /** * @dev Returns the token decimals. */ function decimals() external override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external override view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external override view returns (string memory) { return _name; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() external override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) external override view returns (uint256) { return _balances[account]; } function getTeamWallet() external view returns (address) { return teamWallet; } function setTeamWallet(address _teamWallet) public onlyOwner { require(_teamWallet != address(0), "Team wallet is the zero address"); teamWallet = _teamWallet; } function getPauseTx() external view returns (bool) { return pauseTx; } function setPauseTx(bool _pauseTx) public onlyOwner { pauseTx = _pauseTx; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) external override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner * - `_mintable` must be true */ function mint(uint256 amount) public onlyOwner returns (bool) { require(_mintable, "this token is not mintable"); _mint(_msgSender(), amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `recipient`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner * - `_mintable` must be true */ function mintTo(uint256 amount, address recipient) external onlyOwner returns (bool) { require(_mintable, "this token is not mintable"); _mint(recipient, amount); return true; } /** * @dev Burn `amount` tokens and decreasing the total supply. * * Requirements * * - `_burnable` must be true */ function burn(uint256 amount) external returns (bool) { require(_burnable, "this token is not burnable"); _burn(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); require(pauseTx != true, "Pause Transaction"); uint256 feeamount = amount.mul(_taxFee).div(10**2); uint256 txamount = amount; if (feeamount > 0) { txamount = txamount.sub(feeamount); _balances[teamWallet] = _balances[teamWallet].add(feeamount); } _balances[sender] = _balances[sender].sub(txamount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(txamount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "BEP20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { require(_burnable, "this token is not burnable"); _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance")); } }
sets initials supply and the owner/
function initialize(string memory name, string memory symbol, uint8 decimals, uint256 amount, bool mintable, bool burnable, address owner, address _teamWallet) public initializer { _owner = owner; _name = name; _symbol = symbol; _decimals = decimals; _mintable = mintable; _burnable = burnable; teamWallet = _teamWallet; _mint(owner, amount); }
5,707,977
./partial_match/1/0xF06af63b86591b1ceC25107fE7E93Bdb235c0b6d/sources/contracts/strategies/Common/StrategyMiniChefLP.sol
puts the funds to work
function deposit() public whenNotPaused { uint256 wantBal = IERC20(want).balanceOf(address(this)); if (wantBal > 0) { IMiniChefV2(chef).deposit(poolId, wantBal, address(this)); } }
15,723,869
pragma solidity 0.6.12; // File: @openzeppelin/contracts/GSN/Context.sol // 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/Ownable.sol 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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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/Locker.sol /* Copyright 2020 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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. */ /** * @title Locker: Lock and Unlock Token Balances */ contract Locker is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 internal constant MAX_PERCENTAGE = 100; // Token to be locked (ERC-20) IERC20 public immutable token; // Locked token balances per account mapping(address => uint256) internal balances; // Previous withdrawals per epoch mapping(address => mapping(uint256 => uint256)) public withdrawals; // Total amount locked uint256 public totalSupply; // ERC-20 token properties string public name; string public symbol; uint8 public decimals; // Maximum unlockable percentage per epoch uint256 public throttlingPercentage; // Duration of each epoch in seconds uint256 public throttlingDuration; // Balance above which maximum percentage kicks in uint256 public throttlingBalance; /** * @notice Events */ event Lock(address participant, uint256 amount); event Unlock(address participant, uint256 amount); event SetThrottlingPercentage(uint256 throttlingPercentage); event SetThrottlingDuration(uint256 throttlingDuration); event SetThrottlingBalance(uint256 throttlingBalance); /** * @notice Constructor * @param _token address * @param _name string * @param _symbol string * @param _decimals uint8 * @param _throttlingPercentage uint256 * @param _throttlingDuration uint256 * @param _throttlingBalance uint256 */ constructor( address _token, string memory _name, string memory _symbol, uint8 _decimals, uint256 _throttlingPercentage, uint256 _throttlingDuration, uint256 _throttlingBalance ) public { require(_throttlingPercentage <= MAX_PERCENTAGE, "PERCENTAGE_TOO_HIGH"); token = IERC20(_token); name = _name; symbol = _symbol; decimals = _decimals; throttlingPercentage = _throttlingPercentage; throttlingDuration = _throttlingDuration; throttlingBalance = _throttlingBalance; } /** * @notice Lock tokens for msg.sender * @param amount of tokens to lock */ function lock(uint256 amount) external { _lock(msg.sender, msg.sender, amount); } /** * @notice Lock tokens on behalf of another account * @param account to lock tokens for * @param amount of tokens to lock */ function lockFor(address account, uint256 amount) external { _lock(msg.sender, account, amount); } /** * @notice Unlock and transfer to msg.sender * @param amount of tokens to unlock */ function unlock(uint256 amount) external { uint256 previous = withdrawals[msg.sender][epoch()]; // Only enforce percentage above a certain balance if (balances[msg.sender] > throttlingBalance) { require( (previous.add(amount)) <= throttlingPercentage.mul(balances[msg.sender].add(previous)).div( MAX_PERCENTAGE ), "AMOUNT_EXCEEDS_LIMIT" ); } balances[msg.sender] = balances[msg.sender].sub(amount); totalSupply = totalSupply.sub(amount); withdrawals[msg.sender][epoch()] = previous.add(amount); token.safeTransfer(msg.sender, amount); emit Unlock(msg.sender, amount); } /** * @notice Set throttling percentage * @dev Only owner */ function setThrottlingPercentage(uint256 _throttlingPercentage) external onlyOwner { require(_throttlingPercentage <= MAX_PERCENTAGE, "PERCENTAGE_TOO_HIGH"); throttlingPercentage = _throttlingPercentage; emit SetThrottlingPercentage(throttlingPercentage); } /** * @notice Set throttling duration * @dev Only owner */ function setThrottlingDuration(uint256 _throttlingDuration) external onlyOwner { throttlingDuration = _throttlingDuration; emit SetThrottlingDuration(throttlingDuration); } /** * @notice Set throttling balance * @dev Only owner */ function setThrottlingBalance(uint256 _throttlingBalance) external onlyOwner { throttlingBalance = _throttlingBalance; emit SetThrottlingBalance(throttlingBalance); } /** * @notice Return current epoch */ function epoch() public view returns (uint256) { return block.timestamp.sub(block.timestamp.mod(throttlingDuration)); } /** * @notice See {IERC20-balanceOf} */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Perform a locking token transfer * @param from address * @param account address * @param amount uint256 */ function _lock( address from, address account, uint256 amount ) private { require( balances[account].add(amount) <= (type(uint256).max).div(MAX_PERCENTAGE), "OVERFLOW_PROTECTION" ); require(token.balanceOf(from) >= amount, "BALANCE_INSUFFICIENT"); balances[account] = balances[account].add(amount); totalSupply = totalSupply.add(amount); token.safeTransferFrom(from, address(this), amount); emit Lock(account, amount); } } // File: contracts/Imports.sol contract Imports { }
Set throttling duration Only owner/
function setThrottlingDuration(uint256 _throttlingDuration) external onlyOwner { throttlingDuration = _throttlingDuration; emit SetThrottlingDuration(throttlingDuration); }
12,108,398
./full_match/1/0x57FF2c5134a4B252A85Fac1791403fee4A186B1C/sources/browser/LPstaking.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function maxSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); pragma solidity ^0.6.2; }
9,788,550
pragma solidity 0.4.24; 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; } } contract ERC20 { function totalSupply()public view returns (uint total_Supply); function balanceOf(address who)public view returns (uint256); function allowance(address owner, address spender)public view returns (uint); function transferFrom(address from, address to, uint value)public returns (bool ok); function approve(address spender, uint value)public returns (bool ok); function transfer(address to, uint value)public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract KNOWToken is ERC20 { using SafeMath for uint256; // Name of the token string public constant name = "KNOW Token"; // Symbol of token string public constant symbol = "KNOW"; uint8 public constant decimals = 18; uint public _totalsupply = 18300000000 * 10 ** 18; // 18 billion total supply // muliplies dues to decimal precision address public owner; // Owner of this contract uint256 no_of_tokens; uint256 total_token; bool stopped = false; bool checkTransfer = false; uint256 public lockup_startdate; uint256 public lockup_enddate; uint256 public eth_received; // total ether received in the contract uint256 transferPercent; uint256 transferPercentTotal; uint256 transferDays; uint256 transferDaysTotal; uint256 transferLastTransaction; uint256 transferTotalSpent; uint256 transferPostDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) addOfPrivateSale; mapping(address => bool) addOfContributors; mapping(address => bool) addOfContributors2; mapping(address => bool) addOfTechOperation; mapping(address => bool) addOfMarketingBusinessDev; mapping(address => bool) addOfEarlyInvestor; mapping(address => bool) addOfOwners; event EventPrivateSale(address indexed _PrivateSale, bool _status); event EventContributors(address indexed _Contributors, bool _status); event EventContributors2(address indexed _Contributors2, bool _status); event EventTechOperation(address indexed _TechOperation, bool _status); event EventMarketingBusinessDev(address indexed _MarketingBusinessDev, bool _status); event EventEarlyInvestor(address indexed _EarlyInvestor, bool _status); mapping(address => LockupHolderDetails) lockupHolderMap; struct LockupHolderDetails{ uint transferPercent; uint transferDays; uint transferPercentTotal; uint transferDaysTotal; uint transferLastTransaction; uint transferTotalSpent; uint transferPostDate; bool reset; } enum Stages { LOCKUPNOTSTARTED, LOCKUPSTARTED, LOCKUPENDED } Stages public stage; modifier atStage(Stages _stage) { if (stage != _stage) // Contract not in expected state revert(); _; } modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } function KNOWToken() public { owner = msg.sender; stage = Stages.LOCKUPNOTSTARTED; uint256 _transfertoPrivateSale = 2745000000 * 10 ** 18; // 15% to Private Sale uint256 _transfertoContributors = 10980000000 * 10 ** 18; // 60% to Contributors uint256 _transfertoContributors2 = 1830000000 * 10 ** 18; // 10% to Contributors 2 uint256 _transfertoTechOperationExpenses = 915000000 * 10 ** 18; // 5% to Tech & Operation Expenses uint256 _transfertoMarketingBusinessDev = 915000000 * 10 ** 18; // 5% to Marketing & Business Development uint256 _transfertoEarlyInvestors = 915000000 * 10 ** 18; // 5% to Early Investors // 15% to Private Sale balances[0x8eeC67a193B6B90A4B0047769De8F17a7ee87eB9] = _transfertoPrivateSale; Transfer(address(0), 0x8eeC67a193B6B90A4B0047769De8F17a7ee87eB9, _transfertoPrivateSale); // 60% to Contributors balances[0xc7991555F9F2E731bb2013cfB0ac2dcf6dc4A236] = _transfertoContributors; Transfer(address(0), 0xc7991555F9F2E731bb2013cfB0ac2dcf6dc4A236, _transfertoContributors); // 10% to Contributors 2 balances[0xf26511984b53bf4b96d85355224E06a06180237F] = _transfertoContributors2; Transfer(address(0), 0xf26511984b53bf4b96d85355224E06a06180237F, _transfertoContributors2); // 5% to Tech & Operation Expenses balances[0xDd695A5b4594ad79e3D9cE5280f0A36fde72C70A] = _transfertoTechOperationExpenses; Transfer(address(0), 0xDd695A5b4594ad79e3D9cE5280f0A36fde72C70A, _transfertoTechOperationExpenses); // 5% to Marketing & Business Development balances[0x84B899f535b7128fEC47e53901cE3242CdC9C06f] = _transfertoMarketingBusinessDev; Transfer(address(0), 0x84B899f535b7128fEC47e53901cE3242CdC9C06f, _transfertoMarketingBusinessDev); // 5% to Early Investors balances[0xeD9200CffFBe17af59D288836a9B25520c6CeFa1] = _transfertoEarlyInvestors; Transfer(address(0), 0xeD9200CffFBe17af59D288836a9B25520c6CeFa1, _transfertoEarlyInvestors); } function () public payable { revert(); //Not Applicable } // Start lockup periods function start_LOCKUP(uint _lockupEndDate) public onlyOwner atStage(Stages.LOCKUPNOTSTARTED) { stage = Stages.LOCKUPSTARTED; stopped = false; lockup_startdate = now; lockup_enddate = now + _lockupEndDate * 86400; } // End lockup periods function end_LOCKUP() external onlyOwner atStage(Stages.LOCKUPSTARTED) { require(now > lockup_enddate); stage = Stages.LOCKUPENDED; } // Add address to Private Sale function addtoPrivateSale(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner { addOfPrivateSale[_address] = true; emit EventPrivateSale(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercent, transferDays: 1, transferPercentTotal: _transferPercentTotal, transferDaysTotal: 365, transferLastTransaction: 0, transferTotalSpent: 0, transferPostDate: now, reset: true }); } // Add address to Contributors function addtoContributos(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner { addOfContributors[_address] = true; emit EventContributors(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercent, transferDays: 1, transferPercentTotal: _transferPercentTotal, transferDaysTotal: 365, transferLastTransaction: 0, transferTotalSpent: 0, transferPostDate: now, reset: true }); } // Add address to Contributors2 function addtoContributos2(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner { addOfContributors2[_address] = true; emit EventContributors2(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercent, transferDays: 1, transferPercentTotal: _transferPercentTotal, transferDaysTotal: 365, transferLastTransaction: 0, transferTotalSpent: 0, transferPostDate: now, reset: true }); } // Add address to Tech & Operation function addtoTechOperation(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner { addOfTechOperation[_address] = true; emit EventTechOperation(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercent, transferDays: 1, transferPercentTotal: _transferPercentTotal, transferDaysTotal: 365, transferLastTransaction: 0, transferTotalSpent: 0, transferPostDate: now, reset: true }); } // Add address to Marketing & Business Development function addtoMarketingBusinessDev(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner { addOfMarketingBusinessDev[_address] = true; emit EventMarketingBusinessDev(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercent, transferDays: 1, transferPercentTotal: _transferPercentTotal, transferDaysTotal: 365, transferLastTransaction: 0, transferTotalSpent: 0, transferPostDate: now, reset: true }); } // Add address to Early Investors function addtoEarlyInvestors(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner{ addOfEarlyInvestor[_address] = true; emit EventEarlyInvestor(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercent, transferDays: 1, transferPercentTotal: _transferPercentTotal, transferDaysTotal: 365, transferLastTransaction: 0, transferTotalSpent: 0, transferPostDate: now, reset: true }); } // Add owners function addtoOwners(address _address) public onlyOwner{ addOfOwners[_address] = true; } // what is the total supply of the ech tokens function totalSupply() public view returns (uint256 total_Supply) { total_Supply = _totalsupply; } // What is the balance of a particular account? function balanceOf(address _owner)public view returns (uint256 balance) { return balances[_owner]; } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address _from, address _to, uint256 _amount)public returns (bool success) { require( _to != 0x0); checkTransfer = false; if(addOfOwners[_from]) { checkTransfer = true; } else if(addOfPrivateSale[_from]) { require(checkTransferFunctionPrivateSale(_from, _to, _amount)); } else if(addOfContributors[_from]) { checkTransfer = true; } else if(addOfContributors2[_from] || addOfTechOperation[_from] || addOfMarketingBusinessDev[_from] || addOfEarlyInvestor[_from]) { require(checkTransferFunction(_from, _to, _amount)); } require(checkTransfer == true); require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount >= 0); balances[_from] = (balances[_from]).sub(_amount); allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(_from, _to, _amount); return true; } function checkTransferFunction(address _from, address _to, uint256 _amount) internal returns (bool success) { require(now > lockup_enddate); transferDaysTotal = lockupHolderMap[_from].transferDaysTotal * 86400; transferPostDate = lockupHolderMap[_from].transferPostDate; if(now >= transferPostDate + transferDaysTotal) { lockupHolderMap[_from].transferPostDate = lockupHolderMap[_from].transferPostDate + transferDaysTotal; lockupHolderMap[_from].transferTotalSpent = 0; } transferPercent = lockupHolderMap[_from].transferPercent; transferPercentTotal = lockupHolderMap[_from].transferPercentTotal; transferDays = lockupHolderMap[_from].transferDays * 86400; transferDaysTotal = lockupHolderMap[_from].transferDaysTotal * 86400; transferLastTransaction = lockupHolderMap[_from].transferLastTransaction; transferTotalSpent = lockupHolderMap[_from].transferTotalSpent; transferPostDate = lockupHolderMap[_from].transferPostDate; require((_amount * 10 ** 18) <= ((_totalsupply).mul(transferPercent)).div(100)); require((_amount * 10 ** 18) <= ((_totalsupply).mul(transferPercentTotal)).div(100)); require(now >= transferLastTransaction + transferDays); require((transferTotalSpent * 10 ** 18) <= ((_totalsupply).mul(transferPercentTotal)).div(100)); require(now <= transferPostDate + transferDaysTotal); lockupHolderMap[_from].transferLastTransaction = now; lockupHolderMap[_from].transferTotalSpent += _amount; checkTransfer = true; return true; } function checkTransferFunctionPrivateSale(address _from, address _to, uint256 _amount) internal returns (bool success) { require(stage == Stages.LOCKUPENDED); require(now > lockup_enddate); transferPercent = lockupHolderMap[_from].transferPercent; transferDays = lockupHolderMap[_from].transferDays * 86400; transferLastTransaction = lockupHolderMap[_from].transferLastTransaction; transferTotalSpent = lockupHolderMap[_from].transferTotalSpent; require((_amount * 10 ** 18) <= ((_totalsupply).mul(transferPercent)).div(100)); require(now >= transferLastTransaction + transferDays); lockupHolderMap[_from].transferLastTransaction = now; checkTransfer = true; return true; } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount)public returns (bool success) { require( _spender != 0x0); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender)public view returns (uint256 remaining) { require( _owner != 0x0 && _spender !=0x0); return allowed[_owner][_spender]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount)public returns (bool success) { require( _to != 0x0); require(balances[msg.sender] >= _amount && _amount >= 0); balances[msg.sender] = (balances[msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(msg.sender, _to, _amount); return true; } // Transfer the balance from owner's account to another account function transferTokens(address _to, uint256 _amount) private returns(bool success) { require( _to != 0x0); require(balances[address(this)] >= _amount && _amount > 0); balances[address(this)] = (balances[address(this)]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(address(this), _to, _amount); return true; } // Drain all coins function drain() external onlyOwner { owner.transfer(this.balance); } }
Transfer the balance from owner's account to another account
function transferTokens(address _to, uint256 _amount) private returns(bool success) { require( _to != 0x0); require(balances[address(this)] >= _amount && _amount > 0); balances[address(this)] = (balances[address(this)]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(address(this), _to, _amount); return true; }
973,743
/** <<https://github.com/FidelChe/satellite-broadband-service-chain>> */ // SPDX-License-Identifier: MIT // Solidity code base and design adopted from work done by Kamal Kishor Mehra Blockchain : Pharmaceutical SupplyChain pragma solidity ^0.8.0; import "hardhat/console.sol"; import './Equipment.sol'; import './Equipment_O_P.sol'; import './Equipment_P_E.sol'; contract ServiceChain { address public Owner; // Initiate ServiceChain Contract constructor () public { Owner = msg.sender; } //// OWNER //// // Validate Owner modifier onlyOwner() { require( msg.sender == Owner, "Only owner can call this function." ); _; } enum roles { norole, supplier, transporter, operator, partner, enduser, revoke } // Events event UserRegister(address indexed cryptoAddress, bytes32 Name); event UserRoleRevoked(address indexed cryptoAddress, bytes32 Name, uint Role); event UserRoleRessigne(address indexed cryptoAddress, bytes32 Name, uint Role); /** * @notice Register New user by Owner * @param cryptoAddress Cryptocurrency Network Address of User * @param Name User name * @param Location User Location * @param Role User Role */ function registerUser( address cryptoAddress, bytes32 Name, bytes32 Location, uint Role ) public onlyOwner { require(UsersDetails[cryptoAddress].role == roles.norole, "User Already registered"); UsersDetails[cryptoAddress].name = Name; UsersDetails[cryptoAddress].location = Location; UsersDetails[cryptoAddress].cryptoAddress = cryptoAddress; UsersDetails[cryptoAddress].role = roles(Role); users.push(cryptoAddress); emit UserRegister(cryptoAddress, Name); } // Revoke users role function revokeRole(address userAddress) public onlyOwner { require(UsersDetails[userAddress].role != roles.norole, "User not registered"); emit UserRoleRevoked(userAddress, UsersDetails[userAddress].name,uint(UsersDetails[userAddress].role)); UsersDetails[userAddress].role = roles(6); } // Re-assign new role to User function reassigneRole(address userAddress, uint Role) public onlyOwner { require(UsersDetails[userAddress].role != roles.norole, "User not registered"); UsersDetails[userAddress].role = roles(Role); emit UserRoleRessigne(userAddress, UsersDetails[userAddress].name,uint(UsersDetails[userAddress].role)); } //// USER //// struct UserInfo { bytes32 name; bytes32 location; address cryptoAddress; roles role; } mapping(address => UserInfo) UsersDetails; address[] users; // Get User Information/Profile function getUserInfo(address User) public view returns( bytes32 name, bytes32 location, address cryptoAddress, roles role ) { return ( UsersDetails[User].name, UsersDetails[User].location, UsersDetails[User].cryptoAddress, UsersDetails[User].role); } // Get Number of registered Users function getUsersCount() public view returns(uint count){ return users.length; } // Get User by Index value of stored data // index Indexed Number // User Details function getUserbyIndex(uint index) public view returns( bytes32 name, bytes32 location, address cryptoAddress, roles role ) { return getUserInfo(users[index]); } //// SUPPLIER //// mapping(address => address[]) EquipmentAtSupplier; // Update Package / Equipment batch recieved status by ethier Supplier or Operator function PackageReceived( address pid ) public { require( UsersDetails[msg.sender].role == roles.supplier, "Only supplier can call this function" ); Equipment(pid).receivedPackage(msg.sender); EquipmentAtSupplier[msg.sender].push(pid); } // Get Package Count at Supplier // Number of Packages at Supplier function getPackagesCountS() public view returns(uint count){ require( UsersDetails[msg.sender].role == roles.supplier, "Only supplier can call this function" ); return EquipmentAtSupplier[msg.sender].length; } // Get PackageID by Indexed value of stored data function getPackageIDByIndexM(uint index) public view returns(address BatchID){ require( UsersDetails[msg.sender].role == roles.supplier, "Only supplier can call this function" ); return EquipmentAtSupplier[msg.sender][index]; } mapping(address => address[]) EquipmentBatches; event EquipmentNewBatch( address indexed BatchId, address indexed Supplier, address shipper, address indexed Receiver ); // Create Equipment Batch function packageEquipment( bytes32 Des, bytes32 RM, uint Quant, address Shpr, address Rcvr, uint RcvrType ) public { require( UsersDetails[msg.sender].role == roles.supplier, "Only supplier can call this function" ); require( RcvrType != 0, "Receiver Type must be define" ); Equipment m = new Equipment( msg.sender, Des, RM, Quant, Shpr, Rcvr, RcvrType ); EquipmentBatches[msg.sender].push(address(m)); emit EquipmentNewBatch(address(m), msg.sender, Shpr, Rcvr); } // Get Equipment Batch Count function getBatchesCountS() public view returns (uint count){ require( UsersDetails[msg.sender].role == roles.supplier, "Only Supplier Can call this function." ); return EquipmentBatches[msg.sender].length; } // Get Equipment BatchID by indexed value of stored data function getBatchIdByIndexM(uint index) public view returns(address packageID) { require( UsersDetails[msg.sender].role == roles.supplier, "Only Supplier Can call this function." ); return EquipmentBatches[msg.sender][index]; } //// TRANSPORTER //// // Load consingment for transport one location to another. function loadConsingment( address pid, // Package or Batch ID uint transportertype, address cid // COnsignment ID ) public { require( UsersDetails[msg.sender].role == roles.transporter, "Only Transporter can call this function" ); require( transportertype > 0, "Transporter Type must be define" ); if(transportertype == 1) { // Supplier to operator Equipment(pid).pickPackage(msg.sender); } else if(transportertype == 2) { // operator to partner Equipment_O_P(pid).pickOP(pid,msg.sender); } else if(transportertype == 3) { // partner to enduser Equipment_P_E(pid).pickPE(pid,msg.sender); } } //// OPERATOR //// mapping(address => address[]) EquipmentBatchesAtOperator; //Equipment Batch Received function equipmentReceived( address batchid, address cid ) public { require( UsersDetails[msg.sender].role == roles.operator || UsersDetails[msg.sender].role == roles.partner, "Only Operator and Partner can call this function" ); uint rtype = Equipment(batchid).receivedPackage(msg.sender); if(rtype == 1){ EquipmentBatchesAtOperator[msg.sender].push(batchid); }else if( rtype == 2){ EquipmentBatchesAtOperator[msg.sender].push(batchid); if(Equipment(batchid).getOPE()[0] != address(0)){ Equipment_O_P(cid).recieveOP(batchid,msg.sender); } } } mapping(address => address[]) EquipmentOtoP; mapping(address => address) EquipmentOtoPTxContract; // Sub Contract for Equipment Transfer from Operator to Partner function transferEquipmentOtoP( address BatchID, address Shipper, address Receiver ) public { require( UsersDetails[msg.sender].role == roles.operator && msg.sender == Equipment(BatchID).getOPE()[0], "Only Operator or current owner of package can call this function" ); Equipment_O_P op = new Equipment_O_P( BatchID, msg.sender, Shipper, Receiver ); EquipmentOtoP[msg.sender].push(address(op)); EquipmentOtoPTxContract[BatchID] = address(op); } // Get Equipment Batch Count function getBatchesCountOP() public view returns (uint count){ require( UsersDetails[msg.sender].role == roles.operator, "Only Operator Can call this function." ); return EquipmentOtoP[msg.sender].length; } // Get Equipment BatchID by indexed value of stored data function getBatchIdByIndexOP(uint index) public view returns(address packageID) { require( UsersDetails[msg.sender].role == roles.operator, "Only Operator Can call this function." ); return EquipmentOtoP[msg.sender][index]; } // Get Sub Contract ID of Equipment Batch Transfer in between Operator to Partner function getSubContractOP(address BatchID) public view returns (address SubContractOP) { return EquipmentOtoPTxContract[BatchID]; } //// PARTNER //// mapping(address => address[]) EquipmentBatchAtPartner; mapping(address => address[]) EquipmentPtoE; mapping(address => address) EquipmentPtoETxContract; // Transfer Equipment BatchID in between Partner to EndUser function transferEquipmentPtoE( address BatchID, address Shipper, address Receiver ) public { require( UsersDetails[msg.sender].role == roles.partner && msg.sender == Equipment(BatchID).getOPE()[1], "Only Partner or current owner of package can call this function" ); Equipment_P_E pe = new Equipment_P_E( BatchID, msg.sender, Shipper, Receiver ); EquipmentPtoE[msg.sender].push(address(pe)); EquipmentPtoETxContract[BatchID] = address(pe); } // Get Equipment BatchID Count function getBatchesCountPE() public view returns (uint count){ require( UsersDetails[msg.sender].role == roles.partner, "Only Partner Can call this function." ); return EquipmentPtoE[msg.sender].length; } // Get Equipment BatchID by indexed value of stored data function getBatchIdByIndexPE(uint index) public view returns(address packageID) { require( UsersDetails[msg.sender].role == roles.partner, "Only Partner Can call this function." ); return EquipmentPtoE[msg.sender][index]; } // Get SubContract ID of Equipment Batch Transfer in between Partner to EndUser function getSubContractPE(address BatchID) public view returns (address SubContractPE) { return EquipmentPtoETxContract[BatchID]; } //// END USER //// mapping(address => address[]) EquipmentBatchAtEndUser; mapping(address => equipmentstatus) settled; // Equipment Batch Recieved function EquipmentRecievedAtEndUser( address batchid, address cid ) public { require( UsersDetails[msg.sender].role == roles.enduser, "Only EndUser Can call this function." ); Equipment_P_E(cid).recievePE(batchid, msg.sender); EquipmentBatchAtEndUser[msg.sender].push(batchid); settled[batchid] = equipmentstatus(1); } enum equipmentstatus { notfound, atenduser, paid, expire, damaged } event EquipmentStatus( address BatchID, address indexed EndUser, uint status ); // Update Equipment Batch status function updateSettlementStatus( address BatchID, uint Status ) public { require( UsersDetails[msg.sender].role == roles.enduser && msg.sender == Equipment(BatchID).getOPE()[2], "Only EndUser or current owner of package can call this function" ); require(settled[BatchID] == equipmentstatus(1), "equipment Must be at EndUser"); settled[BatchID] = equipmentstatus(Status); emit EquipmentStatus(BatchID, msg.sender, Status); } // Get Equipment Batch status function settlementinfo( address BatchID ) public view returns( uint Status ){ return uint(settled[BatchID]); } // Get Equipment Batch count // Number of Batches function getBatchesCountE() public view returns(uint count){ require( UsersDetails[msg.sender].role == roles.enduser, "Only Operator or current owner of package can call this function" ); return EquipmentBatchAtEndUser[msg.sender].length; } // Get Equipment BatchID by indexed value of stored data function getBatchIdByIndexE(uint index) public view returns(address BatchID){ require( UsersDetails[msg.sender].role == roles.enduser, "Only Operator or current owner of package can call this function" ); return EquipmentBatchAtEndUser[msg.sender][index]; } }
Register New user by Owner cryptoAddress Cryptocurrency Network Address of User Name User name Location User Location Role User Role/
function registerUser( address cryptoAddress, bytes32 Name, bytes32 Location, uint Role ) public onlyOwner { require(UsersDetails[cryptoAddress].role == roles.norole, "User Already registered"); UsersDetails[cryptoAddress].name = Name; UsersDetails[cryptoAddress].location = Location; UsersDetails[cryptoAddress].cryptoAddress = cryptoAddress; UsersDetails[cryptoAddress].role = roles(Role); users.push(cryptoAddress); emit UserRegister(cryptoAddress, Name); }
886,557
pragma solidity >=0.4.24; import "../math/SafeMath.sol"; /** * @dev 资产列表共通,除资产负债之外提供一个账目清单数组,便于统计和查找. */ library BalanceList { using SafeMath for uint256; struct element { address addr; uint256 idx; uint256 balance; } struct balanceMap { mapping(address => uint256) mapList; element[] list; } function exist(balanceMap storage self, address _addr) internal view returns (bool) { if (self.list.length == 0) return false; return (self.list[self.mapList[_addr]].addr == _addr); } function insert( balanceMap storage self, address _addr, uint256 _amount ) internal returns (bool) { element memory e = element({addr: _addr, idx: self.list.length, balance: _amount}); self.list.push(e); self.mapList[_addr] = e.idx; return true; } function remove(balanceMap storage self, address _addr) internal returns (bool) { if (!exist(self, _addr)) { return false; } if (self.list[self.mapList[_addr]].balance > 0) { return false; } uint256 row2Del = self.mapList[_addr]; element storage keyToMove = self.list[self.list.length.sub(1)]; self.list[row2Del] = keyToMove; self.mapList[keyToMove.addr] = row2Del; self.list.length = self.list.length.sub(1); return true; } function add( balanceMap storage self, address _addr, uint256 _amount ) internal returns (uint256) { // 对于已经存在的数据更新状态即可 if (exist(self, _addr)) { self.list[self.mapList[_addr]].balance = self.list[self.mapList[_addr]] .balance .add(_amount); } else { // 新建数据 require(insert(self, _addr, _amount), "insert data fail"); } return self.list[self.mapList[_addr]].balance; } function sub( balanceMap storage self, address _addr, uint256 _amount ) internal returns (uint256) { require(exist(self, _addr), "can not sub no exist element"); self.list[self.mapList[_addr]].balance = self.list[self.mapList[_addr]] .balance .sub(_amount); if (self.list[self.mapList[_addr]].balance == 0) { require(remove(self, _addr), "remove data fail"); return 0; } return self.list[self.mapList[_addr]].balance; } function count(balanceMap storage self) internal view returns (uint256) { return self.list.length; } function balance(balanceMap storage self, address _addr) internal view returns (uint256) { return exist(self, _addr) ? self.list[self.mapList[_addr]].balance : 0; } function get(balanceMap storage self, uint256 index) internal view returns (element memory) { require(index < self.list.length, "index must small than current count"); return self.list[index]; } // 获取指定下标范围的数据,本函数可以用于分页查询 function getList( balanceMap storage self, uint256 from, uint256 _count ) internal view returns (element[] memory) { require(_count > 0, "count number must bigger than 0"); uint256 _idx = 0; element[] memory res = new element[](_count); for (uint256 i = from; i < self.list.length; i++) { if (_idx == _count) { break; } res[_idx] = self.list[i]; _idx = _idx.add(1); } return res; } }
获取指定下标范围的数据,本函数可以用于分页查询
function getList( balanceMap storage self, uint256 from, uint256 _count ) internal view returns (element[] memory) { require(_count > 0, "count number must bigger than 0"); uint256 _idx = 0; element[] memory res = new element[](_count); for (uint256 i = from; i < self.list.length; i++) { if (_idx == _count) { break; } res[_idx] = self.list[i]; _idx = _idx.add(1); } return res; }
1,847,499
./partial_match/56/0xe3085D1c23242A7c4DbE54774452eb8763664906/sources/MasterChef.sol
Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 _SHUFPerBlock) public onlyOwner { massUpdatePools(); SHUFPerBlock = _SHUFPerBlock; }
11,091,028
// SPDX-License-Identifier: MIT pragma solidity 0.5.5; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } /** * @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; } } contract Stablecoin is ERC20, ERC20Detailed, ReentrancyGuard { PriceSource public ethPriceSource; using SafeMath for uint256; uint256 private _minimumCollateralPercentage; IMyVault public erc721; uint256 public vaultCount; uint256 public debtCeiling; uint256 public closingFee; uint256 public openingFee; uint256 public treasury; uint256 public tokenPeg; mapping(uint256 => bool) public vaultExistence; mapping(uint256 => address) public vaultOwner; mapping(uint256 => uint256) public vaultCollateral; mapping(uint256 => uint256) public vaultDebt; address public stabilityPool; event CreateVault(uint256 vaultID, address creator); event DestroyVault(uint256 vaultID); event TransferVault(uint256 vaultID, address from, address to); event DepositCollateral(uint256 vaultID, uint256 amount); event WithdrawCollateral(uint256 vaultID, uint256 amount); event BorrowToken(uint256 vaultID, uint256 amount); event PayBackToken(uint256 vaultID, uint256 amount, uint256 closingFee); event BuyRiskyVault(uint256 vaultID, address owner, address buyer, uint256 amountPaid); constructor( address ethPriceSourceAddress, uint256 minimumCollateralPercentage, string memory name, string memory symbol, address vaultAddress ) ERC20Detailed(name, symbol, 18) public { assert(ethPriceSourceAddress != address(0)); assert(minimumCollateralPercentage != 0); // | decimals start here debtCeiling=10000000000000000000;// 10 dollas closingFee=50; // 0.5% openingFee=0; // 0.0% ethPriceSource = PriceSource(ethPriceSourceAddress); stabilityPool=address(0); tokenPeg = 100000000; // $1 erc721 = IMyVault(vaultAddress); _minimumCollateralPercentage = minimumCollateralPercentage; } modifier onlyVaultOwner(uint256 vaultID) { require(vaultExistence[vaultID], "Vault does not exist"); require(vaultOwner[vaultID] == msg.sender, "Vault is not owned by you"); _; } function getDebtCeiling() external view returns (uint256){ return debtCeiling; } function getClosingFee() external view returns (uint256){ return closingFee; } function getOpeningFee() external view returns (uint256){ return openingFee; } function getTokenPriceSource() public view returns (uint256){ return tokenPeg; } function getEthPriceSource() public view returns (uint256){ (,int price,,,) = ethPriceSource.latestRoundData(); return uint256(price); } function calculateCollateralProperties(uint256 collateral, uint256 debt) private view returns (uint256, uint256) { assert(getEthPriceSource() != 0); assert(getTokenPriceSource() != 0); uint256 collateralValue = collateral.mul(getEthPriceSource() ); assert(collateralValue >= collateral); uint256 debtValue = debt.mul(getTokenPriceSource()); assert(debtValue >= debt); uint256 collateralValueTimes100 = collateralValue.mul(100); assert(collateralValueTimes100 > collateralValue); return (collateralValueTimes100, debtValue); } function isValidCollateral(uint256 collateral, uint256 debt) private view returns (bool) { (uint256 collateralValueTimes100, uint256 debtValue) = calculateCollateralProperties(collateral, debt); uint256 collateralPercentage = collateralValueTimes100.div(debtValue); return collateralPercentage >= _minimumCollateralPercentage; } function createVault() external returns (uint256) { uint256 id = vaultCount; vaultCount = vaultCount.add(1); assert(vaultCount >= id); vaultExistence[id] = true; vaultOwner[id] = msg.sender; emit CreateVault(id, msg.sender); // mint erc721 (vaultId) erc721.mint(msg.sender,id); return id; } function destroyVault(uint256 vaultID) external onlyVaultOwner(vaultID) nonReentrant { require(vaultDebt[vaultID] == 0, "Vault has outstanding debt"); if(vaultCollateral[vaultID]!=0) { msg.sender.transfer(vaultCollateral[vaultID]); } // burn erc721 (vaultId) erc721.burn(vaultID); delete vaultExistence[vaultID]; delete vaultOwner[vaultID]; delete vaultCollateral[vaultID]; delete vaultDebt[vaultID]; emit DestroyVault(vaultID); } function transferVault(uint256 vaultID, address to) external onlyVaultOwner(vaultID) { vaultOwner[vaultID] = to; // burn erc721 (vaultId) erc721.burn(vaultID); // mint erc721 (vaultId) erc721.mint(to,vaultID); emit TransferVault(vaultID, msg.sender, to); } function depositCollateral(uint256 vaultID) external payable onlyVaultOwner(vaultID) { uint256 newCollateral = vaultCollateral[vaultID].add(msg.value); assert(newCollateral >= vaultCollateral[vaultID]); vaultCollateral[vaultID] = newCollateral; emit DepositCollateral(vaultID, msg.value); } function withdrawCollateral(uint256 vaultID, uint256 amount) external onlyVaultOwner(vaultID) nonReentrant { require(vaultCollateral[vaultID] >= amount, "Vault does not have enough collateral"); uint256 newCollateral = vaultCollateral[vaultID].sub(amount); if(vaultDebt[vaultID] != 0) { require(isValidCollateral(newCollateral, vaultDebt[vaultID]), "Withdrawal would put vault below minimum collateral percentage"); } vaultCollateral[vaultID] = newCollateral; msg.sender.transfer(amount); emit WithdrawCollateral(vaultID, amount); } function borrowToken(uint256 vaultID, uint256 amount) external onlyVaultOwner(vaultID) { require(amount > 0, "Must borrow non-zero amount"); require(totalSupply().add(amount) <= debtCeiling, "borrowToken: Cannot mint over totalSupply."); uint256 newDebt = vaultDebt[vaultID].add(amount); assert(newDebt > vaultDebt[vaultID]); require(isValidCollateral(vaultCollateral[vaultID], newDebt), "Borrow would put vault below minimum collateral percentage"); vaultDebt[vaultID] = newDebt; _mint(msg.sender, amount); emit BorrowToken(vaultID, amount); } function payBackToken(uint256 vaultID, uint256 amount) external onlyVaultOwner(vaultID) { require(balanceOf(msg.sender) >= amount, "Token balance too low"); require(vaultDebt[vaultID] >= amount, "Vault debt less than amount to pay back"); uint256 _closingFee = (amount.mul(closingFee).mul(getTokenPriceSource())).div(getEthPriceSource().mul(10000)); vaultDebt[vaultID] = vaultDebt[vaultID].sub(amount); vaultCollateral[vaultID]=vaultCollateral[vaultID].sub(_closingFee); vaultCollateral[treasury]=vaultCollateral[treasury].add(_closingFee); _burn(msg.sender, amount); emit PayBackToken(vaultID, amount, _closingFee); } function buyRiskyVault(uint256 vaultID) external { require(vaultExistence[vaultID], "Vault does not exist"); require(stabilityPool==address(0) || msg.sender == stabilityPool, "buyRiskyVault disabled for public"); (uint256 collateralValueTimes100, uint256 debtValue) = calculateCollateralProperties(vaultCollateral[vaultID], vaultDebt[vaultID]); uint256 collateralPercentage = collateralValueTimes100.div(debtValue); require(collateralPercentage < _minimumCollateralPercentage, "Vault is not below minimum collateral percentage"); uint256 maximumDebtValue = collateralValueTimes100.div(_minimumCollateralPercentage); uint256 maximumDebt = maximumDebtValue.div(getTokenPriceSource() ); uint256 debtDifference = vaultDebt[vaultID].sub(maximumDebt); require(balanceOf(msg.sender) >= debtDifference, "Token balance too low to pay off outstanding debt"); address previousOwner = vaultOwner[vaultID]; vaultOwner[vaultID] = msg.sender; vaultDebt[vaultID] = maximumDebt; uint256 _closingFee = (debtDifference.mul(closingFee).mul(getTokenPriceSource()) ).div(getEthPriceSource().mul(10000)); vaultCollateral[vaultID]=vaultCollateral[vaultID].sub(_closingFee); vaultCollateral[treasury]=vaultCollateral[treasury].add(_closingFee); _burn(msg.sender, debtDifference); // burn erc721 (vaultId) erc721.burn(vaultID); // mint erc721 (vaultId) erc721.mint(msg.sender,vaultID); emit BuyRiskyVault(vaultID, previousOwner, msg.sender, debtDifference); } } interface IMyVault { function burn(uint256 tokenId) external; function mint(address to, uint256 tokenId) external; } interface PriceSource { function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound); } contract QiStablecoin is Stablecoin, Ownable { constructor( address ethPriceSourceAddress, uint256 minimumCollateralPercentage, string memory name, string memory symbol, address vaultAddress ) Stablecoin( ethPriceSourceAddress, minimumCollateralPercentage, name, symbol, vaultAddress ) public { treasury=0; } function mint(address account, uint256 amount) external onlyOwner() { _mint(account, amount); } function burn(address account, uint256 amount) external onlyOwner() { _burn(account, amount); } function changeEthPriceSource(address ethPriceSourceAddress) external onlyOwner() { ethPriceSource = PriceSource(ethPriceSourceAddress); } function setTokenPeg(uint256 _tokenPeg) external onlyOwner() { tokenPeg = _tokenPeg; } function setStabilityPool(address _pool) external onlyOwner() { stabilityPool = _pool; } function setDebtCeiling(uint256 amount) external onlyOwner() { require(totalSupply()<=amount, "setCeiling: Must be over the amount of outstanding debt."); debtCeiling = amount; } function setClosingFee(uint256 amount) external onlyOwner() { closingFee = amount; } function setOpeningFee(uint256 amount) external onlyOwner() { openingFee = amount; } function setTreasury(uint256 _treasury) external onlyOwner() { require(vaultExistence[_treasury], "Vault does not exist"); treasury = _treasury; } }
burn erc721 (vaultId) mint erc721 (vaultId)
function buyRiskyVault(uint256 vaultID) external { require(vaultExistence[vaultID], "Vault does not exist"); require(stabilityPool==address(0) || msg.sender == stabilityPool, "buyRiskyVault disabled for public"); (uint256 collateralValueTimes100, uint256 debtValue) = calculateCollateralProperties(vaultCollateral[vaultID], vaultDebt[vaultID]); uint256 collateralPercentage = collateralValueTimes100.div(debtValue); require(collateralPercentage < _minimumCollateralPercentage, "Vault is not below minimum collateral percentage"); uint256 maximumDebtValue = collateralValueTimes100.div(_minimumCollateralPercentage); uint256 maximumDebt = maximumDebtValue.div(getTokenPriceSource() ); uint256 debtDifference = vaultDebt[vaultID].sub(maximumDebt); require(balanceOf(msg.sender) >= debtDifference, "Token balance too low to pay off outstanding debt"); address previousOwner = vaultOwner[vaultID]; vaultOwner[vaultID] = msg.sender; vaultDebt[vaultID] = maximumDebt; uint256 _closingFee = (debtDifference.mul(closingFee).mul(getTokenPriceSource()) ).div(getEthPriceSource().mul(10000)); vaultCollateral[vaultID]=vaultCollateral[vaultID].sub(_closingFee); vaultCollateral[treasury]=vaultCollateral[treasury].add(_closingFee); _burn(msg.sender, debtDifference); erc721.burn(vaultID); erc721.mint(msg.sender,vaultID); emit BuyRiskyVault(vaultID, previousOwner, msg.sender, debtDifference); }
1,191,884
pragma solidity ^0.4.23; /** https://zethr.io https://zethr.io https://zethr.io https://zethr.io https://zethr.io ███████╗███████╗████████╗██╗ ██╗██████╗ ╚══███╔╝██╔════╝╚══██╔══╝██║ ██║██╔══██╗ ███╔╝ █████╗ ██║ ███████║██████╔╝ ███╔╝ ██╔══╝ ██║ ██╔══██║██╔══██╗ ███████╗███████╗ ██║ ██║ ██║██║ ██║ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ .------..------. .------..------..------. .------..------..------..------..------. |B.--. ||E.--. |.-. |T.--. ||H.--. ||E.--. |.-. |H.--. ||O.--. ||U.--. ||S.--. ||E.--. | | :(): || (\/) (( )) | :/\: || :/\: || (\/) (( )) | :/\: || :/\: || (\/) || :/\: || (\/) | | ()() || :\/: |&#39;-.-.| (__) || (__) || :\/: |&#39;-.-.| (__) || :\/: || :\/: || :\/: || :\/: | | &#39;--&#39;B|| &#39;--&#39;E| (( )) &#39;--&#39;T|| &#39;--&#39;H|| &#39;--&#39;E| (( )) &#39;--&#39;H|| &#39;--&#39;O|| &#39;--&#39;U|| &#39;--&#39;S|| &#39;--&#39;E| `------&#39;`------&#39; &#39;-&#39;`------&#39;`------&#39;`------&#39; &#39;-&#39;`------&#39;`------&#39;`------&#39;`------&#39;`------&#39; An interactive, variable-dividend rate contract with an ICO-capped price floor and collectibles. Bankroll contract, containing tokens purchased from all dividend-card profit and ICO dividends. Acts as token repository for games on the Zethr platform. Credits ======= Analysis: blurr Randall Contract Developers: Etherguy klob Norsefire Front-End Design: cryptodude oguzhanox TropicalRogue **/ contract ZTHInterface { function buyAndSetDivPercentage(address _referredBy, uint8 _divChoice, string providedUnhashedPass) public payable returns (uint); function balanceOf(address who) public view returns (uint); function transfer(address _to, uint _value) public returns (bool); function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns (bool); function exit() public; function sell(uint amountOfTokens) public; function withdraw(address _recipient) public; function getUserAverageDividendRate(address user) public view returns (uint); } // Interface of zethr games contract ZethrGameInterface{ function execute(address from, uint value, uint userDivRate, bytes data) public; } contract ERC223Receiving { function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool); } // Interface of master bankroll contract ZethrBankroll { address public stakeAddress; mapping (address => bool) public isOwner; function changeAllocation(address what, int delta) public; } // Library to return the actual tier of an average dividend rate library ZethrTierLibrary{ uint constant internal magnitude = 2**64; // Gets the tier (1-7) of the divs sent based off of average dividend rate // This is an index used to call into the correct sub-bankroll to withdraw tokens function getTier(uint divRate) internal pure returns (uint){ // Divide the average dividned rate by magnitude // Remainder doesn&#39;t matter because of the below logic uint actualDiv = divRate / magnitude; if (actualDiv >= 30){ return 7; } else if (actualDiv >= 25){ return 6; } else if (actualDiv >= 20){ return 5; } else if (actualDiv >= 15){ return 4; } else if (actualDiv >= 10){ return 3; } else if (actualDiv >= 5){ return 2; } else if (actualDiv >= 2){ return 1; } else{ // Should be impossible revert(); } } } contract ZethrTokenBankroll is ERC223Receiving { /*================================= = LIST OF OWNERS = =================================*/ /* This list is for reference/identification purposes only, and comprises the eight core Zethr developers. For game contracts to be listed, they must be approved by a majority (i.e. currently five) of the owners. Contracts can be delisted in an emergency by a single owner. 0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae // Norsefire 0x11e52c75998fe2E7928B191bfc5B25937Ca16741 // klob 0x20C945800de43394F70D789874a4daC9cFA57451 // Etherguy 0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB // blurr 0x8537aa2911b193e5B377938A723D805bb0865670 // oguzhanox 0x9D221b2100CbE5F05a0d2048E2556a6Df6f9a6C3 // Randall 0x71009e9E4e5e68e77ECc7ef2f2E95cbD98c6E696 // cryptodude 0xDa83156106c4dba7A26E9bF2Ca91E273350aa551 // TropicalRogue */ // Mapping of whitelisted contracts mapping(address => bool) public whitelistedContract; // Daily allocation mapping is master bankroll // mapping(address => uint) public dailyAllocation; mapping (address => uint) public tokenVolumeInput; // tokens in per game mapping (address => uint) public tokenVolumeOutput; // tokens out per game mapping (address => uint) public gameTokenAmount; // track tokens per game mapping (address => uint) public gameTokenAllocation; // game token allocation // "free" tokens in the contract, can be allocated to games uint public freeTokens; // List of all games address[] public games; // Zethr main contract address address Zethr; // Zethr interface ZTHInterface ZethrContract; // Zethr bankroll address address ZethrMainBankroll; // Dividend rate of this tokenBankroll uint public divRate; // "tier" of this tokeknBankroll (1-7) uint public tier; // Magnitude for calculating average div rate uint constant internal magnitude = 2**64; // Requires supplied address to be a whitelisted contract // Pulls from master bankroll modifier contractIsWhiteListed(address ctr){ require(whitelistedContract[ctr]); _; } // Requires msg.sender to be a dev or the bankroll modifier onlyDevOrBankroll(){ require(msg.sender == ZethrMainBankroll || ZethrBankroll(ZethrMainBankroll).isOwner(msg.sender)); _; } // Requires msg.sender to be a dev modifier onlyDev(){ require(ZethrBankroll(ZethrMainBankroll).isOwner(msg.sender)); _; } /*================================= = PUBLIC FUNCTIONS = =================================*/ /// @dev Contract constructor sets sub roll divrate constructor (uint ctrDivRate) public { // Set the address of Zethr main contract Zethr = address(0xD48B633045af65fF636F3c6edd744748351E020D); // Instantiate the Zethr contract ZethrContract = ZTHInterface(Zethr); // Set the master bankroll address ZethrMainBankroll = address(0x1866abdba62468c33c32eb9cc366923af4b760f9); // Dev addresses are pulled from the bankroll // Set this tokenBankroll&#39;s dividend rate divRate = ctrDivRate; // Set this token&#39;s dividend tier (1-7) tier = ZethrTierLibrary.getTier(divRate * magnitude); } // Admin / bankroll function to change bankroll address function setBankroll(address bankrollAddress) public onlyDevOrBankroll() { ZethrMainBankroll = bankrollAddress; } // Assembly function // Takes: bytes data as input // Returns: the address we want to call // plus the remaining bytes of data which should be fed to the game /* Layout of the actual bytes data as input: First bytes32: an address you want to call to (the game address) (Optional) extra bytes32: remaining data Padding of the address is how we see it in raw tx data: 0x00...address Input MUST have bytes which are a multiple of 32 Input MUST have at least one bytes32 Test cases Only address 0x000000000000000000000000Da83156106c4dba7A26E9bF2Ca91E273350aa551 Address + bytes 0x000000000000000000000000Da83156106c4dba7A26E9bF2Ca91E273350aa551000000000000000000000000Da83156106c4dba7A26E9bF2Ca91E273350aa551 Address + 2 bytes 0x000000000000000000000000Da83156106c4dba7A26E9bF2Ca91E273350aa551000000000000000000000000Da83156106c4dba7A26E9bF2Ca91E273350aa551000000000000000000000000Da83156106c4dba7A26E9bF2Ca91E273350aa551 Error cases: Not a multiple of 32 0x000000000000000000000000Da83156106c4dba7A26E9bF2Ca91E273350aa5 Empty 0x0 Note: sanity check is done after the getData call to check if address is a contract */ function getData(bytes data) public pure returns (address, bytes rem) { // edge case: len 0 should revert // case: len 1 should only parse addr and empty bytes // case: len more should forloop over bytes and dump them require(data.length == (data.length/32) * 32); // sanity check only bytes32 multiples // no address found if (data.length == 0) { revert(); // no data } address out_a; bytes memory out_b; // initialzie to empty array // start the assembly magic if (data.length == 32){ // ONLY an address, rest is empty data. Fine! assembly { // Things to know here: // x := bla sets x to bla // mload loads 32 bytes, the input is the memory slot // vars used here are actually POINTERS not the actual data! // Logic (IMPORTANT) // A bytes is laid out in solidity as: // first bytes32: a uint which has the LENGTH of this byte // the length of the byte is the numbers of bytes (so in here its a multiple of 32, aka 0x20!) //So if we want to retrieve the actual data at the first slot (hence, the address) we need //to add 32 bytes to the actual pointer of data, to skip over the length bytes32 //then we load this bytes32 and dump it into out_a out_a := mload(add(data, 0x20)) // load first byte into the address slot } } else{ // Logic: remove 32 from the actual data length because we want to remove the game address from the data // (Why do that here not in the game? Because it adds a load of code) uint len = data.length - 32; assembly { out_a := mload(add(data, 0x20)) // load first byte into the address slot, same as above in case of only the address // at the out_b pointer, we store the length we want this bytes to have // yup - thats the number of bytes in data (data.length) minus 32 as defined above mstore(out_b, len) // now we will actually fill this bytes // for loop: for(uint i=0; i<len; i++) for { let i := 0 } lt(i, div(len, 0x20)) { i := add(i, 0x1) } { // calculate the memory slot we want to dump data in: // take the out_b pointer // add 32 * (i+1) to this (could have optimized this) let mem_slot := add(out_b, mul(0x20, add(i,1))) // calculate the load slot where we want to actually read memory from // this is the same as the memory slot we want to write to, +32 // this makes sense becausae we want to basically move all bytes32 one place back! let load_slot := add(mem_slot,0x20) // actually dump the loaded memory at load_slot into mem_slot mstore(mem_slot, mload(load_slot)) } } } //uint codelen; //assembly{ // codelen := extcodesize(out_a) //} // require(codelen > 0); // sanity check we are delegate of a contract return (out_a, out_b); } // Returns true if supplied address is a contract // Does not return true if this contract is deployed during this block function isContract(address ctr) internal view returns (bool){ uint codelen; assembly{ codelen := extcodesize(ctr) } return (codelen > 0); } // Token fallback - gets entered when users transfer tokens to this contract function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool) { // Can only be called from Zethr require(msg.sender == Zethr); // Get the user&#39;s dividend rate // This is a big nasty number uint userDivRate = ZethrContract.getUserAverageDividendRate(_from); // Calculate the user&#39;s tier, and make sure it is appropriate for this contract // (sanity check) require(ZethrTierLibrary.getTier(userDivRate) == tier); address target; bytes memory remaining_data; // Grab the data we want to forward (target is the game address) (target, remaining_data) = getData(_data); // Sanity check to make sure we&#39;re calling a contract require(isContract(target)); // Sanity check to make sure this game is actually one which can use the bankroll require(whitelistedContract[target]); // Add tokens the game&#39;s token amount counter (for this contract only) gameTokenAmount[target] = SafeMath.add(gameTokenAmount[target], _amountOfTokens); // Add tokens the game&#39;s token volume counter (for this contract only) tokenVolumeInput[target] = SafeMath.add(tokenVolumeInput[target], _amountOfTokens); // EXECUTE the actual game! // Call into the game with data ZethrGameInterface(target).execute(_from, _amountOfTokens, userDivRate, remaining_data); } // Function called ONLY by a whitelisted game // Sends tokens to the target address (player) function gameRequestTokens(address target, uint tokens) public contractIsWhiteListed(msg.sender) { // Don&#39;t sent more tokens than the game owns require(gameTokenAmount[msg.sender] >= tokens); // Subtract the amount of tokens the game owns gameTokenAmount[msg.sender] = gameTokenAmount[msg.sender] - tokens; // Update output volume tokenVolumeOutput[msg.sender] = tokenVolumeOutput[msg.sender] + tokens; // Actually transfer. Re-entrancy possibility ZethrContract.transfer(target, tokens); } // Add a game to the whitelist. Can only be called by dev or bankroll. function addGame(address game, uint allocated) onlyDevOrBankroll public { // Push the game address to the list games.push(game); // Set the token allocation gameTokenAllocation[game] = allocated; // If we have enough "free" tokens, allocate them if (freeTokens >= allocated){ freeTokens = SafeMath.sub(freeTokens, allocated); gameTokenAmount[game] = allocated; } // Change this tokenbankroll&#39;s allocation ZethrBankroll(ZethrMainBankroll).changeAllocation(address(this), int(allocated)); // Ad the game to the whitelisted addresses whitelistedContract[game] = true; } // Remove the game from the list & dewhitelist it function removeGame(address game) public onlyDevOrBankroll contractIsWhiteListed(game) // Only remove games which are added { // Loop over games to find the actual index to remove for (uint i=0; i < games.length; i++){ if (games[i] == game){ games[i] = address(0x0); // Delete it if (i != games.length){ // If its NOT at the end remove the last game address into the array TO this position games[i] = games[games.length]; } games.length = games.length - 1; // Remove 1 from length break; // Found it, great } } // Add remaining tokens from game to the "free" list freeTokens = SafeMath.add(freeTokens, gameTokenAmount[game]); // Aint got no tokens gameTokenAmount[game] = 0; // Aint whitelisted whitelistedContract[game] = false; // Change this tokenBankroll&#39;s allocation ZethrBankroll(ZethrMainBankroll).changeAllocation(address(this), int(-gameTokenAllocation[game])); // No allocate gameTokenAllocation[game] = 0; } // Callable from games to change their own token allocation // The game must have "free" tokens // Triggers a change in the tokenBankroll&#39;s allocation amount on the master bankroll function changeAllocation(int delta) public contractIsWhiteListed(msg.sender) { uint newAlloc; // We need to INCREASE token allocation: if (delta > 0){ // Calculate new allocation newAlloc = SafeMath.add(gameTokenAllocation[msg.sender], uint(delta)); // It SHOULD have enough tokens require(gameTokenAmount[msg.sender] >= newAlloc); // Set the game&#39;s token allocation gameTokenAllocation[msg.sender] = newAlloc; // Set this tokenBankroll&#39;s allocation (increase it) ZethrBankroll(ZethrMainBankroll).changeAllocation(address(this), delta); } else { // We need to DECREASE token allocation: // Calculate the new allocation newAlloc = SafeMath.sub(gameTokenAllocation[msg.sender], uint(-delta)); // Set the game&#39;s token allocation gameTokenAllocation[msg.sender] = newAlloc; // Set this tokenBankroll&#39;s allocation (decrease it) ZethrBankroll(ZethrMainBankroll).changeAllocation(address(this), delta); } } // Allocates tokens to games // Also buys in if balance >= 0.1 ETH function allocateTokens() onlyDevOrBankroll public { // Withdraw divs first ZethrContract.withdraw(address(this)); // Buy in, but only if balance >= 0.1 ETH if (address(this).balance >= (0.1 ether)){ zethrBuyIn(); } // Store current game address for loop address gameAddress; // Stoe game&#39;s balance for loop uint gameBalance; // Store game&#39;s allotment for loop uint gameAllotment; // Store game&#39;s difference (positive or negative) in tokenBalance vs tokenAllotment int difference; // Loop over each game // Remove any "free" tokens (auto-withdraw) over its allotment for (uint i=0; i < games.length; i++) { // Grab the info about this game&#39;s token amounts gameAddress = games[i]; gameBalance = gameTokenAmount[gameAddress]; gameAllotment = gameTokenAllocation[gameAddress]; // Calculate deltaTokens (positive if it has more than it needs, negative if it needs tokens) difference = int(gameBalance) - int(gameAllotment); // If the game has extra tokens, re-allocate them to the "free" balance // This reminds me of when I had to write malloc() for my C class // I hated that shit if (difference > 0) { // Game now has exactly the amount of tokens it needs gameTokenAmount[gameAddress] = gameAllotment; // "Free" the extra freeTokens = freeTokens + uint(difference); } else { // This means it needs tokenks. We&#39;ll address that in the next for loop. } } // Now that all games have had their excess removed, loop through the games again and allocated them tokens // We /will/ have enough tokens to allocate - because we bought in ETH. for (uint j=0; j < games.length; j++) { // Grab the info about this game&#39;s token amounts gameAddress = games[i]; gameBalance = gameTokenAmount[gameAddress]; gameAllotment = gameTokenAllocation[gameAddress]; // Calculate deltaTokens (either zero or negative in this case) difference = int(gameBalance) - int(gameAllotment); // Game either has zero or negative tokens // If it has negative tokens, allocate it tokens out of the free balance if (difference < 0) { // Sanity check require(freeTokens >= uint(-difference)); // Subtract from free tokens freeTokens = freeTokens - uint(-difference); // Allocate gameTokenAmount[gameAddress] = gameAllotment; } } // After the above two for loops, every game has // a) no excess tokens // b) exactly it&#39;s allotment of tokens // There will probably be some free tokens left over due to the 1% extra ETH deposit. } // Dump all free tokens back to the main bankroll function dumpFreeTokens(address stakeAddress) onlyDevOrBankroll public returns (uint) { // First, allocate tokens allocateTokens(); // Don&#39;t transfer tokens if we have less than 1 free token if (freeTokens < 1e18) { return 0; } // Transfer free tokens to bankroll ZethrContract.transfer(stakeAddress, freeTokens); // Set free tokens to zero uint sent = freeTokens; freeTokens = 0; // Return the number of tokens we sent return sent; } // Contract withdraw free tokens back to the free tokens function contractTokenWithdrawToFreeTokens(address ctr, uint amount) onlyDevOrBankroll contractIsWhiteListed(ctr) public { uint currentBalance = gameTokenAmount[ctr]; uint allocated = gameTokenAllocation[ctr]; if ( SafeMath.sub(currentBalance, amount) > allocated){ gameTokenAmount[ctr] = gameTokenAmount[ctr] - amount; freeTokens = SafeMath.add(freeTokens, amount); } else{ revert(); } } // Function to buy in tokens with Ethereum // Updates free tokens so they can be allocated function zethrBuyIn() onlyDevOrBankroll public { // Only buy in if balance >= 0.1 ETH if (address(this).balance < 0.1 ether) { return; } // Grab the tokenBankroll&#39;s token balance uint cBal = ZethrContract.balanceOf(address(this)); // Buy in with entire balance (divs go to bankroll) ZethrContract.buyAndSetDivPercentage.value(address(this).balance)(ZethrMainBankroll, uint8(divRate), ""); // Calculate and increment freeTokens freeTokens = freeTokens + (ZethrContract.balanceOf(address(this)) - cBal); } // Emergency this fucks up free tokens // Need a redeploy after this function WithdrawTokensToBankroll(uint amount) onlyDevOrBankroll public { ZethrContract.transfer(ZethrMainBankroll, amount); } // Withdraw eth function WithdrawToBankroll() public { ZethrMainBankroll.transfer(address(this).balance); } // Withdraw divs and send to bankroll function WithdrawAndTransferToBankroll() public { ZethrContract.withdraw(ZethrMainBankroll); WithdrawToBankroll(); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint 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 numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } }
Divide the average dividned rate by magnitude Remainder doesn&39;t matter because of the below logic Should be impossible
function getTier(uint divRate) internal pure returns (uint){ uint actualDiv = divRate / magnitude; if (actualDiv >= 30){ return 7; } else if (actualDiv >= 25){ return 6; } else if (actualDiv >= 20){ return 5; } else if (actualDiv >= 15){ return 4; } else if (actualDiv >= 10){ return 3; } else if (actualDiv >= 5){ return 2; } else if (actualDiv >= 2){ return 1; } else{ revert(); } }
15,147,264
pragma solidity ^0.6.0; import "./IERC20.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; contract Farm is Ownable { using SafeMath for uint; IERC20 public STBU; IERC20 public LPtoken; struct stakeHolder { uint256 calcBlock; uint256 totalClaimed; } bool public active; uint256 public roi; uint256 public endBlock; uint256 public startBlock; uint256 public totalBlocks; uint256 private percentage; uint256 public rewardAllocation; uint256 public defaultStakePerBlock; mapping (address => uint256) public balance; mapping(address => stakeHolder) public holders; event LogClaim(address, uint256); constructor(address _LP, address _STBU) public { LPtoken = IERC20(_LP); STBU = IERC20(_STBU); roi = 10**18; percentage = 10**18; uint256 stake = 10**18; defaultStakePerBlock = stake.mul(220).div(100); totalBlocks = 2296215; } /** * @dev Throws if contract is not active. */ modifier isActive() { require(active, "Farm: is not active"); _; } /** * @dev Activating the staking with start block. * Can only be called by the current owner. */ function activate() public onlyOwner returns (bool){ startBlock = block.number; endBlock = startBlock.add(totalBlocks); rewardAllocation = defaultStakePerBlock.mul(totalBlocks); active = true; return true; } /** * @dev Deactivating the staking. * Can only be called by the current owner. */ function deactivate() public onlyOwner returns (bool) { active = false; endBlock = block.number; require(STBU.transfer(owner(), STBU.balanceOf(address(this))), "Deactivation: transfer failure"); return true; } /** * @dev Pause/unpause the staking. * Can only be called by the current owner. */ function pause(bool _value) public onlyOwner returns (bool) { active = _value; return true; } /** * @dev get current stake per block. */ function getStakePerBlock() public view returns (uint256) { return rewardAllocation.div(totalBlocks); } /** * @dev Returns the share of the holder. */ function stakeholderShare(address user) public view returns (uint256) { uint256 hBalance = balance[user]; uint256 supply = LPtoken.balanceOf(address(this)); if (supply > 0) { return hBalance.mul(percentage).div(supply); } return 0; } /** * @dev Deposits the LP tokens. * Can only be called when contract is active. */ function depositLPTokens (uint256 _amount) public isActive { address from = msg.sender; address to = address(this); require(block.number >= holders[from].calcBlock, "Deposit: unable to calculate block"); require(endBlock > block.number, "Farm: is not active"); if (balance[from] > 0) { _claim(from); } require(LPtoken.transferFrom(from, to, _amount), "LP: unable to transfer coins"); balance[from] = balance[from].add(_amount); _calculateHolder(from); } /** * @dev Claim STBU reward. * Can only be called when contract is active. */ function claim () public isActive { address _to = msg.sender; _claim(_to); _calculateHolder(_to); } /** * @dev Claim STBU reward and Unstake LP tokens. * Can only be called when contract is active. */ function claimAndUnstake () public isActive { address _to = msg.sender; uint _balance = balance[_to]; _claim(_to); balance[_to] = 0; require(LPtoken.transfer(_to, _balance), "LP: unable to transfer coins"); _calculateHolder(_to); } /** * @dev Unstake LP tokens. * Can only be called when contract is active. */ function unstake(uint256 _amount) public isActive { address _to = msg.sender; uint _balance = balance[_to]; require(_balance >= _amount, "LP: wrong amount"); _claim(_to); balance[_to] = _balance.sub(_amount); require(LPtoken.transfer(_to, _amount), "LP: unable to transfer coins"); _calculateHolder(_to); } /** * @dev Calcultae share and roi for the holder */ function _calculateHolder(address holder) internal { stakeHolder memory sH = holders[holder]; sH.calcBlock = block.number; holders[holder] = sH; } /** * @dev Send available reward to the holder */ function _claim(address _to) internal { uint _staked = _calculateStaked(_to); holders[_to].totalClaimed = holders[_to].totalClaimed.add(_staked); rewardAllocation = rewardAllocation.sub(_staked); require(STBU.transfer(_to, _staked)); emit LogClaim(_to, _staked); } /** * @dev Calculate available reward for the holder */ function _calculateStaked(address holder) internal view returns(uint256){ stakeHolder memory st = holders[holder]; uint256 share = stakeholderShare(holder); uint256 currentBlock = block.number; uint256 amountBlocks = 0; if(currentBlock >= endBlock) { amountBlocks = endBlock.sub(st.calcBlock); } else { amountBlocks = currentBlock.sub(st.calcBlock); } uint256 fullAmount = rewardAllocation.div(totalBlocks).mul(amountBlocks); uint256 _stakeAmount = fullAmount.mul(share).div(percentage); return _stakeAmount; } /** * @dev get base staking data */ function getStakerData(address _player) public view returns(address, uint256, uint256, uint256) { uint256 staked = _calculateStaked(_player); return (_player, staked, roi, stakeholderShare(_player)); } function emergencyWithdraw() public { address user = msg.sender; uint _balance = balance[user]; balance[user] = 0; require(LPtoken.transfer(user, _balance), "LP: unable to transfer coins"); _calculateHolder(user); } }
Activating the staking with start block. Can only be called by the current owner./
function activate() public onlyOwner returns (bool){ startBlock = block.number; endBlock = startBlock.add(totalBlocks); rewardAllocation = defaultStakePerBlock.mul(totalBlocks); active = true; return true; }
11,920,580
./partial_match/42/0xc2B28F1dE060c379F5687C8f675be4883508AfEC/sources/EtherCollateralpUSD.sol
Add ETH collateral to an open loan Require loanLiquidationOpen to be false or we are in liquidation phase Get the loan from storage Check loan exists and is open Tell the Dapps collateral was added to loan
function depositCollateral(address account, uint256 loanID) external payable notPaused { require(msg.value > 0, "Deposit amount must be greater than 0"); systemStatus().requireIssuanceActive(); require(loanLiquidationOpen == false, "Loans are now being liquidated"); PynthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID); _checkLoanIsOpen(synthLoan); uint256 totalCollateral = synthLoan.collateralAmount.add(msg.value); _updateLoanCollateral(synthLoan, totalCollateral); emit CollateralDeposited(account, loanID, msg.value, totalCollateral); }
3,482,074
// File @openzeppelin/contracts/utils/Context.sol@v4.2.0 // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts-upgradeable/interfaces/draft-IERC1822Upgradeable.sol@v4.5.2 // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // File @openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // File @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // File @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol@v4.5.2 // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol@v4.5.2 // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File contracts/core/IKODAV3Minter.sol pragma solidity 0.8.4; interface IKODAV3Minter { function mintBatchEdition(uint16 _editionSize, address _to, string calldata _uri) external returns (uint256 _editionId); function mintBatchEditionAndComposeERC20s(uint16 _editionSize, address _to, string calldata _uri, address[] calldata _erc20s, uint256[] calldata _amounts) external returns (uint256 _editionId); function mintConsecutiveBatchEdition(uint16 _editionSize, address _to, string calldata _uri) external returns (uint256 _editionId); } // File contracts/marketplace/IKODAV3Marketplace.sol pragma solidity 0.8.4; interface IBuyNowMarketplace { event ListedForBuyNow(uint256 indexed _id, uint256 _price, address _currentOwner, uint256 _startDate); event BuyNowPriceChanged(uint256 indexed _id, uint256 _price); event BuyNowDeListed(uint256 indexed _id); event BuyNowPurchased(uint256 indexed _tokenId, address _buyer, address _currentOwner, uint256 _price); function listForBuyNow(address _creator, uint256 _id, uint128 _listingPrice, uint128 _startDate) external; function buyEditionToken(uint256 _id) external payable; function buyEditionTokenFor(uint256 _id, address _recipient) external payable; function setBuyNowPriceListing(uint256 _editionId, uint128 _listingPrice) external; } interface IEditionOffersMarketplace { event EditionAcceptingOffer(uint256 indexed _editionId, uint128 _startDate); event EditionBidPlaced(uint256 indexed _editionId, address _bidder, uint256 _amount); event EditionBidWithdrawn(uint256 indexed _editionId, address _bidder); event EditionBidAccepted(uint256 indexed _editionId, uint256 indexed _tokenId, address _bidder, uint256 _amount); event EditionBidRejected(uint256 indexed _editionId, address _bidder, uint256 _amount); event EditionConvertedFromOffersToBuyItNow(uint256 _editionId, uint128 _price, uint128 _startDate); function enableEditionOffers(uint256 _editionId, uint128 _startDate) external; function placeEditionBid(uint256 _editionId) external payable; function placeEditionBidFor(uint256 _editionId, address _bidder) external payable; function withdrawEditionBid(uint256 _editionId) external; function rejectEditionBid(uint256 _editionId) external; function acceptEditionBid(uint256 _editionId, uint256 _offerPrice) external; function convertOffersToBuyItNow(uint256 _editionId, uint128 _listingPrice, uint128 _startDate) external; } interface IEditionSteppedMarketplace { event EditionSteppedSaleListed(uint256 indexed _editionId, uint128 _basePrice, uint128 _stepPrice, uint128 _startDate); event EditionSteppedSaleBuy(uint256 indexed _editionId, uint256 indexed _tokenId, address _buyer, uint256 _price, uint16 _currentStep); event EditionSteppedAuctionUpdated(uint256 indexed _editionId, uint128 _basePrice, uint128 _stepPrice); function listSteppedEditionAuction(address _creator, uint256 _editionId, uint128 _basePrice, uint128 _stepPrice, uint128 _startDate) external; function buyNextStep(uint256 _editionId) external payable; function buyNextStepFor(uint256 _editionId, address _buyer) external payable; function convertSteppedAuctionToListing(uint256 _editionId, uint128 _listingPrice, uint128 _startDate) external; function convertSteppedAuctionToOffers(uint256 _editionId, uint128 _startDate) external; function updateSteppedAuction(uint256 _editionId, uint128 _basePrice, uint128 _stepPrice) external; } interface IReserveAuctionMarketplace { event ListedForReserveAuction(uint256 indexed _id, uint256 _reservePrice, uint128 _startDate); event BidPlacedOnReserveAuction(uint256 indexed _id, address _currentOwner, address _bidder, uint256 _amount, uint256 _originalBiddingEnd, uint256 _currentBiddingEnd); event ReserveAuctionResulted(uint256 indexed _id, uint256 _finalPrice, address _currentOwner, address _winner, address _resulter); event BidWithdrawnFromReserveAuction(uint256 _id, address _bidder, uint128 _bid); event ReservePriceUpdated(uint256 indexed _id, uint256 _reservePrice); event ReserveAuctionConvertedToBuyItNow(uint256 indexed _id, uint128 _listingPrice, uint128 _startDate); event EmergencyBidWithdrawFromReserveAuction(uint256 indexed _id, address _bidder, uint128 _bid); function placeBidOnReserveAuction(uint256 _id) external payable; function placeBidOnReserveAuctionFor(uint256 _id, address _bidder) external payable; function listForReserveAuction(address _creator, uint256 _id, uint128 _reservePrice, uint128 _startDate) external; function resultReserveAuction(uint256 _id) external; function withdrawBidFromReserveAuction(uint256 _id) external; function updateReservePriceForReserveAuction(uint256 _id, uint128 _reservePrice) external; function emergencyExitBidFromReserveAuction(uint256 _id) external; } interface IKODAV3PrimarySaleMarketplace is IEditionSteppedMarketplace, IEditionOffersMarketplace, IBuyNowMarketplace, IReserveAuctionMarketplace { function convertReserveAuctionToBuyItNow(uint256 _editionId, uint128 _listingPrice, uint128 _startDate) external; function convertReserveAuctionToOffers(uint256 _editionId, uint128 _startDate) external; } interface ITokenBuyNowMarketplace { event TokenDeListed(uint256 indexed _tokenId); function delistToken(uint256 _tokenId) external; } interface ITokenOffersMarketplace { event TokenBidPlaced(uint256 indexed _tokenId, address _currentOwner, address _bidder, uint256 _amount); event TokenBidAccepted(uint256 indexed _tokenId, address _currentOwner, address _bidder, uint256 _amount); event TokenBidRejected(uint256 indexed _tokenId, address _currentOwner, address _bidder, uint256 _amount); event TokenBidWithdrawn(uint256 indexed _tokenId, address _bidder); function acceptTokenBid(uint256 _tokenId, uint256 _offerPrice) external; function rejectTokenBid(uint256 _tokenId) external; function withdrawTokenBid(uint256 _tokenId) external; function placeTokenBid(uint256 _tokenId) external payable; function placeTokenBidFor(uint256 _tokenId, address _bidder) external payable; } interface IBuyNowSecondaryMarketplace { function listTokenForBuyNow(uint256 _tokenId, uint128 _listingPrice, uint128 _startDate) external; } interface IEditionOffersSecondaryMarketplace { event EditionBidPlaced(uint256 indexed _editionId, address indexed _bidder, uint256 _bid); event EditionBidWithdrawn(uint256 indexed _editionId, address _bidder); event EditionBidAccepted(uint256 indexed _tokenId, address _currentOwner, address _bidder, uint256 _amount); function placeEditionBid(uint256 _editionId) external payable; function placeEditionBidFor(uint256 _editionId, address _bidder) external payable; function withdrawEditionBid(uint256 _editionId) external; function acceptEditionBid(uint256 _tokenId, uint256 _offerPrice) external; } interface IKODAV3SecondarySaleMarketplace is ITokenBuyNowMarketplace, ITokenOffersMarketplace, IEditionOffersSecondaryMarketplace, IBuyNowSecondaryMarketplace { function convertReserveAuctionToBuyItNow(uint256 _tokenId, uint128 _listingPrice, uint128 _startDate) external; function convertReserveAuctionToOffers(uint256 _tokenId) external; } interface IKODAV3GatedMarketplace { function createSale(uint256 _editionId) external; function createPhase( uint256 _editionId, uint128 _startTime, uint128 _endTime, uint128 _priceInWei, uint16 _mintCap, uint16 _walletMintLimit, bytes32 _merkleRoot, string calldata _merkleIPFSHash ) external; function createSaleWithPhases( uint256 _editionId, uint128[] memory _startTimes, uint128[] memory _endTimes, uint128[] memory _pricesInWei, uint16[] memory _mintCaps, uint16[] memory _walletMintLimits, bytes32[] memory _merkleRoots, string[] memory _merkleIPFSHashes ) external; function createPhases( uint256 _editionId, uint128[] memory _startTimes, uint128[] memory _endTimes, uint128[] memory _pricesInWei, uint16[] memory _mintCaps, uint16[] memory _walletMintLimits, bytes32[] memory _merkleRoots, string[] memory _merkleIPFSHashes ) external; function removePhase(uint256 _editionId, uint256 _phaseId) external; } // File contracts/collab/ICollabRoyaltiesRegistry.sol pragma solidity 0.8.4; /// @notice Common interface to the edition royalties registry interface ICollabRoyaltiesRegistry { /// @notice Creates & deploys a new royalties recipient, cloning _handle and setting it up with the provided _recipients and _splits function createRoyaltiesRecipient( address _handler, address[] calldata _recipients, uint256[] calldata _splits ) external returns (address deployedHandler); /// @notice Sets up the provided edition to use the provided _recipient function useRoyaltiesRecipient(uint256 _editionId, address _deployedHandler) external; /// @notice Setup a royalties handler but does not deploy it, uses predicable clone and sets this against the edition function usePredeterminedRoyaltiesRecipient( uint256 _editionId, address _handler, address[] calldata _recipients, uint256[] calldata _splits ) external; /// @notice Deploy and setup a royalties recipient for the given edition function createAndUseRoyaltiesRecipient( uint256 _editionId, address _handler, address[] calldata _recipients, uint256[] calldata _splits ) external returns (address deployedHandler); /// @notice Predict the deployed clone address with the given parameters function predictedRoyaltiesHandler( address _handler, address[] calldata _recipients, uint256[] calldata _splits ) external view returns (address predictedHandler); } // File contracts/access/IKOAccessControlsLookup.sol pragma solidity 0.8.4; interface IKOAccessControlsLookup { function hasAdminRole(address _address) external view returns (bool); function isVerifiedArtist(uint256 _index, address _account, bytes32[] calldata _merkleProof) external view returns (bool); function isVerifiedArtistProxy(address _artist, address _proxy) external view returns (bool); function hasLegacyMinterRole(address _address) external view returns (bool); function hasContractRole(address _address) external view returns (bool); function hasContractOrAdminRole(address _address) external view returns (bool); } // File contracts/minter/MintingFactoryV2.sol pragma solidity 0.8.4; contract MintingFactoryV2 is Context, UUPSUpgradeable { event EditionMinted(uint256 indexed _editionId); event EditionMintedAndListed(uint256 indexed _editionId, SaleType _saleType); event MintingFactoryCreated(); event AdminMintingPeriodChanged(uint256 _mintingPeriod); event AdminMaxMintsInPeriodChanged(uint256 _maxMintsInPeriod); event AdminFrequencyOverrideChanged(address _account, bool _override); event AdminRoyaltiesRegistryChanged(address _royaltiesRegistry); modifier onlyAdmin() { require(accessControls.hasAdminRole(_msgSender()), "Caller must have admin role"); _; } modifier canMintAgain(address _sender) { require(_canCreateNewEdition(_sender), "Caller unable to create yet"); _; } struct MintingPeriod { uint128 mints; uint128 firstMintInPeriod; } enum SaleType { BUY_NOW, OFFERS, STEPPED, RESERVE } // Minting allowance period uint256 public mintingPeriod; // Limit of mints with in the period uint256 public maxMintsInPeriod; // Frequency override list for users - you can temporarily add in address which disables the freeze time check mapping(address => bool) public frequencyOverride; // How many mints within the current minting period mapping(address => MintingPeriod) mintingPeriodConfig; IKOAccessControlsLookup public accessControls; IKODAV3Minter public koda; IKODAV3PrimarySaleMarketplace public marketplace; IKODAV3GatedMarketplace public gatedMarketplace; ICollabRoyaltiesRegistry public royaltiesRegistry; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize( IKOAccessControlsLookup _accessControls, IKODAV3Minter _koda, IKODAV3PrimarySaleMarketplace _marketplace, IKODAV3GatedMarketplace _gatedMarketplace, ICollabRoyaltiesRegistry _royaltiesRegistry ) public initializer { accessControls = _accessControls; koda = _koda; marketplace = _marketplace; gatedMarketplace = _gatedMarketplace; royaltiesRegistry = _royaltiesRegistry; mintingPeriod = 30 days; maxMintsInPeriod = 15; emit MintingFactoryCreated(); } function _authorizeUpgrade(address newImplementation) internal view override { require(accessControls.hasAdminRole(msg.sender), "Only admin can upgrade"); } ////////////////////////////////////////// /// Mint & setup on primary marketplace // ////////////////////////////////////////// function mintBatchEdition( SaleType _saleType, uint16 _editionSize, uint128 _startDate, uint128 _basePrice, uint128 _stepPrice, string calldata _uri, uint256 _merkleIndex, bytes32[] calldata _merkleProof, address _deployedRoyaltiesHandler ) canMintAgain(_msgSender()) external { require(accessControls.isVerifiedArtist(_merkleIndex, _msgSender(), _merkleProof), "Caller must have minter role"); // Make tokens & edition uint256 editionId = koda.mintBatchEdition(_editionSize, _msgSender(), _uri); _setupSalesMechanic(editionId, _saleType, _startDate, _basePrice, _stepPrice); _recordSuccessfulMint(_msgSender()); _setupRoyalties(editionId, _deployedRoyaltiesHandler); } function mintBatchEditionAsProxy( address _creator, SaleType _saleType, uint16 _editionSize, uint128 _startDate, uint128 _basePrice, uint128 _stepPrice, string calldata _uri, address _deployedRoyaltiesHandler ) canMintAgain(_creator) external { require(accessControls.isVerifiedArtistProxy(_creator, _msgSender()), "Caller is not artist proxy"); // Make tokens & edition uint256 editionId = koda.mintBatchEdition(_editionSize, _creator, _uri); _setupSalesMechanic(editionId, _saleType, _startDate, _basePrice, _stepPrice); _recordSuccessfulMint(_creator); _setupRoyalties(editionId, _deployedRoyaltiesHandler); } ////////////////////////////////////// /// Mint & setup on gated only drop // ////////////////////////////////////// function mintBatchEditionGatedOnly( uint16 _editionSize, uint256 _merkleIndex, bytes32[] calldata _merkleProof, address _deployedRoyaltiesHandler, string calldata _uri ) canMintAgain(_msgSender()) external { require(accessControls.isVerifiedArtist(_merkleIndex, _msgSender(), _merkleProof), "Caller must have minter role"); // Make tokens & edition uint256 editionId = koda.mintBatchEdition(_editionSize, _msgSender(), _uri); // Created gated sale gatedMarketplace.createSale(editionId); _recordSuccessfulMint(_msgSender()); _setupRoyalties(editionId, _deployedRoyaltiesHandler); } function mintBatchEditionGatedOnlyAsProxy( address _creator, uint16 _editionSize, address _deployedRoyaltiesHandler, string calldata _uri ) canMintAgain(_creator) external { require(accessControls.isVerifiedArtistProxy(_creator, _msgSender()), "Caller is not artist proxy"); // Make tokens & edition uint256 editionId = koda.mintBatchEdition(_editionSize, _creator, _uri); // Created gated sale gatedMarketplace.createSale(editionId); _recordSuccessfulMint(_creator); _setupRoyalties(editionId, _deployedRoyaltiesHandler); } ////////////////////////////////////////// /// Mint & setup on gated & public drop // ////////////////////////////////////////// function mintBatchEditionGatedAndPublic( uint16 _editionSize, uint128 _publicStartDate, uint128 _publicBuyNowPrice, uint256 _merkleIndex, bytes32[] calldata _merkleProof, address _deployedRoyaltiesHandler, string calldata _uri ) canMintAgain(_msgSender()) external { require(accessControls.isVerifiedArtist(_merkleIndex, _msgSender(), _merkleProof), "Caller must have minter role"); // Make tokens & edition uint256 editionId = koda.mintBatchEdition(_editionSize, _msgSender(), _uri); // Setup public sale _setupSalesMechanic(editionId, SaleType.BUY_NOW, _publicStartDate, _publicBuyNowPrice, 0); // Created gated sale gatedMarketplace.createSale(editionId); _recordSuccessfulMint(_msgSender()); _setupRoyalties(editionId, _deployedRoyaltiesHandler); } function mintBatchEditionGatedAndPublicAsProxy( address _creator, uint16 _editionSize, uint128 _publicStartDate, uint128 _publicBuyNowPrice, address _deployedRoyaltiesHandler, string calldata _uri ) canMintAgain(_creator) external { require(accessControls.isVerifiedArtistProxy(_creator, _msgSender()), "Caller is not artist proxy"); // Make tokens & edition uint256 editionId = koda.mintBatchEdition(_editionSize, _creator, _uri); // Setup public sale _setupSalesMechanic(editionId, SaleType.BUY_NOW, _publicStartDate, _publicBuyNowPrice, 0); // Created gated sale gatedMarketplace.createSale(editionId); _recordSuccessfulMint(_creator); _setupRoyalties(editionId, _deployedRoyaltiesHandler); } //////////////// /// Mint only // //////////////// function mintBatchEditionOnly( uint16 _editionSize, uint256 _merkleIndex, bytes32[] calldata _merkleProof, address _deployedRoyaltiesHandler, string calldata _uri ) canMintAgain(_msgSender()) external { require(accessControls.isVerifiedArtist(_merkleIndex, _msgSender(), _merkleProof), "Caller must have minter role"); // Make tokens & edition uint256 editionId = koda.mintBatchEdition(_editionSize, _msgSender(), _uri); _recordSuccessfulMint(_msgSender()); _setupRoyalties(editionId, _deployedRoyaltiesHandler); emit EditionMinted(editionId); } function mintBatchEditionOnlyAsProxy( address _creator, uint16 _editionSize, address _deployedRoyaltiesHandler, string calldata _uri ) canMintAgain(_creator) external { require(accessControls.isVerifiedArtistProxy(_creator, _msgSender()), "Caller is not artist proxy"); // Make tokens & edition uint256 editionId = koda.mintBatchEdition(_editionSize, _creator, _uri); _recordSuccessfulMint(_creator); _setupRoyalties(editionId, _deployedRoyaltiesHandler); emit EditionMinted(editionId); } /////////////////////// /// Internal helpers // /////////////////////// function _setupSalesMechanic(uint256 _editionId, SaleType _saleType, uint128 _startDate, uint128 _basePrice, uint128 _stepPrice) internal { if (SaleType.BUY_NOW == _saleType) { marketplace.listForBuyNow(_msgSender(), _editionId, _basePrice, _startDate); } else if (SaleType.STEPPED == _saleType) { marketplace.listSteppedEditionAuction(_msgSender(), _editionId, _basePrice, _stepPrice, _startDate); } else if (SaleType.OFFERS == _saleType) { marketplace.enableEditionOffers(_editionId, _startDate); } else if (SaleType.RESERVE == _saleType) { // use base price for reserve price marketplace.listForReserveAuction(_msgSender(), _editionId, _basePrice, _startDate); } emit EditionMintedAndListed(_editionId, _saleType); } function _setupRoyalties(uint256 _editionId, address _deployedHandler) internal { if (_deployedHandler != address(0) && address(royaltiesRegistry) != address(0)) { royaltiesRegistry.useRoyaltiesRecipient(_editionId, _deployedHandler); } } function _canCreateNewEdition(address _account) internal view returns (bool) { // if frequency is overridden then assume they can mint if (frequencyOverride[_account]) { return true; } // if within the period range, check remaining allowance if (_getNow() <= mintingPeriodConfig[_account].firstMintInPeriod + mintingPeriod) { return mintingPeriodConfig[_account].mints < maxMintsInPeriod; } // if period expired - can mint another one return true; } function _recordSuccessfulMint(address _account) internal { MintingPeriod storage period = mintingPeriodConfig[_account]; uint256 endOfCurrentMintingPeriodLimit = period.firstMintInPeriod + mintingPeriod; // if first time use, set the first timestamp to be now abd start counting if (period.firstMintInPeriod == 0) { period.firstMintInPeriod = _getNow(); period.mints = period.mints + 1; } // if still within the minting period, record the new mint else if (_getNow() <= endOfCurrentMintingPeriodLimit) { period.mints = period.mints + 1; } // if we are outside of the window reset the limit and record a new single mint else if (endOfCurrentMintingPeriodLimit < _getNow()) { period.mints = 1; period.firstMintInPeriod = _getNow(); } } function _getNow() internal virtual view returns (uint128) { return uint128(block.timestamp); } /// Public helpers function canCreateNewEdition(address _account) public view returns (bool) { return _canCreateNewEdition(_account); } function currentMintConfig(address _account) public view returns (uint128 mints, uint128 firstMintInPeriod) { MintingPeriod memory config = mintingPeriodConfig[_account]; return ( config.mints, config.firstMintInPeriod ); } function setFrequencyOverride(address _account, bool _override) onlyAdmin public { frequencyOverride[_account] = _override; emit AdminFrequencyOverrideChanged(_account, _override); } function setMintingPeriod(uint256 _mintingPeriod) onlyAdmin public { mintingPeriod = _mintingPeriod; emit AdminMintingPeriodChanged(_mintingPeriod); } function setRoyaltiesRegistry(ICollabRoyaltiesRegistry _royaltiesRegistry) onlyAdmin public { royaltiesRegistry = _royaltiesRegistry; emit AdminRoyaltiesRegistryChanged(address(_royaltiesRegistry)); } function setMaxMintsInPeriod(uint256 _maxMintsInPeriod) onlyAdmin public { maxMintsInPeriod = _maxMintsInPeriod; emit AdminMaxMintsInPeriodChanged(_maxMintsInPeriod); } }
Make tokens & edition
function mintBatchEdition( SaleType _saleType, uint16 _editionSize, uint128 _startDate, uint128 _basePrice, uint128 _stepPrice, string calldata _uri, uint256 _merkleIndex, bytes32[] calldata _merkleProof, address _deployedRoyaltiesHandler ) canMintAgain(_msgSender()) external { require(accessControls.isVerifiedArtist(_merkleIndex, _msgSender(), _merkleProof), "Caller must have minter role"); uint256 editionId = koda.mintBatchEdition(_editionSize, _msgSender(), _uri); _setupSalesMechanic(editionId, _saleType, _startDate, _basePrice, _stepPrice); _recordSuccessfulMint(_msgSender()); _setupRoyalties(editionId, _deployedRoyaltiesHandler); }
5,998,718
// SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/INodes.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IDelegationController.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IValidatorService.sol"; import "@skalenetwork/skale-manager-interfaces/IBountyV2.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./utils/Random.sol"; import "./utils/SegmentTree.sol"; import "./NodeRotation.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions, INodes { using Random for IRandom.RandomGenerator; using SafeCastUpgradeable for uint; using SegmentTree for SegmentTree.Tree; bytes32 constant public COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE"); bytes32 public constant NODE_MANAGER_ROLE = keccak256("NODE_MANAGER_ROLE"); // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public override numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; mapping (uint => string) public domainNames; mapping (uint => bool) private _invisible; SegmentTree.Tree private _nodesAmountBySpace; mapping (uint => bool) public override incompliant; modifier checkNodeExists(uint nodeIndex) { _checkNodeIndex(nodeIndex); _; } modifier onlyNodeOrNodeManager(uint nodeIndex) { _checkNodeOrNodeManager(nodeIndex, msg.sender); _; } modifier onlyCompliance() { require(hasRole(COMPLIANCE_ROLE, msg.sender), "COMPLIANCE_ROLE is required"); _; } modifier nonZeroIP(bytes4 ip) { require(ip != 0x0 && !nodesIPCheck[ip], "IP address is zero or is not available"); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external override checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, (uint(spaceOfNodes[nodeIndex].freeSpace) - space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external override checkNodeExists(nodeIndex) allow("SchainsInternal") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, (uint(spaceOfNodes[nodeIndex].freeSpace) + space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external override checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external override checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external override allow("SkaleManager") nonZeroIP(params.ip) { // checks that Node has correct data require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = IValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); nodes.push(Node({ name: params.name, ip: params.ip, publicIP: params.publicIp, port: params.port, publicKey: params.publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); uint nodeIndex = nodes.length - 1; validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(params.name)); nodesIPCheck[params.ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; domainNames[nodeIndex] = params.domainName; spaceOfNodes.push(SpaceManaging({ freeSpace: totalSpace, indexInSpaceMap: spaceToNodes[totalSpace].length })); _setNodeActive(nodeIndex); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName); } /** * @dev Allows NODE_MANAGER_ROLE to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external override checkNodeExists(nodeIndex) { require(hasRole(NODE_MANAGER_ROLE, msg.sender), "NODE_MANAGER_ROLE is required"); require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); NodeRotation(contractManager.getContract("NodeRotation")).freezeSchains(nodeIndex); emit ExitInitialized(nodeIndex, block.timestamp); } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external override checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); emit ExitCompleted(nodeIndex); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external override checkNodeExists(nodeIndex) allow("SkaleManager") { IValidatorService validatorService = IValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length - 1]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external override allow("SkaleManager") { IValidatorService validatorService = IValidatorService(contractManager.getValidatorService()); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); require( _checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length), "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external override checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { IValidatorService validatorService = IValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); return _checkValidatorPositionToMaintainNode(validatorId, position); } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external override onlyNodeOrNodeManager(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); emit MaintenanceNode(nodeIndex, true); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external override onlyNodeOrNodeManager(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); emit MaintenanceNode(nodeIndex, false); } /** * @dev Marks the node as incompliant * */ function setNodeIncompliant(uint nodeIndex) external override onlyCompliance checkNodeExists(nodeIndex) { if (!incompliant[nodeIndex]) { incompliant[nodeIndex] = true; _makeNodeInvisible(nodeIndex); emit IncompliantNode(nodeIndex, true); } } /** * @dev Marks the node as compliant * */ function setNodeCompliant(uint nodeIndex) external override onlyCompliance checkNodeExists(nodeIndex) { if (incompliant[nodeIndex]) { incompliant[nodeIndex] = false; _tryToMakeNodeVisible(nodeIndex); emit IncompliantNode(nodeIndex, false); } } function setDomainName(uint nodeIndex, string memory domainName) external override onlyNodeOrNodeManager(nodeIndex) { domainNames[nodeIndex] = domainName; } function makeNodeVisible(uint nodeIndex) external override allow("SchainsInternal") { _tryToMakeNodeVisible(nodeIndex); } function makeNodeInvisible(uint nodeIndex) external override allow("SchainsInternal") { _makeNodeInvisible(nodeIndex); } function changeIP( uint nodeIndex, bytes4 newIP, bytes4 newPublicIP ) external override onlyAdmin checkNodeExists(nodeIndex) nonZeroIP(newIP) { if (newPublicIP != 0x0) { require(newIP == newPublicIP, "IP address is not the same"); nodes[nodeIndex].publicIP = newPublicIP; } nodesIPCheck[nodes[nodeIndex].ip] = false; nodesIPCheck[newIP] = true; emit IPChanged(nodeIndex, nodes[nodeIndex].ip, newIP); nodes[nodeIndex].ip = newIP; } function getRandomNodeWithFreeSpace( uint8 freeSpace, IRandom.RandomGenerator memory randomGenerator ) external view override returns (uint) { uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast( freeSpace == 0 ? 1 : freeSpace, randomGenerator ).toUint8(); require(place > 0, "Node not found"); return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)]; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (bool) { return IBountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= block.timestamp; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (string memory) { return domainNames[nodeIndex]; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (uint) { return IBountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view override returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view override returns (uint) { return numberOfActiveNodes + numberOfLeavingNodes ; } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view override returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view override checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view override returns (uint[] memory) { IValidatorService validatorService = IValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) external view override returns (uint count) { if (freeSpace == 0) { return _nodesAmountBySpace.sumFromPlaceToLast(1); } return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace); } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; _nodesAmountBySpace.create(128); } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view override checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view override checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view override checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view override checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal { uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; uint len = spaceToNodes[space].length - 1; if (indexInArray < len) { uint shiftedIndex = spaceToNodes[space][len]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; } spaceToNodes[space].pop(); delete spaceOfNodes[nodeIndex].indexInSpaceMap; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromTree(space); _addNodeToTree(newSpace); _removeNodeFromSpaceToNodes(nodeIndex, space); _addNodeToSpaceToNodes(nodeIndex, newSpace); } spaceOfNodes[nodeIndex].freeSpace = newSpace; } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes + 1; if (_invisible[nodeIndex]) { _tryToMakeNodeVisible(nodeIndex); } else { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); } } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes - 1; _makeNodeInvisible(nodeIndex); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; delete spaceOfNodes[nodeIndex].freeSpace; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; _makeNodeInvisible(nodeIndex); } function _makeNodeInvisible(uint nodeIndex) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); _removeNodeFromTree(space); _invisible[nodeIndex] = true; } } function _tryToMakeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex] && _canBeVisible(nodeIndex)) { _makeNodeVisible(nodeIndex); } } function _makeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); delete _invisible[nodeIndex]; } } function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private { spaceToNodes[space].push(nodeIndex); spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length - 1; } function _addNodeToTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.addToPlace(space, 1); } } function _removeNodeFromTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.removeFromPlace(space, 1); } } function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) { IDelegationController delegationController = IDelegationController( contractManager.getContract("DelegationController") ); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = IConstantsHolder(contractManager.getConstantsHolder()).msr(); return (position + 1) * msr <= delegationsTotal; } function _checkNodeIndex(uint nodeIndex) private view { require(nodeIndex < nodes.length, "Node with such index does not exist"); } function _checkNodeOrNodeManager(uint nodeIndex, address sender) private view { IValidatorService validatorService = IValidatorService(contractManager.getValidatorService()); require( isNodeExist(sender, nodeIndex) || hasRole(NODE_MANAGER_ROLE, msg.sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(sender), "Sender is not permitted to call this function" ); } function _canBeVisible(uint nodeIndex) private view returns (bool) { return !incompliant[nodeIndex] && nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCastUpgradeable { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only /* INodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "./utils/IRandom.sol"; interface INodes { // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod ); /** * @dev Emitted when a node set to in compliant or compliant. */ event IncompliantNode( uint indexed nodeIndex, bool status ); /** * @dev Emitted when a node set to in maintenance or from in maintenance. */ event MaintenanceNode( uint indexed nodeIndex, bool status ); /** * @dev Emitted when a node status changed. */ event IPChanged( uint indexed nodeIndex, bytes4 previousIP, bytes4 newIP ); function removeSpaceFromNode(uint nodeIndex, uint8 space) external returns (bool); function addSpaceToNode(uint nodeIndex, uint8 space) external; function changeNodeLastRewardDate(uint nodeIndex) external; function changeNodeFinishTime(uint nodeIndex, uint time) external; function createNode(address from, NodeCreationParams calldata params) external; function initExit(uint nodeIndex) external; function completeExit(uint nodeIndex) external returns (bool); function deleteNodeForValidator(uint validatorId, uint nodeIndex) external; function checkPossibilityCreatingNode(address nodeAddress) external; function checkPossibilityToMaintainNode(uint validatorId, uint nodeIndex) external returns (bool); function setNodeInMaintenance(uint nodeIndex) external; function removeNodeFromInMaintenance(uint nodeIndex) external; function setNodeIncompliant(uint nodeIndex) external; function setNodeCompliant(uint nodeIndex) external; function setDomainName(uint nodeIndex, string memory domainName) external; function makeNodeVisible(uint nodeIndex) external; function makeNodeInvisible(uint nodeIndex) external; function changeIP(uint nodeIndex, bytes4 newIP, bytes4 newPublicIP) external; function numberOfActiveNodes() external view returns (uint); function incompliant(uint nodeIndex) external view returns (bool); function getRandomNodeWithFreeSpace( uint8 freeSpace, IRandom.RandomGenerator memory randomGenerator ) external view returns (uint); function isTimeForReward(uint nodeIndex) external view returns (bool); function getNodeIP(uint nodeIndex) external view returns (bytes4); function getNodeDomainName(uint nodeIndex) external view returns (string memory); function getNodePort(uint nodeIndex) external view returns (uint16); function getNodePublicKey(uint nodeIndex) external view returns (bytes32[2] memory); function getNodeAddress(uint nodeIndex) external view returns (address); function getNodeFinishTime(uint nodeIndex) external view returns (uint); function isNodeLeft(uint nodeIndex) external view returns (bool); function isNodeInMaintenance(uint nodeIndex) external view returns (bool); function getNodeLastRewardDate(uint nodeIndex) external view returns (uint); function getNodeNextRewardDate(uint nodeIndex) external view returns (uint); function getNumberOfNodes() external view returns (uint); function getNumberOnlineNodes() external view returns (uint); function getActiveNodeIds() external view returns (uint[] memory activeNodeIds); function getNodeStatus(uint nodeIndex) external view returns (NodeStatus); function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory); function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count); function getValidatorId(uint nodeIndex) external view returns (uint); function isNodeExist(address from, uint nodeIndex) external view returns (bool); function isNodeActive(uint nodeIndex) external view returns (bool); function isNodeLeaving(uint nodeIndex) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* IDelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IDelegationController { enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } /** * @dev Emitted when validator was confiscated. */ event Confiscated( uint indexed validatorId, uint amount ); /** * @dev Emitted when validator was confiscated. */ event SlashesProcessed( address indexed holder, uint limit ); /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint); function getAndUpdateDelegatedAmount(address holder) external returns (uint); function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external returns (uint effectiveDelegated); function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external; function cancelPendingDelegation(uint delegationId) external; function acceptPendingDelegation(uint delegationId) external; function requestUndelegation(uint delegationId) external; function confiscate(uint validatorId, uint amount) external; function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external returns (uint); function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint); function processSlashes(address holder, uint limit) external; function processAllSlashes(address holder) external; function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory); function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint); function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint); function getDelegation(uint delegationId) external view returns (Delegation memory); function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint); function getDelegationsByValidatorLength(uint validatorId) external view returns (uint); function getDelegationsByHolderLength(address holder) external view returns (uint); function getState(uint delegationId) external view returns (State state); function getLockedInPendingDelegations(address holder) external view returns (uint); function hasUnprocessedSlashes(address holder) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* IValidatorService.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IValidatorService { struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); /** * @dev Emitted when whitelist disabled. */ event WhitelistDisabled(bool status); /** * @dev Emitted when validator requested new address. */ event RequestNewAddress(uint indexed validatorId, address previousAddress, address newAddress); /** * @dev Emitted when validator set new minimum delegation amount. */ event SetMinimumDelegationAmount(uint indexed validatorId, uint previousMDA, uint newMDA); /** * @dev Emitted when validator set new name. */ event SetValidatorName(uint indexed validatorId, string previousName, string newName); /** * @dev Emitted when validator set new description. */ event SetValidatorDescription(uint indexed validatorId, string previousDescription, string newDescription); /** * @dev Emitted when validator start or stop accepting new delegation requests. */ event AcceptingNewRequests(uint indexed validatorId, bool status); function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId); function enableValidator(uint validatorId) external; function disableValidator(uint validatorId) external; function disableWhitelist() external; function requestForNewAddress(address newValidatorAddress) external; function confirmNewAddress(uint validatorId) external; function linkNodeAddress(address nodeAddress, bytes calldata sig) external; function unlinkNodeAddress(address nodeAddress) external; function setValidatorMDA(uint minimumDelegationAmount) external; function setValidatorName(string calldata newName) external; function setValidatorDescription(string calldata newDescription) external; function startAcceptingNewRequests() external; function stopAcceptingNewRequests() external; function removeNodeAddress(uint validatorId, address nodeAddress) external; function getAndUpdateBondAmount(uint validatorId) external returns (uint); function getMyNodesAddresses() external view returns (address[] memory); function getTrustedValidators() external view returns (uint[] memory); function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool); function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId); function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view; function getNodeAddresses(uint validatorId) external view returns (address[] memory); function validatorExists(uint validatorId) external view returns (bool); function validatorAddressExists(address validatorAddress) external view returns (bool); function checkIfValidatorAddressExists(address validatorAddress) external view; function getValidator(uint validatorId) external view returns (Validator memory); function getValidatorId(address validatorAddress) external view returns (uint); function isAcceptingNewRequests(uint validatorId) external view returns (bool); function isAuthorizedValidator(uint validatorId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* IBountyV2.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Artem Payvin SKALE Manager Interfaces 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. SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IBountyV2 { /** * @dev Emitted when bounty reduction is turned on or turned off. */ event BountyReduction(bool status); /** * @dev Emitted when a node creation window was changed. */ event NodeCreationWindowWasChanged( uint oldValue, uint newValue ); function calculateBounty(uint nodeIndex) external returns (uint); function enableBountyReduction() external; function disableBountyReduction() external; function setNodeCreationWindowSeconds(uint window) external; function handleDelegationAdd(uint amount, uint month) external; function handleDelegationRemoving(uint amount, uint month) external; function estimateBounty(uint nodeIndex) external view returns (uint); function getNextRewardTimestamp(uint nodeIndex) external view returns (uint); function getEffectiveDelegatedSum() external view returns (uint[] memory); } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "@skalenetwork/skale-manager-interfaces/IPermissions.sol"; import "./thirdparty/openzeppelin/AccessControlUpgradeableLegacy.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeableLegacy, IPermissions { using AddressUpgradeable for address; IContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual override initializer { AccessControlUpgradeableLegacy.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeableLegacy skaleManager = AccessControlUpgradeableLegacy(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = IContractManager(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IConstantsHolder.sol"; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions, IConstantsHolder { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; uint public constant ALRIGHT_DELTA = 134161; uint public constant BROADCAST_DELTA = 177490; uint public constant COMPLAINT_BAD_DATA_DELTA = 80995; uint public constant PRE_RESPONSE_DELTA = 100061; uint public constant COMPLAINT_DELTA = 104611; uint public constant RESPONSE_DELTA = 49132; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimeLimit; bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE"); modifier onlyConstantsHolderManager() { require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required"); _; } /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external override onlyConstantsHolderManager { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); emit ConstantUpdated( keccak256(abi.encodePacked("RewardPeriod")), uint(rewardPeriod), uint(newRewardPeriod) ); rewardPeriod = newRewardPeriod; emit ConstantUpdated( keccak256(abi.encodePacked("DeltaPeriod")), uint(deltaPeriod), uint(newDeltaPeriod) ); deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external override onlyConstantsHolderManager { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); emit ConstantUpdated( keccak256(abi.encodePacked("CheckTime")), uint(checkTime), uint(newCheckTime) ); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("AllowableLatency")), uint(allowableLatency), uint(newAllowableLatency) ); allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("MSR")), uint(msr), uint(newMSR) ); msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external override onlyConstantsHolderManager { require( block.timestamp < launchTimestamp, "Cannot set network launch timestamp because network is already launched" ); emit ConstantUpdated( keccak256(abi.encodePacked("LaunchTimestamp")), uint(launchTimestamp), uint(timestamp) ); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("RotationDelay")), uint(rotationDelay), uint(newDelay) ); rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("ProofOfUseLockUpPeriodDays")), uint(proofOfUseLockUpPeriodDays), uint(periodDays) ); proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external override onlyConstantsHolderManager { require(percentage <= 100, "Percentage value is incorrect"); emit ConstantUpdated( keccak256(abi.encodePacked("ProofOfUseDelegationPercentage")), uint(proofOfUseDelegationPercentage), uint(percentage) ); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("LimitValidatorsPerDelegator")), uint(limitValidatorsPerDelegator), uint(newLimit) ); limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("SchainCreationTimeStamp")), uint(schainCreationTimeStamp), uint(timestamp) ); schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("MinimalSchainLifetime")), uint(minimalSchainLifetime), uint(lifetime) ); minimalSchainLifetime = lifetime; } function setComplaintTimeLimit(uint timeLimit) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("ComplaintTimeLimit")), uint(complaintTimeLimit), uint(timeLimit) ); complaintTimeLimit = timeLimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = type(uint).max; rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimeLimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/utils/IRandom.sol"; /** * @title Random * @dev The library for generating of pseudo random numbers */ library Random { /** * @dev Create an instance of RandomGenerator */ function create(uint seed) internal pure returns (IRandom.RandomGenerator memory) { return IRandom.RandomGenerator({seed: seed}); } function createFromEntropy(bytes memory entropy) internal pure returns (IRandom.RandomGenerator memory) { return create(uint(keccak256(entropy))); } /** * @dev Generates random value */ function random(IRandom.RandomGenerator memory self) internal pure returns (uint) { self.seed = uint(sha256(abi.encodePacked(self.seed))); return self.seed; } /** * @dev Generates random value in range [0, max) */ function random(IRandom.RandomGenerator memory self, uint max) internal pure returns (uint) { assert(max > 0); uint maxRand = type(uint).max - type(uint).max % max; if (type(uint).max - maxRand == max - 1) { return random(self) % max; } else { uint rand = random(self); while (rand >= maxRand) { rand = random(self); } return rand % max; } } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "./Random.sol"; /** * @title SegmentTree * @dev This library implements segment tree data structure * * Segment tree allows effectively calculate sum of elements in sub arrays * by storing some amount of additional data. * * IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n. * Size of initial array always must be power of 2 * * Example: * * Array: * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * Segment tree structure: * +-------------------------------+ * | 36 | * +---------------+---------------+ * | 10 | 26 | * +-------+-------+-------+-------+ * | 3 | 7 | 11 | 15 | * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * How the segment tree is stored in an array: * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ * | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ */ library SegmentTree { using Random for IRandom.RandomGenerator; struct Tree { uint[] tree; } /** * @dev Allocates storage for segment tree of `size` elements * * Requirements: * * - `size` must be greater than 0 * - `size` must be power of 2 */ function create(Tree storage segmentTree, uint size) external { require(size > 0, "Size can't be 0"); require(size & size - 1 == 0, "Size is not power of 2"); segmentTree.tree = new uint[](size * 2 - 1); } /** * @dev Adds `delta` to element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] */ function addToPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0] + delta; while(leftBound < rightBound) { uint middle = (leftBound + rightBound) / 2; if (place > middle) { leftBound = middle + 1; step = step + step + 1; } else { rightBound = middle; step = step + step; } self.tree[step - 1] = self.tree[step - 1] + delta; } } /** * @dev Subtracts `delta` from element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] * - initial value of target element must be not less than `delta` */ function removeFromPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0] - delta; while(leftBound < rightBound) { uint middle = (leftBound + rightBound) / 2; if (place > middle) { leftBound = middle + 1; step = step + step + 1; } else { rightBound = middle; step = step + step; } self.tree[step - 1] = self.tree[step - 1] - delta; } } /** * @dev Adds `delta` to element of segment tree at `toPlace` * and subtracts `delta` from element at `fromPlace` * * Requirements: * * - `fromPlace` must be in range [1, size] * - `toPlace` must be in range [1, size] * - initial value of element at `fromPlace` must be not less than `delta` */ function moveFromPlaceToPlace( Tree storage self, uint fromPlace, uint toPlace, uint delta ) external { require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; uint middle = (leftBound + rightBound) / 2; uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace; uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace; while (toPlaceMove <= middle || middle < fromPlaceMove) { if (middle < fromPlaceMove) { leftBound = middle + 1; step = step + step + 1; } else { rightBound = middle; step = step + step; } middle = (leftBound + rightBound) / 2; } uint leftBoundMove = leftBound; uint rightBoundMove = rightBound; uint stepMove = step; while(leftBoundMove < rightBoundMove && leftBound < rightBound) { uint middleMove = (leftBoundMove + rightBoundMove) / 2; if (fromPlace > middleMove) { leftBoundMove = middleMove + 1; stepMove = stepMove + stepMove + 1; } else { rightBoundMove = middleMove; stepMove = stepMove + stepMove; } self.tree[stepMove - 1] = self.tree[stepMove - 1] - delta; middle = (leftBound + rightBound) / 2; if (toPlace > middle) { leftBound = middle + 1; step = step + step + 1; } else { rightBound = middle; step = step + step; } self.tree[step - 1] = self.tree[step - 1] + delta; } } /** * @dev Returns random position in range [`place`, size] * with probability proportional to value stored at this position. * If all element in range are 0 returns 0 * * Requirements: * * - `place` must be in range [1, size] */ function getRandomNonZeroElementFromPlaceToLast( Tree storage self, uint place, IRandom.RandomGenerator memory randomGenerator ) external view returns (uint) { require(_correctPlace(self, place), "Incorrect place"); uint vertex = 1; uint leftBound = 0; uint rightBound = getSize(self); uint currentFrom = place - 1; uint currentSum = sumFromPlaceToLast(self, place); if (currentSum == 0) { return 0; } while(leftBound + 1 < rightBound) { if (_middle(leftBound, rightBound) <= currentFrom) { vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); } else { uint rightSum = self.tree[_right(vertex) - 1]; uint leftSum = currentSum - rightSum; if (Random.random(randomGenerator, currentSum) < leftSum) { // go left vertex = _left(vertex); rightBound = _middle(leftBound, rightBound); currentSum = leftSum; } else { // go right vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); currentFrom = leftBound; currentSum = rightSum; } } } return leftBound + 1; } /** * @dev Returns sum of elements in range [`place`, size] * * Requirements: * * - `place` must be in range [1, size] */ function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) { require(_correctPlace(self, place), "Incorrect place"); if (place == 1) { return self.tree[0]; } uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; while(leftBound < rightBound) { uint middle = (leftBound + rightBound) / 2; if (place > middle) { leftBound = middle + 1; step = step + step + 1; } else { rightBound = middle; step = step + step; sum = sum + self.tree[step]; } } sum = sum + self.tree[step - 1]; } /** * @dev Returns amount of elements in segment tree */ function getSize(Tree storage segmentTree) internal view returns (uint) { if (segmentTree.tree.length > 0) { return segmentTree.tree.length / 2 + 1; } else { return 0; } } /** * @dev Checks if `place` is valid position in segment tree */ function _correctPlace(Tree storage self, uint place) private view returns (bool) { return place >= 1 && place <= getSize(self); } /** * @dev Calculates index of left child of the vertex */ function _left(uint vertex) private pure returns (uint) { return vertex * 2; } /** * @dev Calculates index of right child of the vertex */ function _right(uint vertex) private pure returns (uint) { return vertex * 2 + 1; } /** * @dev Calculates arithmetical mean of 2 numbers */ function _middle(uint left, uint right) private pure returns (uint) { return (left + right) / 2; } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/ISkaleDKG.sol"; import "@skalenetwork/skale-manager-interfaces/INodeRotation.sol"; import "@skalenetwork/skale-manager-interfaces/IConstantsHolder.sol"; import "@skalenetwork/skale-manager-interfaces/INodes.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "./utils/Random.sol"; import "./Permissions.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions, INodeRotation { using Random for IRandom.RandomGenerator; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many _rotations were on this schain * previousNodes - queue of nodeIndex -> previous nodeIndexes * newNodeIndexes - set of all newNodeIndexes for this schain */ struct RotationWithPreviousNodes { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; // schainHash => nodeIndex => nodeIndex mapping (uint256 => uint256) previousNodes; EnumerableSetUpgradeable.UintSet newNodeIndexes; mapping (uint256 => uint256) indexInLeavingHistory; } mapping (bytes32 => RotationWithPreviousNodes) private _rotations; mapping (uint => INodeRotation.LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE"); /** * @dev Emitted when rotation delay skipped. */ event RotationDelaySkipped(bytes32 indexed schainHash); modifier onlyDebugger() { require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required"); _; } /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external override allow("SkaleManager") returns (bool, bool) { ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainHash = schainsInternal.getActiveSchain(nodeIndex); if (schainHash == bytes32(0)) { return (true, false); } _checkBeforeRotation(schainHash, nodeIndex); _startRotation(schainHash, nodeIndex); rotateNode(nodeIndex, schainHash, true, false); return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true); } /** * @dev Allows Nodes contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external override allow("Nodes") { bytes32[] memory schains = ISchainsInternal( contractManager.getContract("SchainsInternal") ).getSchainHashesForNode(nodeIndex); for (uint i = 0; i < schains.length; i++) { if (schains[i] != bytes32(0)) { _checkBeforeRotation(schains[i], nodeIndex); } } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainHash) external override allow("Schains") { delete _rotations[schainHash].nodeIndex; delete _rotations[schainHash].newNodeIndex; delete _rotations[schainHash].freezeUntil; delete _rotations[schainHash].rotationCounter; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainHash) external override onlyDebugger { _rotations[schainHash].freezeUntil = block.timestamp; emit RotationDelaySkipped(schainHash); } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainHash) external view override returns (INodeRotation.Rotation memory) { return Rotation({ nodeIndex: _rotations[schainHash].nodeIndex, newNodeIndex: _rotations[schainHash].newNodeIndex, freezeUntil: _rotations[schainHash].freezeUntil, rotationCounter: _rotations[schainHash].rotationCounter }); } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view override returns (INodeRotation.LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainHash) external view override returns (bool) { bool foundNewNode = isNewNodeFound(schainHash); return foundNewNode ? leavingHistory[_rotations[schainHash].nodeIndex][ _rotations[schainHash].indexInLeavingHistory[_rotations[schainHash].nodeIndex] ].finishedRotation >= block.timestamp : _rotations[schainHash].freezeUntil >= block.timestamp; } /** * @dev Returns a previous node of the node in schain. * If there is no previous node for given node would return an error: * "No previous node" */ function getPreviousNode(bytes32 schainHash, uint256 nodeIndex) external view override returns (uint256) { require(_rotations[schainHash].newNodeIndexes.contains(nodeIndex), "No previous node"); return _rotations[schainHash].previousNodes[nodeIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainHash, bool shouldDelay, bool isBadNode ) public override allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); schainsInternal.removeNodeFromSchain(nodeIndex, schainHash); if (!isBadNode) { schainsInternal.removeNodeFromExceptions(schainHash, nodeIndex); } newNode = selectNodeToGroup(schainHash); _finishRotation(schainHash, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainHash) public override allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint nodeIndex) { ISchainsInternal schainsInternal = ISchainsInternal(contractManager.getContract("SchainsInternal")); INodes nodes = INodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainHash), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainHash); schainsInternal.makeSchainNodesInvisible(schainHash); require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes available for rotation"); IRandom.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), schainHash) ); nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.makeSchainNodesVisible(schainHash); schainsInternal.addSchainForNode(nodeIndex, schainHash); schainsInternal.setException(schainHash, nodeIndex); schainsInternal.setNodeInGroup(schainHash, nodeIndex); } function isNewNodeFound(bytes32 schainHash) public view override returns (bool) { return _rotations[schainHash].newNodeIndexes.contains(_rotations[schainHash].newNodeIndex) && _rotations[schainHash].previousNodes[_rotations[schainHash].newNodeIndex] == _rotations[schainHash].nodeIndex; } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainHash, uint nodeIndex) private { _rotations[schainHash].newNodeIndex = nodeIndex; waitForNewNode[schainHash] = true; } function _startWaiting(bytes32 schainHash, uint nodeIndex) private { IConstantsHolder constants = IConstantsHolder(contractManager.getContract("ConstantsHolder")); _rotations[schainHash].nodeIndex = nodeIndex; _rotations[schainHash].freezeUntil = block.timestamp + constants.rotationDelay(); } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainHash, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { leavingHistory[nodeIndex].push( LeavingHistory( schainHash, shouldDelay ? block.timestamp + IConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() : block.timestamp ) ); require(_rotations[schainHash].newNodeIndexes.add(newNodeIndex), "New node was already added"); _rotations[schainHash].newNodeIndex = newNodeIndex; _rotations[schainHash].rotationCounter++; _rotations[schainHash].previousNodes[newNodeIndex] = nodeIndex; _rotations[schainHash].indexInLeavingHistory[nodeIndex] = leavingHistory[nodeIndex].length - 1; delete waitForNewNode[schainHash]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainHash); } function _checkBeforeRotation(bytes32 schainHash, uint nodeIndex) private { require( ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schainHash), "DKG did not finish on Schain" ); if (_rotations[schainHash].freezeUntil < block.timestamp) { _startWaiting(schainHash, nodeIndex); } else { require(_rotations[schainHash].nodeIndex == nodeIndex, "Occupied by rotation on Schain"); } } } // SPDX-License-Identifier: AGPL-3.0-only /* IRandom.sol - SKALE Manager Interfaces Copyright (C) 2022-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager Interfaces 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. SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IRandom { struct RandomGenerator { uint seed; } } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces 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. SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IContractManager { /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external; function setContractsAddress(string calldata contractsName, address newContractsAddress) external; function contracts(bytes32 nameHash) external view returns (address); function getDelegationPeriodManager() external view returns (address); function getBounty() external view returns (address); function getValidatorService() external view returns (address); function getTimeHelpers() external view returns (address); function getConstantsHolder() external view returns (address); function getSkaleToken() external view returns (address); function getTokenState() external view returns (address); function getPunisher() external view returns (address); function getContract(string calldata name) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* IPermissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IPermissions { function initialize(address contractManagerAddress) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/thirdparty/openzeppelin/IAccessControlUpgradeableLegacy.sol"; import "./InitializableWithGap.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeableLegacy is InitializableWithGap, ContextUpgradeable, IAccessControlUpgradeableLegacy { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override 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 override 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 override 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 override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override { require(hasRole(_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 override { 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 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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // 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/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: AGPL-3.0-only /* IAccessControlUpgradeableLegacy.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IAccessControlUpgradeableLegacy { /** * @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); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleAdmin(bytes32 role) external view returns (bytes32); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract InitializableWithGap is Initializable { uint256[50] 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 (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: AGPL-3.0-only /* IConstantsHolder.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Artem Payvin SKALE Manager Interfaces 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. SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IConstantsHolder { /** * @dev Emitted when constants updated. */ event ConstantUpdated( bytes32 indexed constantHash, uint previousValue, uint newValue ); function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external; function setCheckTime(uint newCheckTime) external; function setLatency(uint32 newAllowableLatency) external; function setMSR(uint newMSR) external; function setLaunchTimestamp(uint timestamp) external; function setRotationDelay(uint newDelay) external; function setProofOfUseLockUpPeriod(uint periodDays) external; function setProofOfUseDelegationPercentage(uint percentage) external; function setLimitValidatorsPerDelegator(uint newLimit) external; function setSchainCreationTimeStamp(uint timestamp) external; function setMinimalSchainLifetime(uint lifetime) external; function setComplaintTimeLimit(uint timeLimit) external; function msr() external view returns (uint); function launchTimestamp() external view returns (uint); function rotationDelay() external view returns (uint); function limitValidatorsPerDelegator() external view returns (uint); function schainCreationTimeStamp() external view returns (uint); function minimalSchainLifetime() external view returns (uint); function complaintTimeLimit() external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISkaleDKG { struct Fp2Point { uint a; uint b; } struct G2Point { Fp2Point x; Fp2Point y; } struct Channel { bool active; uint n; uint startedBlockTimestamp; uint startedBlock; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; bool isResponse; bytes32 keyShare; G2Point sumOfVerVec; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } /** * @dev Emitted when a channel is opened. */ event ChannelOpened(bytes32 schainHash); /** * @dev Emitted when a channel is closed. */ event ChannelClosed(bytes32 schainHash); /** * @dev Emitted when a node broadcasts key share. */ event BroadcastAndKeyShare( bytes32 indexed schainHash, uint indexed fromNode, G2Point[] verificationVector, KeyShare[] secretKeyContribution ); /** * @dev Emitted when all group data is received by node. */ event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex); /** * @dev Emitted when DKG is successful. */ event SuccessfulDKG(bytes32 indexed schainHash); /** * @dev Emitted when a complaint against a node is verified. */ event BadGuy(uint nodeIndex); /** * @dev Emitted when DKG failed. */ event FailedDKG(bytes32 indexed schainHash); /** * @dev Emitted when a new node is rotated in. */ event NewGuy(uint nodeIndex); /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent(bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex); function alright(bytes32 schainHash, uint fromNodeIndex) external; function broadcast( bytes32 schainHash, uint nodeIndex, G2Point[] memory verificationVector, KeyShare[] memory secretKeyContribution ) external; function complaintBadData(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external; function preResponse( bytes32 schainId, uint fromNodeIndex, G2Point[] memory verificationVector, G2Point[] memory verificationVectorMultiplication, KeyShare[] memory secretKeyContribution ) external; function complaint(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external; function response( bytes32 schainHash, uint fromNodeIndex, uint secretNumber, G2Point memory multipliedShare ) external; function openChannel(bytes32 schainHash) external; function deleteChannel(bytes32 schainHash) external; function setStartAlrightTimestamp(bytes32 schainHash) external; function setBadNode(bytes32 schainHash, uint nodeIndex) external; function finalizeSlashing(bytes32 schainHash, uint badNode) external; function getChannelStartedTime(bytes32 schainHash) external view returns (uint); function getChannelStartedBlock(bytes32 schainHash) external view returns (uint); function getNumberOfBroadcasted(bytes32 schainHash) external view returns (uint); function getNumberOfCompleted(bytes32 schainHash) external view returns (uint); function getTimeOfLastSuccessfulDKG(bytes32 schainHash) external view returns (uint); function getComplaintData(bytes32 schainHash) external view returns (uint, uint); function getComplaintStartedTime(bytes32 schainHash) external view returns (uint); function getAlrightStartedTime(bytes32 schainHash) external view returns (uint); function isChannelOpened(bytes32 schainHash) external view returns (bool); function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); function isBroadcastPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool); function isComplaintPossible( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool); function isAlrightPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool); function isPreResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool); function isResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool); function isNodeBroadcasted(bytes32 schainHash, uint nodeIndex) external view returns (bool); function isAllDataReceived(bytes32 schainHash, uint nodeIndex) external view returns (bool); function checkAndReturnIndexInGroup( bytes32 schainHash, uint nodeIndex, bool revertCheck ) external view returns (uint, bool); function isEveryoneBroadcasted(bytes32 schainHash) external view returns (bool); function hashData( KeyShare[] memory secretKeyContribution, G2Point[] memory verificationVector ) external pure returns (bytes32); } // SPDX-License-Identifier: AGPL-3.0-only /* INodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager 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. SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface INodeRotation { /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many _rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainHash; uint finishedRotation; } function exitFromSchain(uint nodeIndex) external returns (bool, bool); function freezeSchains(uint nodeIndex) external; function removeRotation(bytes32 schainHash) external; function skipRotationDelay(bytes32 schainHash) external; function rotateNode( uint nodeIndex, bytes32 schainHash, bool shouldDelay, bool isBadNode ) external returns (uint newNode); function selectNodeToGroup(bytes32 schainHash) external returns (uint nodeIndex); function getRotation(bytes32 schainHash) external view returns (Rotation memory); function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory); function isRotationInProgress(bytes32 schainHash) external view returns (bool); function isNewNodeFound(bytes32 schainHash) external view returns (bool); function getPreviousNode(bytes32 schainHash, uint256 nodeIndex) external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only /* ISchainsInternal - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces 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. SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchainsInternal { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; uint generation; address originator; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } /** * @dev Emitted when schain type added. */ event SchainTypeAdded(uint indexed schainType, uint partOfNode, uint numberOfNodes); /** * @dev Emitted when schain type removed. */ event SchainTypeRemoved(uint indexed schainType); function initializeSchain( string calldata name, address from, address originator, uint lifetime, uint deposit) external; function createGroupForSchain( bytes32 schainHash, uint numberOfNodes, uint8 partOfNode ) external returns (uint[] memory); function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external; function removeSchain(bytes32 schainHash, address from) external; function removeNodeFromSchain(uint nodeIndex, bytes32 schainHash) external; function deleteGroup(bytes32 schainHash) external; function setException(bytes32 schainHash, uint nodeIndex) external; function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external; function removeHolesForSchain(bytes32 schainHash) external; function addSchainType(uint8 partOfNode, uint numberOfNodes) external; function removeSchainType(uint typeOfSchain) external; function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external; function removeNodeFromAllExceptionSchains(uint nodeIndex) external; function removeAllNodesFromSchainExceptions(bytes32 schainHash) external; function makeSchainNodesInvisible(bytes32 schainHash) external; function makeSchainNodesVisible(bytes32 schainHash) external; function newGeneration() external; function addSchainForNode(uint nodeIndex, bytes32 schainHash) external; function removeSchainForNode(uint nodeIndex, uint schainIndex) external; function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external; function isSchainActive(bytes32 schainHash) external view returns (bool); function schainsAtSystem(uint index) external view returns (bytes32); function numberOfSchains() external view returns (uint64); function getSchains() external view returns (bytes32[] memory); function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8); function getSchainListSize(address from) external view returns (uint); function getSchainHashesByAddress(address from) external view returns (bytes32[] memory); function getSchainIdsByAddress(address from) external view returns (bytes32[] memory); function getSchainHashesForNode(uint nodeIndex) external view returns (bytes32[] memory); function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory); function getSchainOwner(bytes32 schainHash) external view returns (address); function getSchainOriginator(bytes32 schainHash) external view returns (address); function isSchainNameAvailable(string calldata name) external view returns (bool); function isTimeExpired(bytes32 schainHash) external view returns (bool); function isOwnerAddress(address from, bytes32 schainId) external view returns (bool); function getSchainName(bytes32 schainHash) external view returns (string memory); function getActiveSchain(uint nodeIndex) external view returns (bytes32); function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains); function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint); function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory); function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool); function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint); function isAnyFreeNode(bytes32 schainHash) external view returns (bool); function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool); function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool); function checkSchainOnNode(uint nodeIndex, bytes32 schainHash) external view returns (bool); function getSchainType(uint typeOfSchain) external view returns(uint8, uint); function getGeneration(bytes32 schainHash) external view returns (uint); function isSchainExist(bytes32 schainHash) external view returns (bool); }
Returns random position in range [`place`, size] with probability proportional to value stored at this position. If all element in range are 0 returns 0 Requirements: - `place` must be in range [1, size]/ go left go right
function getRandomNonZeroElementFromPlaceToLast( Tree storage self, uint place, IRandom.RandomGenerator memory randomGenerator ) external view returns (uint) { require(_correctPlace(self, place), "Incorrect place"); uint vertex = 1; uint leftBound = 0; uint rightBound = getSize(self); uint currentFrom = place - 1; uint currentSum = sumFromPlaceToLast(self, place); if (currentSum == 0) { return 0; } while(leftBound + 1 < rightBound) { if (_middle(leftBound, rightBound) <= currentFrom) { vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); uint rightSum = self.tree[_right(vertex) - 1]; uint leftSum = currentSum - rightSum; if (Random.random(randomGenerator, currentSum) < leftSum) { vertex = _left(vertex); rightBound = _middle(leftBound, rightBound); currentSum = leftSum; vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); currentFrom = leftBound; currentSum = rightSum; } } } return leftBound + 1; }
9,841,141
pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /* * @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; } } /** * @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 Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @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 that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied 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. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } interface IController { function withdraw(address, uint) external; function balanceOf(address) external view returns (uint); function farm(address, uint) external; function harvest(address) external; } interface ITokenMaster { function tokenToPid(address _poolToken) external view returns (uint); function userBalanceForPool(address _user, address _poolToken) external view returns (uint); } // Forked from the original yearn yVault (https://github.com/yearn/yearn-protocol/blob/develop/contracts/vaults/yVault.sol) with the following changes: // - Introduce reward token of which the user can claim from the underlying strategy // - Keeper fees for farm and harvest // - Overriding transfer function to avoid reward token accumulation in TokenMaster (e.g when user stake Vault token into TokenMaster) abstract contract BaseVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ IERC20 public token; IERC20 public rewardToken; uint public availableMin = 9500; uint public farmKeeperFeeMin = 0; uint public harvestKeeperFeeMin = 0; uint public constant MAX = 10000; uint public rewardsPerShareStored; mapping(address => uint256) public userRewardPerSharePaid; mapping(address => uint256) public rewards; address public governance; address public controller; address public tokenMaster; mapping(address => bool) public keepers; /* ========== CONSTRUCTOR ========== */ constructor ( address _token, address _rewardToken, address _controller, address _tokenMaster) public ERC20 ( string(abi.encodePacked("aladdin ", ERC20(_token).name())), string(abi.encodePacked("ald", ERC20(_token).symbol()) ) ) { _setupDecimals(ERC20(_token).decimals()); token = IERC20(_token); rewardToken = IERC20(_rewardToken); controller = _controller; governance = msg.sender; tokenMaster = _tokenMaster; } /* ========== VIEWS ========== */ function balance() public view returns (uint) { return token.balanceOf(address(this)) .add(IController(controller).balanceOf(address(this))); } // Custom logic in here for how much the vault allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint) { return token.balanceOf(address(this)).mul(availableMin).div(MAX); } function getPricePerFullShare() public view returns (uint) { return balance().mul(1e18).div(totalSupply()); } // amount staked in token master function stakedBalanceOf(address _user) public view returns(uint) { return ITokenMaster(tokenMaster).userBalanceForPool(_user, address(this)); } function earned(address account) public view returns (uint) { uint256 totalBalance = balanceOf(account).add(stakedBalanceOf(account)); return totalBalance.mul(rewardsPerShareStored.sub(userRewardPerSharePaid[account])).div(1e18).add(rewards[account]); } /* ========== USER MUTATIVE FUNCTIONS ========== */ function deposit(uint _amount) external nonReentrant { _updateReward(msg.sender); uint _pool = balance(); token.safeTransferFrom(msg.sender, address(this), _amount); uint shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); emit Deposit(msg.sender, _amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint _shares) public nonReentrant { _updateReward(msg.sender); uint r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint b = token.balanceOf(address(this)); if (b < r) { uint _withdraw = r.sub(b); IController(controller).withdraw(address(this), _withdraw); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); emit Withdraw(msg.sender, r); } function claim() public { _updateReward(msg.sender); uint reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); } emit Claim(msg.sender, reward); } function exit() external { withdraw(balanceOf(msg.sender)); claim(); } // Override underlying transfer function to update reward before transfer, except on staking/withdraw to token master function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { if (to != tokenMaster && from != tokenMaster) { _updateReward(from); _updateReward(to); } super._beforeTokenTransfer(from, to, amount); } /* ========== KEEPER MUTATIVE FUNCTIONS ========== */ // Keepers call farm() to send funds to strategy function farm() external onlyKeeper { uint _bal = available(); uint keeperFee = _bal.mul(farmKeeperFeeMin).div(MAX); if (keeperFee > 0) { token.safeTransfer(msg.sender, keeperFee); } uint amountLessFee = _bal.sub(keeperFee); token.safeTransfer(controller, amountLessFee); IController(controller).farm(address(this), amountLessFee); emit Farm(msg.sender, keeperFee, amountLessFee); } // Keepers call harvest() to claim rewards from strategy // harvest() is marked as onlyEOA to prevent sandwich/MEV attack to collect most rewards through a flash-deposit() follow by a claim function harvest() external onlyKeeper { uint _rewardBefore = rewardToken.balanceOf(address(this)); IController(controller).harvest(address(this)); uint _rewardAfter = rewardToken.balanceOf(address(this)); uint harvested = _rewardAfter.sub(_rewardBefore); uint keeperFee = harvested.mul(harvestKeeperFeeMin).div(MAX); if (keeperFee > 0) { rewardToken.safeTransfer(msg.sender, keeperFee); } uint newRewardAmount = harvested.sub(keeperFee); // distribute new rewards to current shares evenly rewardsPerShareStored = rewardsPerShareStored.add(newRewardAmount.mul(1e18).div(totalSupply())); emit Harvest(msg.sender, keeperFee, newRewardAmount); } /* ========== INTERNAL FUNCTIONS ========== */ function _updateReward(address account) internal { rewards[account] = earned(account); userRewardPerSharePaid[account] = rewardsPerShareStored; } /* ========== RESTRICTED FUNCTIONS ========== */ function setAvailableMin(uint _availableMin) external { require(msg.sender == governance, "!governance"); require(_availableMin < MAX, "over MAX"); availableMin = _availableMin; } function setFarmKeeperFeeMin(uint _farmKeeperFeeMin) external { require(msg.sender == governance, "!governance"); require(_farmKeeperFeeMin < MAX, "over MAX"); farmKeeperFeeMin = _farmKeeperFeeMin; } function setHarvestKeeperFeeMin(uint _harvestKeeperFeeMin) external { require(msg.sender == governance, "!governance"); require(_harvestKeeperFeeMin < MAX, "over MAX"); harvestKeeperFeeMin = _harvestKeeperFeeMin; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } function setTokenMaster(address _tokenMaster) external { require(msg.sender == governance, "!governance"); tokenMaster = _tokenMaster; } function addKeeper(address _address) external { require(msg.sender == governance, "!governance"); keepers[_address] = true; } function removeKeeper(address _address) external { require(msg.sender == governance, "!governance"); keepers[_address] = false; } /* ========== MODIFIERS ========== */ modifier onlyKeeper() { require(keepers[msg.sender] == true, "!keeper"); _; } /* ========== EVENTS ========== */ event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Claim(address indexed user, uint256 amount); event Farm(address indexed keeper, uint256 keeperFee, uint256 farmedAmount); event Harvest(address indexed keeper, uint256 keeperFee, uint256 harvestedAmount); } contract VaultCurveSETH is BaseVault { constructor ( address _controller, address _tokenMaster) public BaseVault( address(0xA3D87FffcE63B53E0d54fAa1cc983B7eB0b74A9c), // crvSETH address(0xD533a949740bb3306d119CC777fa900bA034cd52), // crv _controller, _tokenMaster ) {} }
Custom logic in here for how much the vault allows to be borrowed Sets minimum required on-hand to keep small withdrawals cheap
function available() public view returns (uint) { return token.balanceOf(address(this)).mul(availableMin).div(MAX); }
314,355
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IRarities.sol"; import "../commons//OwnableInitializable.sol"; import "../commons//NativeMetaTransaction.sol"; import "../tokens/ERC721Initializable.sol"; import "../libs/String.sol"; abstract contract ERC721BaseCollection is OwnableInitializable, ERC721Initializable, NativeMetaTransaction { using String for bytes32; using Strings for uint256; using String for address; using SafeMath for uint256; bytes32 public constant COLLECTION_HASH = keccak256("Unicial Collection"); uint8 public constant ITEM_ID_BITS = 40; uint8 public constant ISSUED_ID_BITS = 216; uint40 public constant MAX_ITEM_ID = type(uint40).max; uint216 public constant MAX_ISSUED_ID = type(uint216).max; bytes32 internal constant EMPTY_CONTENT = bytes32(0); string private __baseURI; struct ItemParam { string rarity; uint256 price; address beneficiary; string metadata; } struct Item { string rarity; uint256 maxSupply; // max supply uint256 totalSupply; // current supply uint256 price; address beneficiary; string metadata; string contentHash; // used for safe purposes } IRarities public rarities; // Roles address public creator; mapping(address => bool) public globalMinters; mapping(address => bool) public globalManagers; mapping(uint256 => mapping(address => uint256)) public itemMinters; mapping(uint256 => mapping(address => bool)) public itemManagers; Item[] public items; // Status uint256 public createdAt; bool public isInitialized; bool public isCompleted; bool public isEditable; bool public isApproved; event BaseURI(string _oldBaseURI, string _newBaseURI); event SetGlobalMinter(address indexed _minter, bool _value); event SetGlobalManager(address indexed _manager, bool _value); event SetItemMinter( uint256 indexed _itemId, address indexed _minter, uint256 _value ); event SetItemManager( uint256 indexed _itemId, address indexed _manager, bool _value ); event AddItem(uint256 indexed _itemId, Item _item); event RescueItem( uint256 indexed _itemId, string _contentHash, string _metadata ); event Issue( address indexed _beneficiary, uint256 indexed _tokenId, uint256 indexed _itemId, uint256 _issuedId, address _caller ); event UpdateItemData( uint256 indexed _itemId, uint256 _price, address _beneficiary, string _metadata ); event CreatorshipTransferred( address indexed _previousCreator, address indexed _newCreator ); event SetApproved(bool _previousValue, bool _newValue); event SetEditable(bool _previousValue, bool _newValue); event Complete(); /* * Init functions */ /** * @notice Init the contract */ function initImplementation() public { require(!isInitialized, "initialize: ALREADY_INITIALIZED"); isInitialized = true; } /** * @notice Create the contract * @param _name - name of the contract * @param _symbol - symbol of the contract * @param baseURI_ - base URI for token URIs * @param _creator - creator address * @param _shouldComplete - Whether the collection should be completed by the end of this call * @param _isApproved - Whether the collection should be approved by the end of this call * @param _rarities - rarities address * @param _items - items to be added */ function initialize( string memory _name, string memory _symbol, string memory baseURI_, address _creator, bool _shouldComplete, bool _isApproved, IRarities _rarities, ItemParam[] memory _items ) external virtual { initImplementation(); require(_creator != address(0), "initialize: INVALID_CREATOR"); require( address(_rarities) != address(0), "initialize: INVALID_RARITIES" ); // Ownable init _initOwnable(); // EIP712 init _initializeEIP712("Unicial Collection", "1"); // ERC721 init _initERC721(_name, _symbol); // Base URI init setBaseURI(baseURI_); // Creator init creator = _creator; // Rarities init rarities = _rarities; // Items init _addItems(_items); if (_shouldComplete) { _completeCollection(); } isApproved = _isApproved; isEditable = true; createdAt = block.timestamp; } /* * Roles checkers */ function _isCreator() internal view returns (bool) { return creator == _msgSender(); } function _isManager(uint256 _itemId) internal view returns (bool) { address sender = _msgSender(); return globalManagers[sender] || itemManagers[_itemId][sender]; } modifier onlyCreator() { require(_isCreator(), "onlyCreator: CALLER_IS_NOT_CREATOR"); _; } /* * Role functions */ /** * @notice Set allowed account to manage items. * @param _minters - minter addresses * @param _values - values array */ function setMinters(address[] calldata _minters, bool[] calldata _values) external onlyCreator { require( _minters.length == _values.length, "setMinters: LENGTH_MISMATCH" ); for (uint256 i = 0; i < _minters.length; i++) { address minter = _minters[i]; bool value = _values[i]; require(minter != address(0), "setMinters: INVALID_MINTER_ADDRESS"); require( globalMinters[minter] != value, "setMinters: VALUE_IS_THE_SAME" ); globalMinters[minter] = value; emit SetGlobalMinter(minter, value); } } /** * @notice Set allowed account to mint items. * @param _itemIds - item ids * @param _minters - minter addresses * @param _values - values array */ function setItemsMinters( uint256[] calldata _itemIds, address[] calldata _minters, uint256[] calldata _values ) external onlyCreator { require( _itemIds.length == _minters.length && _minters.length == _values.length, "setItemsMinters: LENGTH_MISMATCH" ); for (uint256 i = 0; i < _minters.length; i++) { address minter = _minters[i]; uint256 itemId = _itemIds[i]; uint256 value = _values[i]; require( minter != address(0), "setItemsMinters: INVALID_MINTER_ADDRESS" ); require( itemId < items.length, "setItemsMinters: ITEM_DOES_NOT_EXIST" ); require( itemMinters[itemId][minter] != value, "setItemsMinters: VALUE_IS_THE_SAME" ); itemMinters[itemId][minter] = value; emit SetItemMinter(itemId, minter, value); } } /** * @notice Set allowed account to manage items. * @param _managers - Address allowed to manage items * @param _values - Whether is allowed or not */ function setManagers(address[] calldata _managers, bool[] calldata _values) external onlyCreator { require( _managers.length == _values.length, "setManagers: LENGTH_MISMATCH" ); for (uint256 i = 0; i < _managers.length; i++) { address manager = _managers[i]; bool value = _values[i]; require( manager != address(0), "setManagers: INVALID_MANAGER_ADDRESS" ); require( globalManagers[manager] != value, "setManagers: VALUE_IS_THE_SAME" ); globalManagers[manager] = value; emit SetGlobalManager(manager, value); } } /** * @notice Set allowed account to manage items. * @param _itemIds - item ids to set managers * @param _managers - Addresses allowed to manage items * @param _values - Whether is allowed or not */ function setItemsManagers( uint256[] calldata _itemIds, address[] calldata _managers, bool[] calldata _values ) external onlyCreator { require( _itemIds.length == _managers.length && _managers.length == _values.length, "setItemsManagers: LENGTH_MISMATCH" ); for (uint256 i = 0; i < _managers.length; i++) { address manager = _managers[i]; uint256 itemId = _itemIds[i]; bool value = _values[i]; require( manager != address(0), "setItemsManagers: INVALID_MANAGER_ADDRESS" ); require( itemId < items.length, "setItemsManagers: ITEM_DOES_NOT_EXIST" ); require( itemManagers[itemId][manager] != value, "setItemsManagers: VALUE_IS_THE_SAME" ); itemManagers[itemId][manager] = value; emit SetItemManager(itemId, manager, value); } } /** * @notice Transfers ownership of the contract to a new account (`newOwner`). * @dev Forced owner to check against msg.sender always */ function transferCreatorship(address _newCreator) external virtual { address sender = _msgSender(); require( sender == owner() || sender == creator, "transferCreatorship: CALLER_IS_NOT_OWNER_OR_CREATOR" ); require( _newCreator != address(0), "transferCreatorship: INVALID_CREATOR_ADDRESS" ); emit CreatorshipTransferred(creator, _newCreator); creator = _newCreator; } /* * Items functions */ /** * @notice Add items to the collection. * @param _items - items to add */ function addItems(ItemParam[] memory _items) external virtual onlyOwner { require(!isCompleted, "_addItem: COLLECTION_COMPLETED"); _addItems(_items); } /** * @notice Edit items * @param _itemIds - items ids to edit * @param _prices - new prices * @param _beneficiaries - new beneficiaries */ function editItemsData( uint256[] calldata _itemIds, uint256[] calldata _prices, address[] calldata _beneficiaries, string[] calldata _metadatas ) external virtual { // Check lengths require( _itemIds.length == _prices.length && _prices.length == _beneficiaries.length && _beneficiaries.length == _metadatas.length, "editItemsData: LENGTH_MISMATCH" ); require(isEditable, "editItemsData: COLLECTION_NOT_EDITABLE"); // Check item id for (uint256 i = 0; i < _itemIds.length; i++) { uint256 itemId = _itemIds[i]; uint256 price = _prices[i]; address beneficiary = _beneficiaries[i]; string memory metadata = _metadatas[i]; require( _isCreator() || _isManager(itemId), "editItemsData: CALLER_IS_NOT_CREATOR_OR_MANAGER" ); require( itemId < items.length, "editItemsData: ITEM_DOES_NOT_EXIST" ); require( (price > 0 && beneficiary != address(0)) || (price == 0 && beneficiary == address(0)), "editItemsData: INVALID_PRICE_AND_BENEFICIARY" ); require( bytes(metadata).length > 0, "editItemsData: EMPTY_METADATA" ); Item storage item = items[itemId]; require( !isApproved || keccak256(abi.encode(item.metadata)) == keccak256(abi.encode(metadata)), "editItemsData: CAN_NOT_EDIT_METADATA" ); item.price = price; item.beneficiary = beneficiary; item.metadata = metadata; emit UpdateItemData(itemId, price, beneficiary, metadata); } } /** * @notice Add new items to the collection. * @dev The item should follow: * rarity: should be one of the RARITY enum * totalSupply: starts in 0 * metadata: shouldn't be empty * price & beneficiary: is the price is > 0, a beneficiary should be passed. If not, price and * beneficiary should be empty. * contentHash: starts empty * @param _items - items to add */ function _addItems(ItemParam[] memory _items) internal { require(_items.length > 0, "_addItems: EMPTY_ITEMS"); IRarities.Rarity memory rarity; bytes32 lastRarityKey; for (uint256 i = 0; i < _items.length; i++) { ItemParam memory _item = _items[i]; bytes32 rarityKey = keccak256(bytes(_item.rarity)); if (lastRarityKey != rarityKey) { rarity = rarities.getRarityByName(_item.rarity); lastRarityKey = rarityKey; require( rarity.maxSupply > 0 && rarity.maxSupply <= MAX_ISSUED_ID, "_addItem: INVALID_RARITY" ); } require( bytes(_item.metadata).length > 0, "_addItem: EMPTY_METADATA" ); require( (_item.price > 0 && _item.beneficiary != address(0)) || (_item.price == 0 && _item.beneficiary == address(0)), "_addItem: INVALID_PRICE_AND_BENEFICIARY" ); uint256 newItemId = items.length; require(newItemId < MAX_ITEM_ID, "_addItem: MAX_ITEM_ID_REACHED"); Item memory item = Item({ rarity: rarity.name, maxSupply: rarity.maxSupply, totalSupply: 0, price: _item.price, beneficiary: _item.beneficiary, metadata: _item.metadata, contentHash: "" }); items.push(item); emit AddItem(newItemId, item); } } /** * @notice Issue tokens by item ids. * @dev Will throw if the items have reached its maximum or is invalid * @param _beneficiaries - owner of the tokens * @param _itemIds - item ids */ function issueTokens( address[] calldata _beneficiaries, uint256[] calldata _itemIds ) external virtual { require(isMintingAllowed(), "issueTokens: MINT_NOT_ALLOWED"); require( _beneficiaries.length == _itemIds.length, "issueTokens: LENGTH_MISMATCH" ); address sender = _msgSender(); for (uint256 i = 0; i < _itemIds.length; i++) { _issueToken(_beneficiaries[i], _itemIds[i], sender); } } /** * @notice Issue a new token of the specified item. * @dev Will throw if the item has reached its maximum or is invalid * @param _beneficiary - owner of the token * @param _itemId - item id * @param _sender - transaction sender */ function _issueToken( address _beneficiary, uint256 _itemId, address _sender ) internal virtual { if (!(_isCreator() || globalMinters[_sender])) { uint256 allowance = itemMinters[_itemId][_sender]; require(allowance > 0, "_issueToken: CALLER_CAN_NOT_MINT"); if (allowance != type(uint256).max) { itemMinters[_itemId][_sender]--; } } // Check item id require(_itemId < items.length, "_issueToken: ITEM_DOES_NOT_EXIST"); Item storage item = items[_itemId]; uint256 currentIssuance = item.totalSupply.add(1); // Check issuance require( currentIssuance <= item.maxSupply, "_issueToken: ITEM_EXHAUSTED" ); // Encode token id uint256 tokenId = encodeTokenId(_itemId, currentIssuance); // Increase issuance item.totalSupply = currentIssuance; // Mint token to beneficiary super._mint(_beneficiary, tokenId); // Log emit Issue(_beneficiary, tokenId, _itemId, currentIssuance, _sender); } /** * @notice Rescue an item by providing new metadata and/or content hash * @dev Only the owner can rescue an item. This function should be used * to resolve a dispute or fix a broken metadata or hashContent item * @param _itemIds - Item ids to be fixed * @param _contentHashes - New items content hash * @param _metadatas - New items metadata */ function rescueItems( uint256[] calldata _itemIds, string[] calldata _contentHashes, string[] calldata _metadatas ) external onlyOwner { // Check lengths require( _itemIds.length == _contentHashes.length && _contentHashes.length == _metadatas.length, "rescueItems: LENGTH_MISMATCH" ); for (uint256 i = 0; i < _itemIds.length; i++) { uint256 itemId = _itemIds[i]; require(itemId < items.length, "rescueItems: ITEM_DOES_NOT_EXIST"); Item storage item = items[itemId]; string memory contentHash = _contentHashes[i]; string memory metadata = _metadatas[i]; item.contentHash = contentHash; if (bytes(metadata).length > 0) { item.metadata = metadata; } emit RescueItem(itemId, contentHash, item.metadata); } } /** * @notice Returns the amount of item in the collection * @return Amount of items in the collection */ function itemsCount() external view returns (uint256) { return items.length; } /* * Status functions */ /** * @notice Get whether minting is allowed * @return boolean whether minting is allowed or not */ function isMintingAllowed() public view returns (bool) { return isCompleted && isApproved; } /** * @notice Complete the collection. * @dev Disable forever the possibility of adding new items in the collection. * The issuance is still allowed. */ function completeCollection() external onlyCreator { require( !isCompleted, "completeCollection: COLLECTION_ALREADY_COMPLETED" ); _completeCollection(); } /** * @notice Complete the collection. * @dev Internal. Disable forever the possibility of adding new items in the collection. * The issuance is still allowed. */ function _completeCollection() internal { isCompleted = true; emit Complete(); } /** * @notice Approve a collection */ function setApproved(bool _value) external virtual onlyOwner { require(isApproved != _value, "setApproved: VALUE_IS_THE_SAME"); emit SetApproved(isApproved, _value); isApproved = _value; } /** * @notice Set whether the collection can be editable or not. * @dev This property is used off-chain to check whether the items of the collection * can be updated or not * @param _value - Value to set */ function setEditable(bool _value) external onlyOwner { require(isEditable != _value, "setEditable: VALUE_IS_THE_SAME"); emit SetEditable(isEditable, _value); isEditable = _value; } /* * URI functions */ /** * @notice Set Base URI * @param baseURI_ - base URI for token URIs */ function setBaseURI(string memory baseURI_) public onlyOwner { emit BaseURI(_baseURI(), baseURI_); _setBaseURI(baseURI_); } /** * @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_; } function _baseURI() internal view override returns (string memory) { return __baseURI; } function baseURI() public view returns (string memory) { return _baseURI(); } /** * @notice Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param _tokenId - uint256 ID of the token queried * @return token URI */ function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "tokenURI: INVALID_TOKEN_ID"); (uint256 itemId, uint256 issuedId) = decodeTokenId(_tokenId); uint256 id; assembly { id := chainid() } return string( abi.encodePacked( _baseURI(), Strings.toString(id), "/", "0x", address(this).addressToString(), "/", Strings.toString(itemId), "/", Strings.toString(issuedId) ) ); } /* * Batch Transfer functions */ /** * @notice Transfers the ownership of given tokens ID to another address. * Usage of this method is discouraged, use {safeBatchTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenIds uint256 ID of the token to be transferred */ function batchTransferFrom( address _from, address _to, uint256[] calldata _tokenIds ) external { for (uint256 i = 0; i < _tokenIds.length; i++) { transferFrom(_from, _to, _tokenIds[i]); } } /** * @notice Safely transfers the ownership of given token IDs to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param _from - current owner of the token * @param _to - address to receive the ownership of the given token ID * @param _tokenIds - uint256 ID of the tokens to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, bytes memory _data ) external { for (uint256 i = 0; i < _tokenIds.length; i++) { safeTransferFrom(_from, _to, _tokenIds[i], _data); } } /* * Token Utils functions */ /** * @notice Encode token id * @dev itemId (`itemIdBits` bits) + issuedId (`issuedIdBits` bits) * @param _itemId - item id * @param _issuedId - issued id * @return id uint256 of the encoded id */ function encodeTokenId(uint256 _itemId, uint256 _issuedId) public pure returns (uint256 id) { require(_itemId <= MAX_ITEM_ID, "encodeTokenId: INVALID_ITEM_ID"); require(_issuedId <= MAX_ISSUED_ID, "encodeTokenId: INVALID_ISSUED_ID"); // solium-disable-next-line security/no-inline-assembly assembly { id := or(shl(ISSUED_ID_BITS, _itemId), _issuedId) } } /** * @notice Decode token id * @dev itemId (`itemIdBits` bits) + issuedId (`issuedIdBits` bits) * @param _id - token id * @return itemId uint256 of the item id * @return issuedId uint256 of the issued id */ function decodeTokenId(uint256 _id) public pure returns (uint256 itemId, uint256 issuedId) { uint256 mask = MAX_ISSUED_ID; // solium-disable-next-line security/no-inline-assembly assembly { itemId := shr(ISSUED_ID_BITS, _id) issuedId := and(mask, _id) } } }
Set allowed account to manage items. _managers - Address allowed to manage items _values - Whether is allowed or not/
function setManagers(address[] calldata _managers, bool[] calldata _values) external onlyCreator { require( _managers.length == _values.length, "setManagers: LENGTH_MISMATCH" ); for (uint256 i = 0; i < _managers.length; i++) { address manager = _managers[i]; bool value = _values[i]; require( manager != address(0), "setManagers: INVALID_MANAGER_ADDRESS" ); require( globalManagers[manager] != value, "setManagers: VALUE_IS_THE_SAME" ); globalManagers[manager] = value; emit SetGlobalManager(manager, value); } }
12,976,034
./full_match/43113/0x3a7D90487F8E6c8631317E1B812d020CE5bB1288/sources/src/libraries/math/Encoded.sol
Internal function to decode a bytes32 sample into a bool using an offset This function can overflow encoded The encoded value offset The offset return boolean The decoded value as a bool/
function decodeBool(bytes32 encoded, uint256 offset) internal pure returns (bool boolean) { assembly { boolean := and(shr(offset, encoded), MASK_UINT1) } }
7,117,598
./full_match/1/0xb68c8ce82BADe6455d220C90428ECc7A4798a1a8/sources/contracts/ArtongNFT.sol
Override isApprovedForAll to whitelist Artong contracts to enable gas-less listings.
function isApprovedForAll(address owner, address operator) override public view returns (bool) { if (marketplace == operator) { return true; } return super.isApprovedForAll(owner, operator); }
9,618,258
pragma solidity 0.4.24; contract ExecutionTarget { uint256 public counter; function execute() public { counter += 1; emit Executed(counter); } function setCounter(uint256 x) public { counter = x; } event Executed(uint256 x); } pragma solidity 0.4.24; import "@aragon/os/contracts/acl/ACL.sol"; import "@aragon/os/contracts/kernel/Kernel.sol"; import "@aragon/os/contracts/factory/DAOFactory.sol"; import "@aragon/os/contracts/factory/APMRegistryFactory.sol"; import "@aragon/os/contracts/factory/ENSFactory.sol"; import "@aragon/os/contracts/apm/APMRegistry.sol"; import "@aragon/os/contracts/apm/Repo.sol"; import "@aragon/os/contracts/ens/ENSSubdomainRegistrar.sol"; import "@aragon/os/contracts/lib/ens/ENS.sol"; import "@aragon/os/contracts/lib/ens/AbstractENS.sol"; import "@aragon/os/contracts/lib/ens/PublicResolver.sol"; import "@aragon/test-helpers/contracts/TokenMock.sol"; contract Imports { // solium-disable-previous-line no-empty-blocks } pragma solidity 0.4.24; import "../apps/AragonApp.sol"; import "../common/ConversionHelpers.sol"; import "../common/TimeHelpers.sol"; import "./ACLSyntaxSugar.sol"; import "./IACL.sol"; import "./IACLOracle.sol"; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); bool ok; assembly { // send all available gas; if the oracle eats up all the gas, we will eventually revert // note that we are currently guaranteed to still have some gas after the call from // EIP-150's 63/64 gas forward rule ok := staticcall(gas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./AppStorage.sol"; import "../acl/ACLSyntaxSugar.sol"; import "../common/Autopetrified.sol"; import "../common/ConversionHelpers.sol"; import "../common/ReentrancyGuard.sol"; import "../common/VaultRecoverable.sol"; import "../evmscript/EVMScriptRunner.sol"; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "../common/UnstructuredStorage.sol"; import "../kernel/IKernel.sol"; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "../acl/IACL.sol"; import "../common/IVaultRecoverable.sol"; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./Petrifiable.sol"; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./Initializable.sol"; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./TimeHelpers.sol"; import "./UnstructuredStorage.sol"; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./Uint256Helpers.sol"; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "../common/UnstructuredStorage.sol"; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "../lib/token/ERC20.sol"; import "./EtherTokenConstant.sol"; import "./IsContract.sol"; import "./IVaultRecoverable.sol"; import "./SafeERC20.sol"; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; import "../lib/token/ERC20.sol"; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } /** * @dev Static call into ERC20.totalSupply(). * Reverts if the call fails for some reason (should never fail). */ function staticTotalSupply(ERC20 _token) internal view returns (uint256) { bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector); (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return totalSupply; } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./IEVMScriptExecutor.sol"; import "./IEVMScriptRegistry.sol"; import "../apps/AppStorage.sol"; import "../kernel/KernelConstants.sol"; import "../common/Initializable.sol"; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./IEVMScriptExecutor.sol"; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } pragma solidity 0.4.24; import "./IKernel.sol"; import "./KernelConstants.sol"; import "./KernelStorage.sol"; import "../acl/IACL.sol"; import "../acl/ACLSyntaxSugar.sol"; import "../common/ConversionHelpers.sol"; import "../common/IsContract.sol"; import "../common/Petrifiable.sol"; import "../common/VaultRecoverable.sol"; import "../factory/AppProxyFactory.sol"; import "../lib/misc/ERCProxy.sol"; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } pragma solidity 0.4.24; import "../apps/AppProxyUpgradeable.sol"; import "../apps/AppProxyPinned.sol"; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } pragma solidity 0.4.24; import "./AppProxyBase.sol"; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } pragma solidity 0.4.24; import "./AppStorage.sol"; import "../common/DepositableDelegateProxy.sol"; import "../kernel/KernelConstants.sol"; import "../kernel/IKernel.sol"; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } pragma solidity 0.4.24; import "./DelegateProxy.sol"; import "./DepositableStorage.sol"; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { uint256 forwardGasThreshold = FWD_GAS_LIMIT; bytes32 isDepositablePosition = DEPOSITABLE_POSITION; // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity: // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20 assembly { // Continue only if the gas left is lower than the threshold for forwarding to the implementation code, // otherwise continue outside of the assembly block. if lt(gas, forwardGasThreshold) { // Only accept the deposit and emit an event if all of the following are true: // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0 if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) { // Equivalent Solidity code for emitting the event: // emit ProxyDeposit(msg.sender, msg.value); let logData := mload(0x40) // free memory pointer mstore(logData, caller) // add 'msg.sender' to the log data (first event param) mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param) // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1 log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1) stop() // Stop. Exits execution context } // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender) revert(0, 0) } } address target = implementation(); delegatedFwd(target, msg.data); } } pragma solidity 0.4.24; import "../common/IsContract.sol"; import "../lib/misc/ERCProxy.sol"; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } pragma solidity 0.4.24; import "./UnstructuredStorage.sol"; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } pragma solidity 0.4.24; import "../common/UnstructuredStorage.sol"; import "../common/IsContract.sol"; import "./AppProxyBase.sol"; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } pragma solidity 0.4.24; import "../kernel/IKernel.sol"; import "../kernel/Kernel.sol"; import "../kernel/KernelProxy.sol"; import "../acl/IACL.sol"; import "../acl/ACL.sol"; import "./EVMScriptRegistryFactory.sol"; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } pragma solidity 0.4.24; import "./IKernel.sol"; import "./KernelConstants.sol"; import "./KernelStorage.sol"; import "../common/DepositableDelegateProxy.sol"; import "../common/IsContract.sol"; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } pragma solidity 0.4.24; import "../evmscript/IEVMScriptExecutor.sol"; import "../evmscript/EVMScriptRegistry.sol"; import "../evmscript/executors/CallsScript.sol"; import "../kernel/Kernel.sol"; import "../acl/ACL.sol"; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } pragma solidity 0.4.24; import "../apps/AragonApp.sol"; import "./ScriptHelpers.sol"; import "./IEVMScriptExecutor.sol"; import "./IEVMScriptRegistry.sol"; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager import "../ScriptHelpers.sol"; import "./BaseEVMScriptExecutor.sol"; contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "../../common/Autopetrified.sol"; import "../IEVMScriptExecutor.sol"; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } pragma solidity 0.4.24; import "../apm/APMRegistry.sol"; import "../apm/Repo.sol"; import "../ens/ENSSubdomainRegistrar.sol"; import "./DAOFactory.sol"; import "./ENSFactory.sol"; import "./AppProxyFactory.sol"; contract APMRegistryFactory is APMInternalAppNames { DAOFactory public daoFactory; APMRegistry public registryBase; Repo public repoBase; ENSSubdomainRegistrar public ensSubdomainRegistrarBase; ENS public ens; event DeployAPM(bytes32 indexed node, address apm); /** * @notice Create a new factory for deploying Aragon Package Managers (aragonPM) * @dev Requires either a given ENS registrar or ENSFactory (used for generating a new ENS in test environments). * @param _daoFactory Base factory for deploying DAOs * @param _registryBase APMRegistry base contract location * @param _repoBase Repo base contract location * @param _ensSubBase ENSSubdomainRegistrar base contract location * @param _ens ENS instance * @param _ensFactory ENSFactory (used to generated a new ENS if no ENS is given) */ constructor( DAOFactory _daoFactory, APMRegistry _registryBase, Repo _repoBase, ENSSubdomainRegistrar _ensSubBase, ENS _ens, ENSFactory _ensFactory ) public // DAO initialized without evmscript run support { daoFactory = _daoFactory; registryBase = _registryBase; repoBase = _repoBase; ensSubdomainRegistrarBase = _ensSubBase; // Either the ENS address provided is used, if any. // Or we use the ENSFactory to generate a test instance of ENS // If not the ENS address nor factory address are provided, this will revert ens = _ens != address(0) ? _ens : _ensFactory.newENS(this); } /** * @notice Create a new Aragon Package Manager (aragonPM) DAO, holding the `_label` subdomain from parent `_tld` and controlled by `_root` * @param _tld The parent node of the controlled subdomain * @param _label The subdomain label * @param _root Manager for the new aragonPM DAO * @return The new aragonPM's APMRegistry app */ function newAPM(bytes32 _tld, bytes32 _label, address _root) public returns (APMRegistry) { bytes32 node = keccak256(abi.encodePacked(_tld, _label)); // Assume it is the test ENS if (ens.owner(node) != address(this)) { // If we weren't in test ens and factory doesn't have ownership, will fail require(ens.owner(_tld) == address(this)); ens.setSubnodeOwner(_tld, _label, this); } Kernel dao = daoFactory.newDAO(this); ACL acl = ACL(dao.acl()); acl.createPermission(this, dao, dao.APP_MANAGER_ROLE(), this); // Deploy app proxies bytes memory noInit = new bytes(0); ENSSubdomainRegistrar ensSub = ENSSubdomainRegistrar( dao.newAppInstance( keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(ENS_SUB_APP_NAME)))), ensSubdomainRegistrarBase, noInit, false ) ); APMRegistry apm = APMRegistry( dao.newAppInstance( keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(APM_APP_NAME)))), registryBase, noInit, false ) ); // APMRegistry controls Repos bytes32 repoAppId = keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(REPO_APP_NAME)))); dao.setApp(dao.APP_BASES_NAMESPACE(), repoAppId, repoBase); emit DeployAPM(node, apm); // Grant permissions needed for APM on ENSSubdomainRegistrar acl.createPermission(apm, ensSub, ensSub.CREATE_NAME_ROLE(), _root); acl.createPermission(apm, ensSub, ensSub.POINT_ROOTNODE_ROLE(), _root); // allow apm to create permissions for Repos in Kernel bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); acl.grantPermission(apm, acl, permRole); // Initialize ens.setOwner(node, ensSub); ensSub.initialize(ens, node); apm.initialize(ensSub); uint16[3] memory firstVersion; firstVersion[0] = 1; acl.createPermission(this, apm, apm.CREATE_REPO_ROLE(), this); apm.newRepoWithVersion(APM_APP_NAME, _root, firstVersion, registryBase, b("ipfs:apm")); apm.newRepoWithVersion(ENS_SUB_APP_NAME, _root, firstVersion, ensSubdomainRegistrarBase, b("ipfs:enssub")); apm.newRepoWithVersion(REPO_APP_NAME, _root, firstVersion, repoBase, b("ipfs:repo")); configureAPMPermissions(acl, apm, _root); // Permission transition to _root acl.setPermissionManager(_root, dao, dao.APP_MANAGER_ROLE()); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); return apm; } function b(string memory x) internal pure returns (bytes memory y) { y = bytes(x); } // Factory can be subclassed and permissions changed function configureAPMPermissions(ACL _acl, APMRegistry _apm, address _root) internal { _acl.grantPermission(_root, _apm, _apm.CREATE_REPO_ROLE()); _acl.setPermissionManager(_root, _apm, _apm.CREATE_REPO_ROLE()); } } pragma solidity 0.4.24; import "../lib/ens/AbstractENS.sol"; import "../ens/ENSSubdomainRegistrar.sol"; import "../factory/AppProxyFactory.sol"; import "../apps/AragonApp.sol"; import "../acl/ACL.sol"; import "./Repo.sol"; contract APMInternalAppNames { string internal constant APM_APP_NAME = "apm-registry"; string internal constant REPO_APP_NAME = "apm-repo"; string internal constant ENS_SUB_APP_NAME = "apm-enssub"; } contract APMRegistry is AragonApp, AppProxyFactory, APMInternalAppNames { /* Hardcoded constants to save gas bytes32 public constant CREATE_REPO_ROLE = keccak256("CREATE_REPO_ROLE"); */ bytes32 public constant CREATE_REPO_ROLE = 0x2a9494d64846c9fdbf0158785aa330d8bc9caf45af27fa0e8898eb4d55adcea6; string private constant ERROR_INIT_PERMISSIONS = "APMREG_INIT_PERMISSIONS"; string private constant ERROR_EMPTY_NAME = "APMREG_EMPTY_NAME"; AbstractENS public ens; ENSSubdomainRegistrar public registrar; event NewRepo(bytes32 id, string name, address repo); /** * NEEDS CREATE_NAME_ROLE and POINT_ROOTNODE_ROLE permissions on registrar * @dev Initialize can only be called once. It saves the block number in which it was initialized * @notice Initialize this APMRegistry instance and set `_registrar` as the ENS subdomain registrar * @param _registrar ENSSubdomainRegistrar instance that holds registry root node ownership */ function initialize(ENSSubdomainRegistrar _registrar) public onlyInit { initialized(); registrar = _registrar; ens = registrar.ens(); registrar.pointRootNode(this); // Check APM has all permissions it needss ACL acl = ACL(kernel().acl()); require(acl.hasPermission(this, registrar, registrar.CREATE_NAME_ROLE()), ERROR_INIT_PERMISSIONS); require(acl.hasPermission(this, acl, acl.CREATE_PERMISSIONS_ROLE()), ERROR_INIT_PERMISSIONS); } /** * @notice Create new repo in registry with `_name` * @param _name Repo name, must be ununsed * @param _dev Address that will be given permission to create versions */ function newRepo(string _name, address _dev) public auth(CREATE_REPO_ROLE) returns (Repo) { return _newRepo(_name, _dev); } /** * @notice Create new repo in registry with `_name` and publish a first version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _name Repo name * @param _dev Address that will be given permission to create versions * @param _initialSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newRepoWithVersion( string _name, address _dev, uint16[3] _initialSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_REPO_ROLE) returns (Repo) { Repo repo = _newRepo(_name, this); // need to have permissions to create version repo.newVersion(_initialSemanticVersion, _contractAddress, _contentURI); // Give permissions to _dev ACL acl = ACL(kernel().acl()); acl.revokePermission(this, repo, repo.CREATE_VERSION_ROLE()); acl.grantPermission(_dev, repo, repo.CREATE_VERSION_ROLE()); acl.setPermissionManager(_dev, repo, repo.CREATE_VERSION_ROLE()); return repo; } function _newRepo(string _name, address _dev) internal returns (Repo) { require(bytes(_name).length > 0, ERROR_EMPTY_NAME); Repo repo = newClonedRepo(); ACL(kernel().acl()).createPermission(_dev, repo, repo.CREATE_VERSION_ROLE(), _dev); // Creates [name] subdomain in the rootNode and sets registry as resolver // This will fail if repo name already exists bytes32 node = registrar.createNameAndPoint(keccak256(abi.encodePacked(_name)), repo); emit NewRepo(node, _name, repo); return repo; } function newClonedRepo() internal returns (Repo repo) { repo = Repo(newAppProxy(kernel(), repoAppId())); repo.initialize(); } function repoAppId() internal view returns (bytes32) { return keccak256(abi.encodePacked(registrar.rootNode(), keccak256(abi.encodePacked(REPO_APP_NAME)))); } } // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // 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); } pragma solidity 0.4.24; import "../lib/ens/AbstractENS.sol"; import "../lib/ens/PublicResolver.sol"; import "./ENSConstants.sol"; import "../apps/AragonApp.sol"; /* solium-disable function-order */ // Allow public initialize() to be first contract ENSSubdomainRegistrar is AragonApp, ENSConstants { /* Hardcoded constants to save gas bytes32 public constant CREATE_NAME_ROLE = keccak256("CREATE_NAME_ROLE"); bytes32 public constant DELETE_NAME_ROLE = keccak256("DELETE_NAME_ROLE"); bytes32 public constant POINT_ROOTNODE_ROLE = keccak256("POINT_ROOTNODE_ROLE"); */ bytes32 public constant CREATE_NAME_ROLE = 0xf86bc2abe0919ab91ef714b2bec7c148d94f61fdb069b91a6cfe9ecdee1799ba; bytes32 public constant DELETE_NAME_ROLE = 0x03d74c8724218ad4a99859bcb2d846d39999449fd18013dd8d69096627e68622; bytes32 public constant POINT_ROOTNODE_ROLE = 0x9ecd0e7bddb2e241c41b595a436c4ea4fd33c9fa0caa8056acf084fc3aa3bfbe; string private constant ERROR_NO_NODE_OWNERSHIP = "ENSSUB_NO_NODE_OWNERSHIP"; string private constant ERROR_NAME_EXISTS = "ENSSUB_NAME_EXISTS"; string private constant ERROR_NAME_DOESNT_EXIST = "ENSSUB_DOESNT_EXIST"; AbstractENS public ens; bytes32 public rootNode; event NewName(bytes32 indexed node, bytes32 indexed label); event DeleteName(bytes32 indexed node, bytes32 indexed label); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. This contract must be the owner of the `_rootNode` node so that it can create subdomains. * @notice Initialize this ENSSubdomainRegistrar instance with `_ens` as the root ENS registry and `_rootNode` as the node to allocate subdomains under * @param _ens Address of ENS registry * @param _rootNode Node to allocate subdomains under */ function initialize(AbstractENS _ens, bytes32 _rootNode) public onlyInit { initialized(); // We need ownership to create subnodes require(_ens.owner(_rootNode) == address(this), ERROR_NO_NODE_OWNERSHIP); ens = _ens; rootNode = _rootNode; } /** * @notice Create a new ENS subdomain record for `_label` and assign ownership to `_owner` * @param _label Label of new subdomain * @param _owner Owner of new subdomain * @return node Hash of created node */ function createName(bytes32 _label, address _owner) external auth(CREATE_NAME_ROLE) returns (bytes32 node) { return _createName(_label, _owner); } /** * @notice Create a new ENS subdomain record for `_label` that resolves to `_target` and is owned by this ENSSubdomainRegistrar * @param _label Label of new subdomain * @param _target Ethereum address this new subdomain label will point to * @return node Hash of created node */ function createNameAndPoint(bytes32 _label, address _target) external auth(CREATE_NAME_ROLE) returns (bytes32 node) { node = _createName(_label, this); _pointToResolverAndResolve(node, _target); } /** * @notice Deregister ENS subdomain record for `_label` * @param _label Label of subdomain to deregister */ function deleteName(bytes32 _label) external auth(DELETE_NAME_ROLE) { bytes32 node = getNodeForLabel(_label); address currentOwner = ens.owner(node); require(currentOwner != address(0), ERROR_NAME_DOESNT_EXIST); // fail if deleting unset name if (currentOwner != address(this)) { // needs to reclaim ownership so it can set resolver ens.setSubnodeOwner(rootNode, _label, this); } ens.setResolver(node, address(0)); // remove resolver so it ends resolving ens.setOwner(node, address(0)); emit DeleteName(node, _label); } /** * @notice Resolve this ENSSubdomainRegistrar's root node to `_target` * @param _target Ethereum address root node will point to */ function pointRootNode(address _target) external auth(POINT_ROOTNODE_ROLE) { _pointToResolverAndResolve(rootNode, _target); } function _createName(bytes32 _label, address _owner) internal returns (bytes32 node) { node = getNodeForLabel(_label); require(ens.owner(node) == address(0), ERROR_NAME_EXISTS); // avoid name reset ens.setSubnodeOwner(rootNode, _label, _owner); emit NewName(node, _label); return node; } function _pointToResolverAndResolve(bytes32 _node, address _target) internal { address publicResolver = getAddr(PUBLIC_RESOLVER_NODE); ens.setResolver(_node, publicResolver); PublicResolver(publicResolver).setAddr(_node, _target); } function getAddr(bytes32 node) internal view returns (address) { address resolver = ens.resolver(node); return PublicResolver(resolver).addr(node); } function getNodeForLabel(bytes32 _label) internal view returns (bytes32) { return keccak256(abi.encodePacked(rootNode, _label)); } } // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; import "./AbstractENS.sol"; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ENSConstants { /* Hardcoded constants to save gas bytes32 internal constant ENS_ROOT = bytes32(0); bytes32 internal constant ETH_TLD_LABEL = keccak256("eth"); bytes32 internal constant ETH_TLD_NODE = keccak256(abi.encodePacked(ENS_ROOT, ETH_TLD_LABEL)); bytes32 internal constant PUBLIC_RESOLVER_LABEL = keccak256("resolver"); bytes32 internal constant PUBLIC_RESOLVER_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL)); */ bytes32 internal constant ENS_ROOT = bytes32(0); bytes32 internal constant ETH_TLD_LABEL = 0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0; bytes32 internal constant ETH_TLD_NODE = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae; bytes32 internal constant PUBLIC_RESOLVER_LABEL = 0x329539a1d23af1810c48a07fe7fc66a3b34fbc8b37e9b3cdb97bb88ceab7e4bf; bytes32 internal constant PUBLIC_RESOLVER_NODE = 0xfdd5d5de6dd63db72bbc2d487944ba13bf775b50a80805fe6fcaba9b0fba88f5; } pragma solidity 0.4.24; import "../apps/AragonApp.sol"; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } pragma solidity 0.4.24; import "../lib/ens/ENS.sol"; import "../lib/ens/PublicResolver.sol"; import "../ens/ENSConstants.sol"; // WARNING: This is an incredibly trustful ENS deployment, do NOT use in production! // This contract is NOT meant to be deployed to a live network. // Its only purpose is to easily create ENS instances for testing aragonPM. contract ENSFactory is ENSConstants { event DeployENS(address ens); /** * @notice Create a new ENS and set `_owner` as the owner of the top level domain. * @param _owner Owner of .eth * @return ENS */ function newENS(address _owner) public returns (ENS) { ENS ens = new ENS(); // Setup .eth TLD ens.setSubnodeOwner(ENS_ROOT, ETH_TLD_LABEL, this); // Setup public resolver PublicResolver resolver = new PublicResolver(ens); ens.setSubnodeOwner(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL, this); ens.setResolver(PUBLIC_RESOLVER_NODE, resolver); resolver.setAddr(PUBLIC_RESOLVER_NODE, resolver); ens.setOwner(ETH_TLD_NODE, _owner); ens.setOwner(ENS_ROOT, _owner); emit DeployENS(ens); return ens; } } // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; import "./AbstractENS.sol"; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // Modified from https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/StandardToken.sol pragma solidity 0.4.24; import "@aragon/os/contracts/lib/math/SafeMath.sol"; contract TokenMock { using SafeMath for uint256; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; uint256 private totalSupply_; bool private allowTransfer_; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); // Allow us to set the inital balance for an account on construction constructor(address initialAccount, uint256 initialBalance) public { balances[initialAccount] = initialBalance; totalSupply_ = initialBalance; allowTransfer_ = true; } function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev 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 Set whether the token is transferable or not * @param _allowTransfer Should token be transferable */ function setAllowTransfer(bool _allowTransfer) public { allowTransfer_ = _allowTransfer; } /** * @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(allowTransfer_); require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev 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) { // Assume we want to protect for the race condition require(allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _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) { require(allowTransfer_); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } } // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } pragma solidity ^0.4.24; import "@aragon/os/contracts/lib/math/SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken { using SafeMath for uint256; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal supply; string public name; string public symbol; uint8 public decimals; constructor( string _name, string _symbol, uint8 _decimals, uint256 _totalSupply ) public { supply = _totalSupply; // Update total supply name = _name; // Set the id for reference symbol = _symbol; decimals = _decimals; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); // Transfer event indicating token creation } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev 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 Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return supply; } /** * @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]; } event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity 0.4.24; import "@1hive/apps-dandelion-voting/contracts/DandelionVoting.sol"; // NOTE: used because truffle does not support function overloading contract VotingMock is DandelionVoting { function newVoteExt( bytes _executionScript, string _metadata, bool _castVote ) external returns (uint256) { return _newVote(_executionScript, _metadata, _castVote); } } /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; import "@aragon/os/contracts/apps/AragonApp.sol"; import "@aragon/os/contracts/common/IForwarder.sol"; import "@aragon/os/contracts/acl/IACLOracle.sol"; import "@aragon/os/contracts/lib/math/SafeMath.sol"; import "@aragon/os/contracts/lib/math/SafeMath64.sol"; import "@aragon/apps-shared-minime/contracts/MiniMeToken.sol"; contract DandelionVoting is IForwarder, IACLOracle, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); bytes32 public constant MODIFY_BUFFER_BLOCKS_ROLE = keccak256("MODIFY_BUFFER_BLOCKS_ROLE"); bytes32 public constant MODIFY_EXECUTION_DELAY_ROLE = keccak256("MODIFY_EXECUTION_DELAY_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint8 private constant EXECUTION_PERIOD_FALLBACK_DIVISOR = 2; string private constant ERROR_VOTE_ID_ZERO = "DANDELION_VOTING_VOTE_ID_ZERO"; string private constant ERROR_NO_VOTE = "DANDELION_VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "DANDELION_VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "DANDELION_VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "DANDELION_VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "DANDELION_VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "DANDELION_VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "DANDELION_VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "DANDELION_VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "DANDELION_VOTING_CAN_NOT_FORWARD"; string private constant ERROR_ORACLE_SENDER_MISSING = "DANDELION_VOTING_ORACLE_SENDER_MISSING"; string private constant ERROR_ORACLE_SENDER_TOO_BIG = "DANDELION_VOTING_ORACLE_SENDER_TOO_BIG"; string private constant ERROR_ORACLE_SENDER_ZERO = "DANDELION_VOTING_ORACLE_SENDER_ZERO"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startBlock; uint64 executionBlock; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public durationBlocks; uint64 public bufferBlocks; uint64 public executionDelayBlocks; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; mapping (address => uint256) public latestYeaVoteId; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); event ChangeBufferBlocks(uint64 bufferBlocks); event ChangeExecutionDelayBlocks(uint64 executionDelayBlocks); modifier voteExists(uint256 _voteId) { require(_voteId != 0, ERROR_VOTE_ID_ZERO); require(_voteId <= votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, a voting duration of `_voteDurationBlocks` blocks, and a vote buffer of `_voteBufferBlocks` blocks * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _durationBlocks Blocks that a vote will be open for token holders to vote * @param _bufferBlocks Minimum number of blocks between the start block of each vote * @param _executionDelayBlocks Minimum number of blocks between the end of a vote and when it can be executed */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _durationBlocks, uint64 _bufferBlocks, uint64 _executionDelayBlocks ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; durationBlocks = _durationBlocks; bufferBlocks = _bufferBlocks; executionDelayBlocks = _executionDelayBlocks; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Change vote buffer to `_voteBufferBlocks` blocks * @param _bufferBlocks New vote buffer defined in blocks */ function changeBufferBlocks(uint64 _bufferBlocks) external auth(MODIFY_BUFFER_BLOCKS_ROLE) { bufferBlocks = _bufferBlocks; emit ChangeBufferBlocks(_bufferBlocks); } /** * @notice Change execution delay to `_executionDelayBlocks` blocks * @param _executionDelayBlocks New vote execution delay defined in blocks */ function changeExecutionDelayBlocks(uint64 _executionDelayBlocks) external auth(MODIFY_EXECUTION_DELAY_ROLE) { executionDelayBlocks = _executionDelayBlocks; emit ChangeExecutionDelayBlocks(_executionDelayBlocks); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote */ function vote(uint256 _voteId, bool _supports) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } // Forwarding fns /** * @notice Returns whether the Voting app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true); } /** * @notice Returns whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can create votes, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // ACL Oracle fns /** * @notice Returns whether the sender has voted on the most recent open vote or closed unexecuted vote. * @dev IACLOracle interface conformance. The ACLOracle permissioned function should specify the sender * with 'authP(SOME_ACL_ROLE, arr(sender))', where sender is typically set to 'msg.sender'. * @param _how Array passed by Kernel when using 'authP()'. First item should be the address to check can perform. * return False if the sender has voted on the most recent open vote or closed unexecuted vote, true if they haven't. */ function canPerform(address, address, bytes32, uint256[] _how) external view returns (bool) { if (votesLength == 0) { return true; } require(_how.length > 0, ERROR_ORACLE_SENDER_MISSING); require(_how[0] < 2**160, ERROR_ORACLE_SENDER_TOO_BIG); require(_how[0] != 0, ERROR_ORACLE_SENDER_ZERO); address sender = address(_how[0]); uint256 senderLatestYeaVoteId = latestYeaVoteId[sender]; Vote storage senderLatestYeaVote_ = votes[senderLatestYeaVoteId]; uint64 blockNumber = getBlockNumber64(); bool senderLatestYeaVoteFailed = !_votePassed(senderLatestYeaVote_); bool senderLatestYeaVoteExecutionBlockPassed = blockNumber >= senderLatestYeaVote_.executionBlock; uint64 fallbackPeriodLength = bufferBlocks / EXECUTION_PERIOD_FALLBACK_DIVISOR; bool senderLatestYeaVoteFallbackPeriodPassed = blockNumber > senderLatestYeaVote_.executionBlock.add(fallbackPeriodLength); return senderLatestYeaVoteFailed && senderLatestYeaVoteExecutionBlockPassed || senderLatestYeaVote_.executed || senderLatestYeaVoteFallbackPeriodPassed; } // Getter fns /** * @notice Tells whether a vote #`_voteId` can be executed or not * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @return True if the given vote can be executed, false otherwise */ function canExecute(uint256 _voteId) public view returns (bool) { return _canExecute(_voteId); } /** * @notice Tells whether `_sender` can participate in the vote #`_voteId` or not * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @return True if the given voter can participate a certain vote, false otherwise */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } /** * @dev Return all information for a vote by its ID * @param _voteId Vote identifier * @return Vote open status * @return Vote executed status * @return Vote start block * @return Vote snapshot block * @return Vote support required * @return Vote minimum acceptance quorum * @return Vote yeas amount * @return Vote nays amount * @return Vote power * @return Vote script */ function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startBlock, uint64 executionBlock, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 votingPower, uint256 yea, uint256 nay, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startBlock = vote_.startBlock; executionBlock = vote_.executionBlock; snapshotBlock = vote_.snapshotBlock; votingPower = token.totalSupplyAt(vote_.snapshotBlock); supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; script = vote_.executionScript; } /** * @dev Return the state of a voter for a given vote by its ID * @param _voteId Vote identifier * @return VoterState of the requested voter for a certain vote */ function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns /** * @dev Internal function to create a new vote * @return voteId id for newly created vote */ function _newVote(bytes _executionScript, string _metadata, bool _castVote) internal returns (uint256 voteId) { voteId = ++votesLength; // Increment votesLength before assigning to votedId. The first voteId is 1. uint64 previousVoteStartBlock = votes[voteId - 1].startBlock; uint64 earliestStartBlock = previousVoteStartBlock == 0 ? 0 : previousVoteStartBlock.add(bufferBlocks); uint64 startBlock = earliestStartBlock < getBlockNumber64() ? getBlockNumber64() : earliestStartBlock; uint64 executionBlock = startBlock.add(durationBlocks).add(executionDelayBlocks); Vote storage vote_ = votes[voteId]; vote_.startBlock = startBlock; vote_.executionBlock = executionBlock; vote_.snapshotBlock = startBlock - 1; // avoid double voting in this very block vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender); } } /** * @dev Internal function to cast a vote. It assumes the queried vote exists. */ function _vote(uint256 _voteId, bool _supports, address _voter) internal { Vote storage vote_ = votes[_voteId]; uint256 voterStake = _voterStake(vote_, _voter); if (_supports) { vote_.yea = vote_.yea.add(voterStake); if (latestYeaVoteId[_voter] < _voteId) { latestYeaVoteId[_voter] = _voteId; } } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); } /** * @dev Internal function to check if a vote can be executed. It assumes the queried vote exists. * @return True if the given vote can be executed, false otherwise */ function _canExecute(uint256 _voteId) internal view voteExists(_voteId) returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // This will always be later than the end of the previous vote if (getBlockNumber64() < vote_.executionBlock) { return false; } return _votePassed(vote_); } /** * @dev Internal function to check if a vote has passed. It assumes the vote period has passed. * @return True if the given vote has passed, false otherwise. */ function _votePassed(Vote storage vote_) internal view returns (bool) { uint256 totalVotes = vote_.yea.add(vote_.nay); uint256 votingPowerAtSnapshot = token.totalSupplyAt(vote_.snapshotBlock); bool hasSupportRequired = _isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct); bool hasMinQuorum = _isValuePct(vote_.yea, votingPowerAtSnapshot, vote_.minAcceptQuorumPct); return hasSupportRequired && hasMinQuorum; } /** * @dev Internal function to check if a voter can participate on a vote. It assumes the queried vote exists. * @return True if the given voter can participate a certain vote, false otherwise */ function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; uint256 voterStake = _voterStake(vote_, _voter); bool hasNotVoted = vote_.voters[_voter] == VoterState.Absent; return _isVoteOpen(vote_) && voterStake > 0 && hasNotVoted; } /** * @dev Internal function to determine a voters stake which is the minimum of snapshot balance and current balance. * @return Voters current stake. */ function _voterStake(Vote storage vote_, address _voter) internal view returns (uint256) { uint256 balanceAtSnapshot = token.balanceOfAt(_voter, vote_.snapshotBlock); uint256 currentBalance = token.balanceOf(_voter); return balanceAtSnapshot < currentBalance ? balanceAtSnapshot : currentBalance; } /** * @dev Internal function to check if a vote is still open * @return True if the given vote is open, false otherwise */ function _isVoteOpen(Vote storage vote_) internal view returns (bool) { uint256 votingPowerAtSnapshot = token.totalSupplyAt(vote_.snapshotBlock); uint64 blockNumber = getBlockNumber64(); return votingPowerAtSnapshot > 0 && blockNumber >= vote_.startBlock && blockNumber < vote_.startBlock.add(durationBlocks); } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina 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/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. import "./ITokenController.sol"; contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "@aragon/os/contracts/apps/AragonApp.sol"; import "@aragon/os/contracts/common/SafeERC20.sol"; import "@aragon/os/contracts/lib/token/ERC20.sol"; import "@1hive/apps-dandelion-voting/contracts/DandelionVoting.sol"; import "@aragon/apps-vault/contracts/Vault.sol"; import "@aragon/os/contracts/lib/math/SafeMath.sol"; import "@aragon/os/contracts/lib/math/SafeMath64.sol"; import "@aragon/apps-shared-minime/contracts/MiniMeToken.sol"; contract VotingRewards is AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CHANGE_EPOCH_DURATION_ROLE = keccak256("CHANGE_EPOCH_DURATION_ROLE"); bytes32 public constant CHANGE_LOCK_TIME_ROLE = keccak256("CHANGE_LOCK_TIME_ROLE"); bytes32 public constant CHANGE_MISSING_VOTES_THRESHOLD_ROLE = keccak256("CHANGE_MISSING_VOTES_THRESHOLD_ROLE"); bytes32 public constant OPEN_REWARDS_DISTRIBUTION_ROLE = keccak256("OPEN_REWARDS_DISTRIBUTION_ROLE"); bytes32 public constant CLOSE_REWARDS_DISTRIBUTION_ROLE = keccak256("CLOSE_REWARDS_DISTRIBUTION_ROLE"); bytes32 public constant DISTRIBUTE_REWARDS_ROLE = keccak256("DISTRIBUTE_REWARDS_ROLE"); bytes32 public constant CHANGE_PERCENTAGE_REWARDS_ROLE = keccak256("CHANGE_PERCENTAGE_REWARDS_ROLE"); bytes32 public constant CHANGE_VAULT_ROLE = keccak256("CHANGE_VAULT_ROLE"); bytes32 public constant CHANGE_REWARDS_TOKEN_ROLE = keccak256("CHANGE_REWARDS_TOKEN_ROLE"); bytes32 public constant CHANGE_VOTING_ROLE = keccak256("CHANGE_VOTING_ROLE"); uint64 public constant PCT_BASE = 10**18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_ADDRESS_NOT_CONTRACT = "VOTING_REWARDS_ADDRESS_NOT_CONTRACT"; string private constant ERROR_EPOCH = "VOTING_REWARDS_ERROR_EPOCH"; string private constant ERROR_PERCENTAGE_REWARDS = "VOTING_REWARDS_ERROR_PERCENTAGE_REWARDS"; // prettier-ignore string private constant ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED = "VOTING_REWARDS_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED"; // prettier-ignore string private constant ERROR_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED = "VOTING_REWARDS_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED"; string private constant ERROR_NO_REWARDS = "VOTING_REWARDS_NO_REWARDS"; struct Reward { uint256 amount; uint64 lockBlock; uint64 lockTime; } Vault public baseVault; Vault public rewardsVault; DandelionVoting public dandelionVoting; address public rewardsToken; uint256 public percentageRewards; uint256 public missingVotesThreshold; uint64 public epochDuration; uint64 public currentEpoch; uint64 public startBlockNumberOfCurrentEpoch; uint64 public lockTime; uint64 public lastRewardsDistributionBlock; uint64 private deployBlock; bool public isDistributionOpen; // NOTE: previousRewardsDistributionBlockNumber kept even if not used so as not to break the proxy contract storage after an upgrade mapping(address => uint64) private previousRewardsDistributionBlockNumber; mapping(address => Reward[]) public addressUnlockedRewards; mapping(address => Reward[]) public addressWithdrawnRewards; // kept even if not used so as not to break the proxy contract storage after an upgrade event BaseVaultChanged(address baseVault); event RewardsVaultChanged(address rewardsVault); event DandelionVotingChanged(address dandelionVoting); event PercentageRewardsChanged(uint256 percentageRewards); event RewardDistributed(address indexed beneficiary, uint256 indexed amount, uint64 lockTime); event RewardCollected(address indexed beneficiary, uint256 amount, uint64 indexed lockBlock, uint64 lockTime); event EpochDurationChanged(uint64 epochDuration); event MissingVoteThresholdChanged(uint256 missingVotesThreshold); event LockTimeChanged(uint64 lockTime); event RewardsDistributionEpochOpened(uint64 startBlock, uint64 endBlock); event RewardsDistributionEpochClosed(uint64 rewardDistributionBlock); event RewardsTokenChanged(address rewardsToken); /** * @notice Initialize VotingRewards app contract * @param _baseVault Vault address from which token are taken * @param _rewardsVault Vault address to which token are put * @param _rewardsToken Accepted token address * @param _epochDuration number of blocks for which an epoch is opened * @param _percentageRewards percentage of a reward expressed as a number between 10^16 and 10^18 * @param _lockTime number of blocks for which token will be locked after colleting reward * @param _missingVotesThreshold number of missing votes allowed in an epoch */ function initialize( address _baseVault, address _rewardsVault, address _dandelionVoting, address _rewardsToken, uint64 _epochDuration, uint256 _percentageRewards, uint64 _lockTime, uint256 _missingVotesThreshold ) external onlyInit { require(isContract(_baseVault), ERROR_ADDRESS_NOT_CONTRACT); require(isContract(_rewardsVault), ERROR_ADDRESS_NOT_CONTRACT); require(isContract(_dandelionVoting), ERROR_ADDRESS_NOT_CONTRACT); require(isContract(_rewardsToken), ERROR_ADDRESS_NOT_CONTRACT); require(_percentageRewards <= PCT_BASE, ERROR_PERCENTAGE_REWARDS); baseVault = Vault(_baseVault); rewardsVault = Vault(_rewardsVault); dandelionVoting = DandelionVoting(_dandelionVoting); rewardsToken = _rewardsToken; epochDuration = _epochDuration; percentageRewards = _percentageRewards; missingVotesThreshold = _missingVotesThreshold; lockTime = _lockTime; deployBlock = getBlockNumber64(); lastRewardsDistributionBlock = getBlockNumber64(); currentEpoch = 0; initialized(); } /** * @notice Open the distribution for the current epoch from _fromBlock * @param _fromBlock block from which starting to look for rewards */ function openRewardsDistributionForEpoch(uint64 _fromBlock) external auth(OPEN_REWARDS_DISTRIBUTION_ROLE) { require(!isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED); require(_fromBlock > lastRewardsDistributionBlock, ERROR_EPOCH); require(getBlockNumber64() - lastRewardsDistributionBlock > epochDuration, ERROR_EPOCH); startBlockNumberOfCurrentEpoch = _fromBlock; isDistributionOpen = true; emit RewardsDistributionEpochOpened(_fromBlock, _fromBlock + epochDuration); } /** * @notice close distribution for thee current epoch if it's opened and starts a new one */ function closeRewardsDistributionForCurrentEpoch() external auth(CLOSE_REWARDS_DISTRIBUTION_ROLE) { require(isDistributionOpen == true, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED); isDistributionOpen = false; currentEpoch = currentEpoch.add(1); lastRewardsDistributionBlock = getBlockNumber64(); emit RewardsDistributionEpochClosed(lastRewardsDistributionBlock); } /** * @notice distribute rewards for a list of address. Tokens are locked for lockTime in rewardsVault * @param _beneficiaries address that are looking for reward * @dev this function should be called from outside each _epochDuration seconds */ function distributeRewardsToMany(address[] _beneficiaries, uint256[] _amount) external auth(DISTRIBUTE_REWARDS_ROLE) returns (bool) { require(isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED); uint256 totalRewardAmount = 0; for (uint256 i = 0; i < _beneficiaries.length; i++) { // NOTE: switching to a semi-trusted solution in order to spend less in gas // _assignUnlockedReward(_beneficiaries[i], _amount[i]); totalRewardAmount = totalRewardAmount.add(_amount[i]); emit RewardDistributed(_beneficiaries[i], _amount[i], lockTime); } baseVault.transfer(rewardsToken, rewardsVault, totalRewardAmount); return true; } /** * @notice Distribute rewards to _beneficiary * @param _beneficiary address to which the deposit will be transferred if successful * @dev baseVault should have TRANSFER_ROLE permission */ function distributeRewardsTo(address _beneficiary, uint256 _amount) external auth(DISTRIBUTE_REWARDS_ROLE) returns (bool) { require(isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED); // NOTE: switching to a semi-trusted solution in order to spend less in gas // _assignUnlockedReward(_beneficiary, _amount); baseVault.transfer(rewardsToken, rewardsVault, _amount); emit RewardDistributed(_beneficiary, _amount, lockTime); return true; } /** * @notice collect rewards for a list of address * if lockTime is passed since when tokens have been distributed * @param _beneficiaries addresses that should be fund with rewards */ function collectRewardsForMany(address[] _beneficiaries) external { for (uint256 i = 0; i < _beneficiaries.length; i++) { collectRewardsFor(_beneficiaries[i]); } } /** * @notice Change minimum number of seconds to claim dandelionVoting rewards * @param _epochDuration number of seconds minimum to claim access to dandelionVoting rewards */ function changeEpochDuration(uint64 _epochDuration) external auth(CHANGE_EPOCH_DURATION_ROLE) { require(_epochDuration > 0, ERROR_EPOCH); epochDuration = _epochDuration; emit EpochDurationChanged(_epochDuration); } /** * @notice Change minimum number of missing votes allowed * @param _missingVotesThreshold number of seconds minimum to claim access to voting rewards */ function changeMissingVotesThreshold(uint256 _missingVotesThreshold) external auth(CHANGE_MISSING_VOTES_THRESHOLD_ROLE) { missingVotesThreshold = _missingVotesThreshold; emit MissingVoteThresholdChanged(_missingVotesThreshold); } /** * @notice Change minimum number of missing votes allowed * @param _lockTime number of seconds for which tokens will be locked after distributing reward */ function changeLockTime(uint64 _lockTime) external auth(CHANGE_LOCK_TIME_ROLE) { lockTime = _lockTime; emit LockTimeChanged(_lockTime); } /** * @notice Change Base Vault * @param _baseVault new base vault address */ function changeBaseVaultContractAddress(address _baseVault) external auth(CHANGE_VAULT_ROLE) { require(isContract(_baseVault), ERROR_ADDRESS_NOT_CONTRACT); baseVault = Vault(_baseVault); emit BaseVaultChanged(_baseVault); } /** * @notice Change Reward Vault * @param _rewardsVault new reward vault address */ function changeRewardsVaultContractAddress(address _rewardsVault) external auth(CHANGE_VAULT_ROLE) { require(isContract(_rewardsVault), ERROR_ADDRESS_NOT_CONTRACT); rewardsVault = Vault(_rewardsVault); emit RewardsVaultChanged(_rewardsVault); } /** * @notice Change Dandelion Voting contract address * @param _dandelionVoting new dandelionVoting address */ function changeDandelionVotingContractAddress(address _dandelionVoting) external auth(CHANGE_VOTING_ROLE) { require(isContract(_dandelionVoting), ERROR_ADDRESS_NOT_CONTRACT); dandelionVoting = DandelionVoting(_dandelionVoting); emit DandelionVotingChanged(_dandelionVoting); } /** * @notice Change percentage rewards * @param _percentageRewards new percentage * @dev PCT_BASE is the maximun allowed percentage */ function changePercentageRewards(uint256 _percentageRewards) external auth(CHANGE_PERCENTAGE_REWARDS_ROLE) { require(_percentageRewards <= PCT_BASE, ERROR_PERCENTAGE_REWARDS); percentageRewards = _percentageRewards; emit PercentageRewardsChanged(percentageRewards); } /** * @notice Change rewards token * @param _rewardsToken new percentage */ function changeRewardsTokenContractAddress(address _rewardsToken) external auth(CHANGE_REWARDS_TOKEN_ROLE) { require(isContract(_rewardsToken), ERROR_ADDRESS_NOT_CONTRACT); rewardsToken = _rewardsToken; emit RewardsTokenChanged(rewardsToken); } /** * @notice Returns all unlocked rewards given an address * @param _beneficiary address of which we want to get all rewards */ function getUnlockedRewardsInfo(address _beneficiary) external view returns (Reward[]) { Reward[] storage rewards = addressUnlockedRewards[_beneficiary]; return rewards; } /** * @notice Returns all withdrawan rewards given an address * @param _beneficiary address of which we want to get all rewards */ function getWithdrawnRewardsInfo(address _beneficiary) external view returns (Reward[]) { Reward[] storage rewards = addressWithdrawnRewards[_beneficiary]; return rewards; } /** * @notice collect rewards for an msg.sender */ function collectRewards() external { collectRewardsFor(msg.sender); } /** * @notice collect rewards for an address if lockTime is passed since when tokens have been distributed * @param _beneficiary address that should be fund with rewards * @dev rewardsVault should have TRANSFER_ROLE permission */ function collectRewardsFor(address _beneficiary) public returns (bool) { uint64 currentBlockNumber = getBlockNumber64(); Reward[] storage rewards = addressUnlockedRewards[_beneficiary]; uint256 rewardsLength = rewards.length; require(rewardsLength > 0, ERROR_NO_REWARDS); uint256 collectedRewardsAmount = 0; for (uint256 i = 0; i < rewardsLength; i++) { Reward reward = rewards[i]; if (currentBlockNumber - reward.lockBlock > reward.lockTime && !_isRewardEmpty(reward)) { collectedRewardsAmount = collectedRewardsAmount + reward.amount; emit RewardCollected(_beneficiary, reward.amount, reward.lockBlock, reward.lockTime); delete rewards[i]; } } rewardsVault.transfer(rewardsToken, _beneficiary, collectedRewardsAmount); return true; } /** * @notice Check if msg.sender is able to be rewarded, and in positive case, * he will be funded with the corresponding earned amount of tokens * @param _beneficiary address to which the deposit will be transferred if successful */ function _assignUnlockedReward(address _beneficiary, uint256 _amount) internal returns (bool) { Reward[] storage unlockedRewards = addressUnlockedRewards[_beneficiary]; uint64 currentBlockNumber = getBlockNumber64(); // prettier-ignore uint64 lastBlockDistributedReward = unlockedRewards.length == 0 ? deployBlock : unlockedRewards[unlockedRewards.length - 1].lockBlock; // NOTE: avoid double collecting for the same epoch require(currentBlockNumber.sub(lastBlockDistributedReward) > epochDuration, ERROR_EPOCH); addressUnlockedRewards[_beneficiary].push(Reward(_amount, currentBlockNumber, lockTime)); return true; } /** * @notice Check if a Reward is empty * @param _reward reward */ function _isRewardEmpty(Reward memory _reward) internal pure returns (bool) { return _reward.amount == 0 && _reward.lockBlock == 0 && _reward.lockTime == 0; } } pragma solidity 0.4.24; import "@aragon/os/contracts/apps/AragonApp.sol"; import "@aragon/os/contracts/common/DepositableStorage.sol"; import "@aragon/os/contracts/common/EtherTokenConstant.sol"; import "@aragon/os/contracts/common/SafeERC20.sol"; import "@aragon/os/contracts/lib/token/ERC20.sol"; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } }
NOTE: this should NEVER be used for authentication 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 getRecoveryVault() public view returns (address); } pragma solidity ^0.4.24; } pragma solidity ^0.4.24; } pragma solidity ^0.4.24; function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; return size > 0; }
13,453,620
./full_match/56/0x34F33e7bBB05fb59352a5B6d3ac61DEd2274af94/sources/project_/contracts/DistributedRewardsPot/DistributedRewardsPot.sol
&& only the marketpalace admin, should authorize using marketplace contract
function withdrawUnclaimedRewards( uint256 month, address admin, TokenType tokenType ) external onlyOwner { if (_shouldUpdateCurrentMonth()) _updateCurrentMonth(); Statistics storage statistics = statisticsFor[month][tokenType]; require(_theMonthIsValid[month], 'Month is not valid'); require( currentMonth.add(_twoMonths).sub(month) > _sixMonths, 'Can only withdraw rewards older than 6 months' ); uint256 remainingRewards = statistics.collection.sub( statistics.withdrawn ); require(remainingRewards > _ZERO, _NO_REWARDS); statistics.withdrawn = statistics.collection; if (tokenType == TokenType.Native) { payable(admin).transfer(remainingRewards); _ayraToken.safeTransfer(admin, remainingRewards); _ithdToken.safeTransfer(admin, remainingRewards); } emit UnclaimedRewardsWithdrawn( month, admin, tokenType, remainingRewards ); }
3,234,617
import "DB.sol"; import "String.sol"; contract DBTest { event readResult(bytes32 name, int item_id, bytes32 item_name); event insertResult(int count); event updateResult(int count); event removeResult(int count); function create() public { DBFactory df = DBFactory(0x1001); df.createTable("t_test", "name", "item_id,item_name"); } function read(string name) public constant returns(bytes32[], int[], bytes32[]){ DBFactory df = DBFactory(0x1001); DB db = df.openDB("t_test"); Condition condition = db.newCondition(); //condition.EQ("name", name); Entries entries = db.select(name, condition); bytes32[] memory user_name_bytes_list = new bytes32[](uint256(entries.size())); int[] memory item_id_list = new int[](uint256(entries.size())); bytes32[] memory item_name_bytes_list = new bytes32[](uint256(entries.size())); for(int i=0; i<entries.size(); ++i) { Entry entry = entries.get(i); user_name_bytes_list[uint256(i)] = entry.getString("name").toBytes32(); item_id_list[uint256(i)] = entry.getInt("item_id"); item_name_bytes_list[uint256(i)] = entry.getString("item_name").toBytes32(); } return (user_name_bytes_list, item_id_list, item_name_bytes_list); } function insert(string name, int item_id, string item_name) public returns(int) { DBFactory df = DBFactory(0x1001); DB db = df.openDB("t_test"); Entry entry = db.newEntry(); entry.set("name", name); entry.set("item_id", item_id); entry.set("item_name", item_name); int count = db.insert(name, entry); insertResult(count); return count; } function update(string name, int item_id, string item_name) public returns(int) { DBFactory df = DBFactory(0x1001); DB db = df.openDB("t_test"); Entry entry = db.newEntry(); entry.set("item_name", item_name); Condition condition = db.newCondition(); condition.EQ("name", name); condition.EQ("item_id", item_id); int count = db.update(name, entry, condition); updateResult(count); return count; } function remove(string name, int item_id) public returns(int){ DBFactory df = DBFactory(0x1001); DB db = df.openDB("t_test"); Condition condition = db.newCondition(); condition.EQ("name", name); condition.EQ("item_id", item_id); int count = db.remove(name, condition); removeResult(count); return count; } }
condition.EQ("name", name);
function read(string name) public constant returns(bytes32[], int[], bytes32[]){ DBFactory df = DBFactory(0x1001); DB db = df.openDB("t_test"); Condition condition = db.newCondition(); Entries entries = db.select(name, condition); bytes32[] memory user_name_bytes_list = new bytes32[](uint256(entries.size())); int[] memory item_id_list = new int[](uint256(entries.size())); bytes32[] memory item_name_bytes_list = new bytes32[](uint256(entries.size())); for(int i=0; i<entries.size(); ++i) { Entry entry = entries.get(i); user_name_bytes_list[uint256(i)] = entry.getString("name").toBytes32(); item_id_list[uint256(i)] = entry.getInt("item_id"); item_name_bytes_list[uint256(i)] = entry.getString("item_name").toBytes32(); } return (user_name_bytes_list, item_id_list, item_name_bytes_list); }
15,864,745
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; import './Trib.sol'; import './Genesis.sol'; import './interfaces/IVault.sol'; import './utils/MathUtils.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; /// @title Contribute /// @notice A capital coordination tool. /// @author Kento Sadim contract Contribute is ReentrancyGuard { using SafeMath for uint256; using MathUtils for uint256; using SafeERC20 for IERC20; event TokensBought(address indexed from, uint256 amountInvested, uint256 tokensMinted); event TokensSold(address indexed from, uint256 tokensSold, uint256 amountReceived); event MintAndBurn(uint256 reserveAmount, uint256 tokensBurned); event InterestClaimed(address indexed from, uint256 initerestAmount); /// @notice A 10% tax is applied to every purchase or sale of tokens. uint256 public constant TAX = 10; /// @notice The slope of the bonding curve. uint256 public constant DIVIDER = 1000000; // 1 / multiplier 0.000001 (so that we don't deal with decimals) /// @notice Address in which tokens are sent to be burned. /// These tokens can't be redeemed by the reserve. address constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; /// @notice Trib token instance. Trib public token; /// @notice Genesis Mint Event contract instance. Genesis public genesis; /// @notice Token price at the Genesis Mint Event. uint256 public genesisAveragePrice; /// @notice Total funds invested in the Genesis Mint Event. uint256 public genesisReserve; /// @notice Total interests earned since the contract deployment. uint256 public totalInterestClaimed; /// @notice Total reserve value that backs all tokens in circulation. /// @dev Area below the bonding curve. uint256 public totalReserve; /// @notice mUSD reserve instance. /// ropsten - 0x4E1000616990D83e56f4b5fC6CC8602DcfD20459 /// mainnet - 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5 address public reserve; /// @notice Interface for integration with lending platform. address public vault; /// @notice Current state of the application. /// GME is either open (true) or finished (false). bool public GME = true; modifier onlyGenesis() { require(msg.sender == address(genesis), 'Genesis contract only'); _; } modifier GMEOpen() { require(GME, 'Genesis Mint Event is over'); _; } modifier GMEOver() { require(!GME, 'Genesis Mint Event is not over'); _; } constructor(address _vault, uint256 _endTime) public { vault = _vault; reserve = IVault(vault).reserve(); token = new Trib(address(this)); genesis = new Genesis(reserve, address(this), _endTime); _approveMax(reserve, vault); } /// @notice Invests funds contributed in the Genesis Mint Event. /// @dev Updates average price on each investment. /// @param contributedAmount Total value in reserve to exchange for tokens. function genesisInvest(uint256 contributedAmount) external onlyGenesis GMEOpen { genesisReserve = genesisReserve.add(contributedAmount); _invest(contributedAmount); genesisAveragePrice = genesisReserve.mul(1e18).div(genesis.totalTokenBalance()); } /// @notice Concludes the Genesis Mint Event. /// @dev Can only be called by the Genesis Contract after the GME is over. function concludeGME() external onlyGenesis GMEOpen { GME = false; } /// @notice Exchanges reserve to tokens according to the bonding curve formula. /// @dev Amount to be invested needs to be approved first. /// @param reserveAmount Value in wei that will be exchanged to tokens. function invest(uint256 reserveAmount) external GMEOver { _invest(reserveAmount); } /// @notice Exchanges token for reserve according to the bonding curve formula. /// @param tokenAmount Token value in wei that will be exchanged to reserve function sell(uint256 tokenAmount) external GMEOver { _sell(tokenAmount); } /// @notice Sells the maximum amount of tokens required to claim the most interest. function claimInterest() external GMEOver { uint256 balance = token.balanceOf(msg.sender); uint256 totalRequired = totalClaimRequired(); uint256 totalToClaim = balance < totalRequired ? balance : totalRequired; _sell(totalToClaim); } /// @notice Calculates the amount of tokens required to claim a specific interest amount. /// @param amountToClaim Interest amount to be claimed. /// @return Amount of tokens required to claim all specified interest. function claimRequired(uint256 amountToClaim) external view returns (uint256) { return _calculateClaimRequired(amountToClaim); } /// @notice Calculates the amount of tokens required to claim the outstanding interest. /// @return Amount of tokens required to claim all the outstanding interest. function totalClaimRequired() public view returns (uint256) { return _calculateClaimRequired(getInterest()); } /// @notice Total amount that has been paid in Taxes /// and is now forever locked in the protocol. function totalContributed() external view returns (uint256) { return _calculateReserveFromSupply(getBurnedTokensAmount()); } /// @notice Total outstanding interest accumulated. /// @return interest Interest in reserve accumulated in lending protocol. function getInterest() public view returns (uint256 interest) { uint256 vaultBalance = IVault(vault).getBalance(); // Sometimes mStable returns a value lower than the // deposit because their exchange rate gets updated after the deposit. if (vaultBalance > totalReserve) { interest = vaultBalance - totalReserve; } } /// @notice Total supply of tokens. This includes burned tokens. /// @return Total supply of token in wei. function getTotalSupply() public view returns (uint256) { return token.totalSupply(); } /// @notice Total tokens that have been burned. /// @dev These tokens are still in circulation therefore they /// are still considered on the bonding curve formula. /// @return Total burned token amount in wei. function getBurnedTokensAmount() public view returns (uint256) { return token.balanceOf(BURN_ADDRESS); } /// @notice Token's price in wei according to the bonding curve formula. /// @return Current token price in wei. function getCurrentTokenPrice() external view returns (uint256) { // price = supply * multiplier return getTotalSupply().roundedDiv(DIVIDER); } /// @notice Calculates the amount of tokens in exchange for reserve after applying the 10% tax. /// @param reserveAmount Reserve value in wei to use in the conversion. /// @return Token amount in wei after the 10% tax has been applied. function getReserveToTokensTaxed(uint256 reserveAmount) external view returns (uint256) { if (reserveAmount == 0) { return 0; } uint256 fee = reserveAmount.div(TAX); uint256 totalTokens = getReserveToTokens(reserveAmount); uint256 taxedTokens = getReserveToTokens(fee); return totalTokens.sub(taxedTokens); } /// @notice Calculates the amount of reserve in exchange for tokens after applying the 10% tax. /// @param tokenAmount Token value in wei to use in the conversion. /// @return Reserve amount in wei after the 10% tax has been applied. function getTokensToReserveTaxed(uint256 tokenAmount) external view returns (uint256) { if (tokenAmount == 0) { return 0; } uint256 reserveAmount = getTokensToReserve(tokenAmount); uint256 fee = reserveAmount.div(TAX); return reserveAmount.sub(fee); } /// @notice Calculates the amount of tokens in exchange for reserve. /// @param reserveAmount Reserve value in wei to use in the conversion. /// @return Token amount in wei. function getReserveToTokens(uint256 reserveAmount) public view returns (uint256) { return _calculateReserveToTokens(reserveAmount, totalReserve, getTotalSupply()); } /// @notice Calculates the amount of reserve in exchange for tokens. /// @param tokenAmount Token value in wei to use in the conversion. /// @return Reserve amount in wei. function getTokensToReserve(uint256 tokenAmount) public view returns (uint256) { return _calculateTokensToReserve(tokenAmount, getTotalSupply(), totalReserve); } /// @notice Worker function that exchanges reserve to tokens. /// Extracts 10% fee from the reserve supplied and exchanges the rest to tokens. /// Total amount is then sent to the lending protocol so it can start earning interest. /// @dev User must approve the reserve to be spent before investing. /// @param _reserveAmount Total reserve value in wei to be exchanged to tokens. function _invest(uint256 _reserveAmount) internal nonReentrant { uint256 fee = _reserveAmount.div(TAX); require(fee >= 1, 'Transaction amount not sufficient to pay fee'); uint256 totalTokens = getReserveToTokens(_reserveAmount); uint256 taxedTokens = getReserveToTokens(fee); uint256 userTokens = totalTokens.sub(taxedTokens); require(taxedTokens > 0, 'This is not enough to buy a token'); IERC20(reserve).safeTransferFrom(msg.sender, address(this), _reserveAmount); if (IERC20(reserve).allowance(address(this), vault) < _reserveAmount) { _approveMax(reserve, vault); } require(IVault(vault).deposit(_reserveAmount), 'Vault deposit failed'); totalReserve = totalReserve.add(_reserveAmount); token.mint(BURN_ADDRESS, taxedTokens); token.mint(msg.sender, userTokens); emit TokensBought(msg.sender, _reserveAmount, userTokens); emit MintAndBurn(fee, taxedTokens); } /// @notice Worker function that exchanges token for reserve. /// Tokens are decreased from the total supply according to the bonding curve formula. /// A 10% tax is applied to the reserve amount. 90% is retrieved /// from the lending protocol and sent to the user and 10% is used to mint and burn tokens. /// @param _tokenAmount Token value in wei that will be exchanged to reserve. function _sell(uint256 _tokenAmount) internal nonReentrant { require(_tokenAmount <= token.balanceOf(msg.sender), 'Insuficcient balance'); require(_tokenAmount > 0, 'Must sell something'); uint256 reserveAmount = getTokensToReserve(_tokenAmount); uint256 fee = reserveAmount.div(TAX); require(fee >= 1, 'Must pay minimum fee'); uint256 net = reserveAmount.sub(fee); uint256 taxedTokens = _calculateReserveToTokens( fee, totalReserve.sub(reserveAmount), getTotalSupply().sub(_tokenAmount) ); uint256 claimable = _calculateClaimableAmount(reserveAmount); uint256 totalClaim = net.add(claimable); totalReserve = totalReserve.sub(net); totalInterestClaimed = totalInterestClaimed.add(claimable); token.decreaseSupply(msg.sender, _tokenAmount); token.mint(BURN_ADDRESS, taxedTokens); IVault(vault).redeem(totalClaim); IERC20(reserve).safeTransfer(msg.sender, totalClaim); emit TokensSold(msg.sender, _tokenAmount, net); emit MintAndBurn(fee, taxedTokens); emit InterestClaimed(msg.sender, claimable); } function _approveMax(address tkn, address spender) internal { uint256 max = uint256(-1); IERC20(tkn).safeApprove(spender, max); } /// @notice Calculates the tokens required to claim a specific amount of interest. /// @param _amount The interest to be claimed. /// @return The amount of tokens in wei that are required to claim the interest. function _calculateClaimRequired(uint256 _amount) internal view returns (uint256) { uint256 newReserve = totalReserve.sub(_amount); uint256 newReserveSupply = _calculateReserveToTokens(newReserve, 0, 0); return getTotalSupply().sub(newReserveSupply); } /// @notice Calculates the maximum amount of interest that can be claimed /// given a certain value. /// @param _amount Value to be used in the calculation. /// @return _claimable The interest amount in wei that can be claimed for the given value. function _calculateClaimableAmount(uint256 _amount) internal view returns (uint256 _claimable) { uint256 interest = getInterest(); _claimable = _amount > interest ? interest : _amount; } /** * Supply (s), reserve (r) and token price (p) are in a relationship defined by the bonding curve: * p = m * s * The reserve equals to the area below the bonding curve * r = s^2 / 2 * The formula for the supply becomes * s = sqrt(2 * r / m) * * In solidity computations, we are using divider instead of multiplier (because its an integer). * All values are decimals with 18 decimals (represented as uints), which needs to be compensated for in * multiplications and divisions */ /// @notice Computes the increased supply given an amount of reserve. /// @param _reserveDelta The amount of reserve in wei to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @return _supplyDelta token amount in wei. function _calculateReserveToTokens( uint256 _reserveDelta, uint256 _totalReserve, uint256 _supply ) internal pure returns (uint256 _supplyDelta) { uint256 _reserve = _totalReserve; uint256 _newReserve = _reserve.add(_reserveDelta); // s = sqrt(2 * r / m) uint256 _newSupply = MathUtils.sqrt( _newReserve .mul(2) .mul(DIVIDER) // inverse the operation (Divider instead of multiplier) .mul(1e18) // compensation for the squared unit ); _supplyDelta = _newSupply.sub(_supply); } /// @notice Computes the decrease in reserve given an amount of tokens. /// @param _supplyDelta The amount of tokens in wei to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @return _reserveDelta Reserve amount in wei. function _calculateTokensToReserve( uint256 _supplyDelta, uint256 _supply, uint256 _totalReserve ) internal pure returns (uint256 _reserveDelta) { require(_supplyDelta <= _supply, 'Token amount must be less than the supply'); uint256 _newSupply = _supply.sub(_supplyDelta); uint256 _newReserve = _calculateReserveFromSupply(_newSupply); _reserveDelta = _totalReserve.sub(_newReserve); } /// @notice Calculates reserve given a specific supply. /// @param _supply The token supply in wei to be used in the calculation. /// @return _reserve Reserve amount in wei. function _calculateReserveFromSupply(uint256 _supply) internal pure returns (uint256 _reserve) { // r = s^2 * m / 2 _reserve = _supply .mul(_supply) .div(DIVIDER) // inverse the operation (Divider instead of multiplier) .div(2) .roundedDiv(1e18); // correction of the squared unit } }
Calculates the amount of tokens in exchange for reserve after applying the 10% tax. reserveAmount Reserve value in wei to use in the conversion. return Token amount in wei after the 10% tax has been applied.
function getReserveToTokensTaxed(uint256 reserveAmount) external view returns (uint256) { if (reserveAmount == 0) { return 0; } uint256 fee = reserveAmount.div(TAX); uint256 totalTokens = getReserveToTokens(reserveAmount); uint256 taxedTokens = getReserveToTokens(fee); return totalTokens.sub(taxedTokens); }
12,688,594
./full_match/43113/0xe2Cd6d9947720966298Da8537c919c000841Bd72/sources/doggesRouter.sol
given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'DoggesLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'DoggesLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; }
13,150,265
pragma solidity ^0.5.13; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/Math.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/utils/Address.sol"; import "./interfaces/IGovernance.sol"; import "./Proposals.sol"; import "../common/interfaces/IAccounts.sol"; import "../common/ExtractFunctionSignature.sol"; import "../common/Initializable.sol"; import "../common/FixidityLib.sol"; import "../common/linkedlists/IntegerSortedLinkedList.sol"; import "../common/UsingRegistry.sol"; import "../common/UsingPrecompiles.sol"; import "../common/interfaces/ICeloVersionedContract.sol"; import "../common/libraries/ReentrancyGuard.sol"; /** * @title A contract for making, passing, and executing on-chain governance proposals. */ contract Governance is IGovernance, ICeloVersionedContract, Ownable, Initializable, ReentrancyGuard, UsingRegistry, UsingPrecompiles { using Proposals for Proposals.Proposal; using FixidityLib for FixidityLib.Fraction; using SafeMath for uint256; using IntegerSortedLinkedList for SortedLinkedList.List; using BytesLib for bytes; using Address for address payable; // prettier-ignore uint256 private constant FIXED_HALF = 500000000000000000000000; enum VoteValue { None, Abstain, No, Yes } struct UpvoteRecord { uint256 proposalId; uint256 weight; } struct VoteRecord { Proposals.VoteValue value; uint256 proposalId; uint256 weight; } struct Voter { // Key of the proposal voted for in the proposal queue UpvoteRecord upvote; uint256 mostRecentReferendumProposal; // Maps a `dequeued` index to a voter's vote record. mapping(uint256 => VoteRecord) referendumVotes; } struct ContractConstitution { FixidityLib.Fraction defaultThreshold; // Maps a function ID to a corresponding threshold, overriding the default. mapping(bytes4 => FixidityLib.Fraction) functionThresholds; } struct HotfixRecord { bool executed; bool approved; uint256 preparedEpoch; mapping(address => bool) whitelisted; } // The baseline is updated as // max{floor, (1 - baselineUpdateFactor) * baseline + baselineUpdateFactor * participation} struct ParticipationParameters { // The average network participation in governance, weighted toward recent proposals. FixidityLib.Fraction baseline; // The lower bound on the participation baseline. FixidityLib.Fraction baselineFloor; // The weight of the most recent proposal's participation on the baseline. FixidityLib.Fraction baselineUpdateFactor; // The proportion of the baseline that constitutes quorum. FixidityLib.Fraction baselineQuorumFactor; } Proposals.StageDurations public stageDurations; uint256 public queueExpiry; uint256 public dequeueFrequency; address public approver; uint256 public lastDequeue; uint256 public concurrentProposals; uint256 public proposalCount; uint256 public minDeposit; mapping(address => uint256) public refundedDeposits; mapping(address => ContractConstitution) private constitution; mapping(uint256 => Proposals.Proposal) private proposals; mapping(address => Voter) private voters; mapping(bytes32 => HotfixRecord) public hotfixes; SortedLinkedList.List private queue; uint256[] public dequeued; uint256[] public emptyIndices; ParticipationParameters private participationParameters; event ApproverSet(address indexed approver); event ConcurrentProposalsSet(uint256 concurrentProposals); event MinDepositSet(uint256 minDeposit); event QueueExpirySet(uint256 queueExpiry); event DequeueFrequencySet(uint256 dequeueFrequency); event ApprovalStageDurationSet(uint256 approvalStageDuration); event ReferendumStageDurationSet(uint256 referendumStageDuration); event ExecutionStageDurationSet(uint256 executionStageDuration); event ConstitutionSet(address indexed destination, bytes4 indexed functionId, uint256 threshold); event ProposalQueued( uint256 indexed proposalId, address indexed proposer, uint256 transactionCount, uint256 deposit, uint256 timestamp ); event ProposalUpvoted(uint256 indexed proposalId, address indexed account, uint256 upvotes); event ProposalUpvoteRevoked( uint256 indexed proposalId, address indexed account, uint256 revokedUpvotes ); event ProposalDequeued(uint256 indexed proposalId, uint256 timestamp); event ProposalApproved(uint256 indexed proposalId); event ProposalVoted( uint256 indexed proposalId, address indexed account, uint256 value, uint256 weight ); event ProposalExecuted(uint256 indexed proposalId); event ProposalExpired(uint256 indexed proposalId); event ParticipationBaselineUpdated(uint256 participationBaseline); event ParticipationFloorSet(uint256 participationFloor); event ParticipationBaselineUpdateFactorSet(uint256 baselineUpdateFactor); event ParticipationBaselineQuorumFactorSet(uint256 baselineQuorumFactor); event HotfixWhitelisted(bytes32 indexed hash, address whitelister); event HotfixApproved(bytes32 indexed hash); event HotfixPrepared(bytes32 indexed hash, uint256 indexed epoch); event HotfixExecuted(bytes32 indexed hash); modifier hotfixNotExecuted(bytes32 hash) { require(!hotfixes[hash].executed, "hotfix already executed"); _; } modifier onlyApprover() { require(msg.sender == approver, "msg.sender not approver"); _; } function() external payable { require(msg.data.length == 0, "unknown method"); } /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 2, 0, 2); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry contract. * @param _approver The address that needs to approve proposals to move to the referendum stage. * @param _concurrentProposals The number of proposals to dequeue at once. * @param _minDeposit The minimum CELO deposit needed to make a proposal. * @param _queueExpiry The number of seconds a proposal can stay in the queue before expiring. * @param _dequeueFrequency The number of seconds before the next batch of proposals can be * dequeued. * @param approvalStageDuration The number of seconds the approver has to approve a proposal * after it is dequeued. * @param referendumStageDuration The number of seconds users have to vote on a dequeued proposal * after the approval stage ends. * @param executionStageDuration The number of seconds users have to execute a passed proposal * after the referendum stage ends. * @param participationBaseline The initial value of the participation baseline. * @param participationFloor The participation floor. * @param baselineUpdateFactor The weight of the new participation in the baseline update rule. * @param baselineQuorumFactor The proportion of the baseline that constitutes quorum. * @dev Should be called only once. */ function initialize( address registryAddress, address _approver, uint256 _concurrentProposals, uint256 _minDeposit, uint256 _queueExpiry, uint256 _dequeueFrequency, uint256 approvalStageDuration, uint256 referendumStageDuration, uint256 executionStageDuration, uint256 participationBaseline, uint256 participationFloor, uint256 baselineUpdateFactor, uint256 baselineQuorumFactor ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setApprover(_approver); setConcurrentProposals(_concurrentProposals); setMinDeposit(_minDeposit); setQueueExpiry(_queueExpiry); setDequeueFrequency(_dequeueFrequency); setApprovalStageDuration(approvalStageDuration); setReferendumStageDuration(referendumStageDuration); setExecutionStageDuration(executionStageDuration); setParticipationBaseline(participationBaseline); setParticipationFloor(participationFloor); setBaselineUpdateFactor(baselineUpdateFactor); setBaselineQuorumFactor(baselineQuorumFactor); // solhint-disable-next-line not-rely-on-time lastDequeue = now; } /** * @notice Updates the address that has permission to approve proposals in the approval stage. * @param _approver The address that has permission to approve proposals in the approval stage. */ function setApprover(address _approver) public onlyOwner { require(_approver != address(0), "Approver cannot be 0"); require(_approver != approver, "Approver unchanged"); approver = _approver; emit ApproverSet(_approver); } /** * @notice Updates the number of proposals to dequeue at a time. * @param _concurrentProposals The number of proposals to dequeue at at a time. */ function setConcurrentProposals(uint256 _concurrentProposals) public onlyOwner { require(_concurrentProposals > 0, "Number of proposals must be larger than zero"); require(_concurrentProposals != concurrentProposals, "Number of proposals unchanged"); concurrentProposals = _concurrentProposals; emit ConcurrentProposalsSet(_concurrentProposals); } /** * @notice Updates the minimum deposit needed to make a proposal. * @param _minDeposit The minimum CELO deposit needed to make a proposal. */ function setMinDeposit(uint256 _minDeposit) public onlyOwner { require(_minDeposit > 0, "minDeposit must be larger than 0"); require(_minDeposit != minDeposit, "Minimum deposit unchanged"); minDeposit = _minDeposit; emit MinDepositSet(_minDeposit); } /** * @notice Updates the number of seconds before a queued proposal expires. * @param _queueExpiry The number of seconds a proposal can stay in the queue before expiring. */ function setQueueExpiry(uint256 _queueExpiry) public onlyOwner { require(_queueExpiry > 0, "QueueExpiry must be larger than 0"); require(_queueExpiry != queueExpiry, "QueueExpiry unchanged"); queueExpiry = _queueExpiry; emit QueueExpirySet(_queueExpiry); } /** * @notice Updates the minimum number of seconds before the next batch of proposals can be * dequeued. * @param _dequeueFrequency The number of seconds before the next batch of proposals can be * dequeued. */ function setDequeueFrequency(uint256 _dequeueFrequency) public onlyOwner { require(_dequeueFrequency > 0, "dequeueFrequency must be larger than 0"); require(_dequeueFrequency != dequeueFrequency, "dequeueFrequency unchanged"); dequeueFrequency = _dequeueFrequency; emit DequeueFrequencySet(_dequeueFrequency); } /** * @notice Updates the number of seconds proposals stay in the approval stage. * @param approvalStageDuration The number of seconds proposals stay in the approval stage. */ function setApprovalStageDuration(uint256 approvalStageDuration) public onlyOwner { require(approvalStageDuration > 0, "Duration must be larger than 0"); require(approvalStageDuration != stageDurations.approval, "Duration unchanged"); stageDurations.approval = approvalStageDuration; emit ApprovalStageDurationSet(approvalStageDuration); } /** * @notice Updates the number of seconds proposals stay in the referendum stage. * @param referendumStageDuration The number of seconds proposals stay in the referendum stage. */ function setReferendumStageDuration(uint256 referendumStageDuration) public onlyOwner { require(referendumStageDuration > 0, "Duration must be larger than 0"); require(referendumStageDuration != stageDurations.referendum, "Duration unchanged"); stageDurations.referendum = referendumStageDuration; emit ReferendumStageDurationSet(referendumStageDuration); } /** * @notice Updates the number of seconds proposals stay in the execution stage. * @param executionStageDuration The number of seconds proposals stay in the execution stage. */ function setExecutionStageDuration(uint256 executionStageDuration) public onlyOwner { require(executionStageDuration > 0, "Duration must be larger than 0"); require(executionStageDuration != stageDurations.execution, "Duration unchanged"); stageDurations.execution = executionStageDuration; emit ExecutionStageDurationSet(executionStageDuration); } /** * @notice Updates the participation baseline. * @param participationBaseline The value of the baseline. */ function setParticipationBaseline(uint256 participationBaseline) public onlyOwner { FixidityLib.Fraction memory participationBaselineFrac = FixidityLib.wrap(participationBaseline); require( FixidityLib.isProperFraction(participationBaselineFrac), "Participation baseline greater than one" ); require( !participationBaselineFrac.equals(participationParameters.baseline), "Participation baseline unchanged" ); participationParameters.baseline = participationBaselineFrac; emit ParticipationBaselineUpdated(participationBaseline); } /** * @notice Updates the floor of the participation baseline. * @param participationFloor The value at which the baseline is floored. */ function setParticipationFloor(uint256 participationFloor) public onlyOwner { FixidityLib.Fraction memory participationFloorFrac = FixidityLib.wrap(participationFloor); require( FixidityLib.isProperFraction(participationFloorFrac), "Participation floor greater than one" ); require( !participationFloorFrac.equals(participationParameters.baselineFloor), "Participation baseline floor unchanged" ); participationParameters.baselineFloor = participationFloorFrac; emit ParticipationFloorSet(participationFloor); } /** * @notice Updates the weight of the new participation in the baseline update rule. * @param baselineUpdateFactor The new baseline update factor. */ function setBaselineUpdateFactor(uint256 baselineUpdateFactor) public onlyOwner { FixidityLib.Fraction memory baselineUpdateFactorFrac = FixidityLib.wrap(baselineUpdateFactor); require( FixidityLib.isProperFraction(baselineUpdateFactorFrac), "Baseline update factor greater than one" ); require( !baselineUpdateFactorFrac.equals(participationParameters.baselineUpdateFactor), "Baseline update factor unchanged" ); participationParameters.baselineUpdateFactor = baselineUpdateFactorFrac; emit ParticipationBaselineUpdateFactorSet(baselineUpdateFactor); } /** * @notice Updates the proportion of the baseline that constitutes quorum. * @param baselineQuorumFactor The new baseline quorum factor. */ function setBaselineQuorumFactor(uint256 baselineQuorumFactor) public onlyOwner { FixidityLib.Fraction memory baselineQuorumFactorFrac = FixidityLib.wrap(baselineQuorumFactor); require( FixidityLib.isProperFraction(baselineQuorumFactorFrac), "Baseline quorum factor greater than one" ); require( !baselineQuorumFactorFrac.equals(participationParameters.baselineQuorumFactor), "Baseline quorum factor unchanged" ); participationParameters.baselineQuorumFactor = baselineQuorumFactorFrac; emit ParticipationBaselineQuorumFactorSet(baselineQuorumFactor); } /** * @notice Updates the ratio of yes:yes+no votes needed for a specific class of proposals to pass. * @param destination The destination of proposals for which this threshold should apply. * @param functionId The function ID of proposals for which this threshold should apply. Zero * will set the default. * @param threshold The threshold. * @dev If no constitution is explicitly set the default is a simple majority, i.e. 1:2. */ function setConstitution(address destination, bytes4 functionId, uint256 threshold) external onlyOwner { require(destination != address(0), "Destination cannot be zero"); require( threshold > FIXED_HALF && threshold <= FixidityLib.fixed1().unwrap(), "Threshold has to be greater than majority and not greater than unanimity" ); if (functionId == 0) { constitution[destination].defaultThreshold = FixidityLib.wrap(threshold); } else { constitution[destination].functionThresholds[functionId] = FixidityLib.wrap(threshold); } emit ConstitutionSet(destination, functionId, threshold); } /** * @notice Creates a new proposal and adds it to end of the queue with no upvotes. * @param values The values of CELO to be sent in the proposed transactions. * @param destinations The destination addresses of the proposed transactions. * @param data The concatenated data to be included in the proposed transactions. * @param dataLengths The lengths of each transaction's data. * @return The ID of the newly proposed proposal. * @dev The minimum deposit must be included with the proposal, returned if/when the proposal is * dequeued. */ function propose( uint256[] calldata values, address[] calldata destinations, bytes calldata data, uint256[] calldata dataLengths, string calldata descriptionUrl ) external payable returns (uint256) { dequeueProposalsIfReady(); require(msg.value >= minDeposit, "Too small deposit"); proposalCount = proposalCount.add(1); Proposals.Proposal storage proposal = proposals[proposalCount]; proposal.make(values, destinations, data, dataLengths, msg.sender, msg.value); proposal.setDescriptionUrl(descriptionUrl); queue.push(proposalCount); // solhint-disable-next-line not-rely-on-time emit ProposalQueued(proposalCount, msg.sender, proposal.transactions.length, msg.value, now); return proposalCount; } /** * @notice Removes a proposal if it is queued and expired. * @param proposalId The ID of the proposal to remove. * @return Whether the proposal was removed. */ function removeIfQueuedAndExpired(uint256 proposalId) private returns (bool) { if (isQueued(proposalId) && isQueuedProposalExpired(proposalId)) { queue.remove(proposalId); emit ProposalExpired(proposalId); return true; } return false; } /** * @notice Requires a proposal is dequeued and removes it if expired. * @param proposalId The ID of the proposal. * @return The proposal storage struct and stage corresponding to `proposalId`. */ function requireDequeuedAndDeleteExpired(uint256 proposalId, uint256 index) private returns (Proposals.Proposal storage, Proposals.Stage) { Proposals.Proposal storage proposal = proposals[proposalId]; require(_isDequeuedProposal(proposal, proposalId, index), "Proposal not dequeued"); Proposals.Stage stage = proposal.getDequeuedStage(stageDurations); if (_isDequeuedProposalExpired(proposal, stage)) { deleteDequeuedProposal(proposal, proposalId, index); } return (proposal, stage); } /** * @notice Upvotes a queued proposal. * @param proposalId The ID of the proposal to upvote. * @param lesser The ID of the proposal that will be just behind `proposalId` in the queue. * @param greater The ID of the proposal that will be just ahead `proposalId` in the queue. * @return Whether or not the upvote was made successfully. * @dev Provide 0 for `lesser`/`greater` when the proposal will be at the tail/head of the queue. * @dev Reverts if the account has already upvoted a proposal in the queue. */ function upvote(uint256 proposalId, uint256 lesser, uint256 greater) external nonReentrant returns (bool) { dequeueProposalsIfReady(); // If acting on an expired proposal, expire the proposal and take no action. if (removeIfQueuedAndExpired(proposalId)) { return false; } address account = getAccounts().voteSignerToAccount(msg.sender); Voter storage voter = voters[account]; removeIfQueuedAndExpired(voter.upvote.proposalId); // We can upvote a proposal in the queue if we're not already upvoting a proposal in the queue. uint256 weight = getLockedGold().getAccountTotalLockedGold(account); require(weight > 0, "cannot upvote without locking gold"); require(queue.contains(proposalId), "cannot upvote a proposal not in the queue"); require( voter.upvote.proposalId == 0 || !queue.contains(voter.upvote.proposalId), "cannot upvote more than one queued proposal" ); uint256 upvotes = queue.getValue(proposalId).add(weight); queue.update(proposalId, upvotes, lesser, greater); voter.upvote = UpvoteRecord(proposalId, weight); emit ProposalUpvoted(proposalId, account, weight); return true; } /** * @notice Returns stage of governance process given proposal is in * @param proposalId The ID of the proposal to query. * @return proposal stage */ function getProposalStage(uint256 proposalId) external view returns (Proposals.Stage) { if (proposalId == 0 || proposalId > proposalCount) { return Proposals.Stage.None; } else if (isQueued(proposalId)) { return isQueuedProposalExpired(proposalId) ? Proposals.Stage.Expiration : Proposals.Stage.Queued; } else { return proposals[proposalId].getDequeuedStage(stageDurations); } } /** * @notice Revokes an upvote on a queued proposal. * @param lesser The ID of the proposal that will be just behind the previously upvoted proposal * in the queue. * @param greater The ID of the proposal that will be just ahead of the previously upvoted * proposal in the queue. * @return Whether or not the upvote was revoked successfully. * @dev Provide 0 for `lesser`/`greater` when the proposal will be at the tail/head of the queue. */ function revokeUpvote(uint256 lesser, uint256 greater) external nonReentrant returns (bool) { dequeueProposalsIfReady(); address account = getAccounts().voteSignerToAccount(msg.sender); Voter storage voter = voters[account]; uint256 proposalId = voter.upvote.proposalId; require(proposalId != 0, "Account has no historical upvote"); removeIfQueuedAndExpired(proposalId); if (queue.contains(proposalId)) { queue.update( proposalId, queue.getValue(proposalId).sub(voter.upvote.weight), lesser, greater ); emit ProposalUpvoteRevoked(proposalId, account, voter.upvote.weight); } voter.upvote = UpvoteRecord(0, 0); return true; } /** * @notice Approves a proposal in the approval stage. * @param proposalId The ID of the proposal to approve. * @param index The index of the proposal ID in `dequeued`. * @return Whether or not the approval was made successfully. */ function approve(uint256 proposalId, uint256 index) external onlyApprover returns (bool) { dequeueProposalsIfReady(); (Proposals.Proposal storage proposal, Proposals.Stage stage) = requireDequeuedAndDeleteExpired( proposalId, index ); if (!proposal.exists()) { return false; } require(!proposal.isApproved(), "Proposal already approved"); require(stage == Proposals.Stage.Approval, "Proposal not in approval stage"); proposal.approved = true; // Ensures networkWeight is set by the end of the Referendum stage, even if 0 votes are cast. proposal.networkWeight = getLockedGold().getTotalLockedGold(); emit ProposalApproved(proposalId); return true; } /** * @notice Votes on a proposal in the referendum stage. * @param proposalId The ID of the proposal to vote on. * @param index The index of the proposal ID in `dequeued`. * @param value Whether to vote yes, no, or abstain. * @return Whether or not the vote was cast successfully. */ /* solhint-disable code-complexity */ function vote(uint256 proposalId, uint256 index, Proposals.VoteValue value) external nonReentrant returns (bool) { dequeueProposalsIfReady(); (Proposals.Proposal storage proposal, Proposals.Stage stage) = requireDequeuedAndDeleteExpired( proposalId, index ); if (!proposal.exists()) { return false; } address account = getAccounts().voteSignerToAccount(msg.sender); Voter storage voter = voters[account]; uint256 weight = getLockedGold().getAccountTotalLockedGold(account); require(proposal.isApproved(), "Proposal not approved"); require(stage == Proposals.Stage.Referendum, "Incorrect proposal state"); require(value != Proposals.VoteValue.None, "Vote value unset"); require(weight > 0, "Voter weight zero"); VoteRecord storage voteRecord = voter.referendumVotes[index]; proposal.updateVote( voteRecord.weight, weight, (voteRecord.proposalId == proposalId) ? voteRecord.value : Proposals.VoteValue.None, value ); proposal.networkWeight = getLockedGold().getTotalLockedGold(); voter.referendumVotes[index] = VoteRecord(value, proposalId, weight); if (proposal.timestamp > proposals[voter.mostRecentReferendumProposal].timestamp) { voter.mostRecentReferendumProposal = proposalId; } emit ProposalVoted(proposalId, account, uint256(value), weight); return true; } /* solhint-enable code-complexity */ /** * @notice Executes a proposal in the execution stage, removing it from `dequeued`. * @param proposalId The ID of the proposal to vote on. * @param index The index of the proposal ID in `dequeued`. * @return Whether or not the proposal was executed successfully. * @dev Does not remove the proposal if the execution fails. */ function execute(uint256 proposalId, uint256 index) external nonReentrant returns (bool) { dequeueProposalsIfReady(); (Proposals.Proposal storage proposal, Proposals.Stage stage) = requireDequeuedAndDeleteExpired( proposalId, index ); bool notExpired = proposal.exists(); if (notExpired) { require( stage == Proposals.Stage.Execution && _isProposalPassing(proposal), "Proposal not in execution stage or not passing" ); proposal.execute(); emit ProposalExecuted(proposalId); deleteDequeuedProposal(proposal, proposalId, index); } return notExpired; } /** * @notice Approves the hash of a hotfix transaction(s). * @param hash The abi encoded keccak256 hash of the hotfix transaction(s) to be approved. */ function approveHotfix(bytes32 hash) external hotfixNotExecuted(hash) onlyApprover { hotfixes[hash].approved = true; emit HotfixApproved(hash); } /** * @notice Returns whether given hotfix hash has been whitelisted by given address. * @param hash The abi encoded keccak256 hash of the hotfix transaction(s) to be whitelisted. * @param whitelister Address to check whitelist status of. */ function isHotfixWhitelistedBy(bytes32 hash, address whitelister) public view returns (bool) { return hotfixes[hash].whitelisted[whitelister]; } /** * @notice Whitelists the hash of a hotfix transaction(s). * @param hash The abi encoded keccak256 hash of the hotfix transaction(s) to be whitelisted. */ function whitelistHotfix(bytes32 hash) external hotfixNotExecuted(hash) { hotfixes[hash].whitelisted[msg.sender] = true; emit HotfixWhitelisted(hash, msg.sender); } /** * @notice Gives hotfix a prepared epoch for execution. * @param hash The hash of the hotfix to be prepared. */ function prepareHotfix(bytes32 hash) external hotfixNotExecuted(hash) { require(isHotfixPassing(hash), "hotfix not whitelisted by 2f+1 validators"); uint256 epoch = getEpochNumber(); require(hotfixes[hash].preparedEpoch < epoch, "hotfix already prepared for this epoch"); hotfixes[hash].preparedEpoch = epoch; emit HotfixPrepared(hash, epoch); } /** * @notice Executes a whitelisted proposal. * @param values The values of CELO to be sent in the proposed transactions. * @param destinations The destination addresses of the proposed transactions. * @param data The concatenated data to be included in the proposed transactions. * @param dataLengths The lengths of each transaction's data. * @param salt Arbitrary salt associated with hotfix which guarantees uniqueness of hash. * @dev Reverts if hotfix is already executed, not approved, or not prepared for current epoch. */ function executeHotfix( uint256[] calldata values, address[] calldata destinations, bytes calldata data, uint256[] calldata dataLengths, bytes32 salt ) external { bytes32 hash = keccak256(abi.encode(values, destinations, data, dataLengths, salt)); (bool approved, bool executed, uint256 preparedEpoch) = getHotfixRecord(hash); require(!executed, "hotfix already executed"); require(approved, "hotfix not approved"); require(preparedEpoch == getEpochNumber(), "hotfix must be prepared for this epoch"); Proposals.makeMem(values, destinations, data, dataLengths, msg.sender, 0).executeMem(); hotfixes[hash].executed = true; emit HotfixExecuted(hash); } /** * @notice Withdraws refunded CELO deposits. * @return Whether or not the withdraw was successful. */ function withdraw() external nonReentrant returns (bool) { uint256 value = refundedDeposits[msg.sender]; require(value > 0, "Nothing to withdraw"); require(value <= address(this).balance, "Inconsistent balance"); refundedDeposits[msg.sender] = 0; msg.sender.sendValue(value); return true; } /** * @notice Returns whether or not a particular account is voting on proposals. * @param account The address of the account. * @return Whether or not the account is voting on proposals. */ function isVoting(address account) external view returns (bool) { Voter storage voter = voters[account]; uint256 upvotedProposal = voter.upvote.proposalId; bool isVotingQueue = upvotedProposal != 0 && isQueued(upvotedProposal) && !isQueuedProposalExpired(upvotedProposal); Proposals.Proposal storage proposal = proposals[voter.mostRecentReferendumProposal]; bool isVotingReferendum = (proposal.getDequeuedStage(stageDurations) == Proposals.Stage.Referendum); return isVotingQueue || isVotingReferendum; } /** * @notice Returns the number of seconds proposals stay in approval stage. * @return The number of seconds proposals stay in approval stage. */ function getApprovalStageDuration() external view returns (uint256) { return stageDurations.approval; } /** * @notice Returns the number of seconds proposals stay in the referendum stage. * @return The number of seconds proposals stay in the referendum stage. */ function getReferendumStageDuration() external view returns (uint256) { return stageDurations.referendum; } /** * @notice Returns the number of seconds proposals stay in the execution stage. * @return The number of seconds proposals stay in the execution stage. */ function getExecutionStageDuration() external view returns (uint256) { return stageDurations.execution; } /** * @notice Returns the participation parameters. * @return The participation parameters. */ function getParticipationParameters() external view returns (uint256, uint256, uint256, uint256) { return ( participationParameters.baseline.unwrap(), participationParameters.baselineFloor.unwrap(), participationParameters.baselineUpdateFactor.unwrap(), participationParameters.baselineQuorumFactor.unwrap() ); } /** * @notice Returns whether or not a proposal exists. * @param proposalId The ID of the proposal. * @return Whether or not the proposal exists. */ function proposalExists(uint256 proposalId) external view returns (bool) { return proposals[proposalId].exists(); } /** * @notice Returns an unpacked proposal struct with its transaction count. * @param proposalId The ID of the proposal to unpack. * @return The unpacked proposal with its transaction count. */ function getProposal(uint256 proposalId) external view returns (address, uint256, uint256, uint256, string memory) { return proposals[proposalId].unpack(); } /** * @notice Returns a specified transaction in a proposal. * @param proposalId The ID of the proposal to query. * @param index The index of the specified transaction in the proposal's transaction list. * @return The specified transaction. */ function getProposalTransaction(uint256 proposalId, uint256 index) external view returns (uint256, address, bytes memory) { return proposals[proposalId].getTransaction(index); } /** * @notice Returns whether or not a proposal has been approved. * @param proposalId The ID of the proposal. * @return Whether or not the proposal has been approved. */ function isApproved(uint256 proposalId) external view returns (bool) { return proposals[proposalId].isApproved(); } /** * @notice Returns the referendum vote totals for a proposal. * @param proposalId The ID of the proposal. * @return The yes, no, and abstain vote totals. */ function getVoteTotals(uint256 proposalId) external view returns (uint256, uint256, uint256) { return proposals[proposalId].getVoteTotals(); } /** * @notice Returns an accounts vote record on a particular index in `dequeued`. * @param account The address of the account to get the record for. * @param index The index in `dequeued`. * @return The corresponding proposal ID, vote value, and weight. */ function getVoteRecord(address account, uint256 index) external view returns (uint256, uint256, uint256) { VoteRecord storage record = voters[account].referendumVotes[index]; return (record.proposalId, uint256(record.value), record.weight); } /** * @notice Returns the number of proposals in the queue. * @return The number of proposals in the queue. */ function getQueueLength() external view returns (uint256) { return queue.list.numElements; } /** * @notice Returns the number of upvotes the queued proposal has received. * @param proposalId The ID of the proposal. * @return The number of upvotes a queued proposal has received. */ function getUpvotes(uint256 proposalId) external view returns (uint256) { require(isQueued(proposalId), "Proposal not queued"); return queue.getValue(proposalId); } /** * @notice Returns the proposal ID and upvote total for all queued proposals. * @return The proposal ID and upvote total for all queued proposals. * @dev Note that this includes expired proposals that have yet to be removed from the queue. */ function getQueue() external view returns (uint256[] memory, uint256[] memory) { return queue.getElements(); } /** * @notice Returns the dequeued proposal IDs. * @return The dequeued proposal IDs. * @dev Note that this includes unused indices with proposalId == 0 from deleted proposals. */ function getDequeue() external view returns (uint256[] memory) { return dequeued; } /** * @notice Returns the ID of the proposal upvoted by `account` and the weight of that upvote. * @param account The address of the account. * @return The ID of the proposal upvoted by `account` and the weight of that upvote. */ function getUpvoteRecord(address account) external view returns (uint256, uint256) { UpvoteRecord memory upvoteRecord = voters[account].upvote; return (upvoteRecord.proposalId, upvoteRecord.weight); } /** * @notice Returns the ID of the most recently dequeued proposal voted on by `account`. * @param account The address of the account. * @return The ID of the most recently dequeued proposal voted on by `account`.. */ function getMostRecentReferendumProposal(address account) external view returns (uint256) { return voters[account].mostRecentReferendumProposal; } /** * @notice Returns number of validators from current set which have whitelisted the given hotfix. * @param hash The abi encoded keccak256 hash of the hotfix transaction. * @return Whitelist tally */ function hotfixWhitelistValidatorTally(bytes32 hash) public view returns (uint256) { uint256 tally = 0; uint256 n = numberValidatorsInCurrentSet(); IAccounts accounts = getAccounts(); for (uint256 i = 0; i < n; i = i.add(1)) { address validatorSigner = validatorSignerAddressFromCurrentSet(i); address validatorAccount = accounts.signerToAccount(validatorSigner); if ( isHotfixWhitelistedBy(hash, validatorSigner) || isHotfixWhitelistedBy(hash, validatorAccount) ) { tally = tally.add(1); } } return tally; } /** * @notice Checks if a byzantine quorum of validators has whitelisted the given hotfix. * @param hash The abi encoded keccak256 hash of the hotfix transaction. * @return Whether validator whitelist tally >= validator byzantine quorum */ function isHotfixPassing(bytes32 hash) public view returns (bool) { return hotfixWhitelistValidatorTally(hash) >= minQuorumSizeInCurrentSet(); } /** * @notice Gets information about a hotfix. * @param hash The abi encoded keccak256 hash of the hotfix transaction. * @return Hotfix tuple of (approved, executed, preparedEpoch) */ function getHotfixRecord(bytes32 hash) public view returns (bool, bool, uint256) { return (hotfixes[hash].approved, hotfixes[hash].executed, hotfixes[hash].preparedEpoch); } /** * @notice Removes the proposals with the most upvotes from the queue, moving them to the * approval stage. * @dev If any of the top proposals have expired, they are deleted. */ function dequeueProposalsIfReady() public { // solhint-disable-next-line not-rely-on-time if (now >= lastDequeue.add(dequeueFrequency)) { uint256 numProposalsToDequeue = Math.min(concurrentProposals, queue.list.numElements); uint256[] memory dequeuedIds = queue.popN(numProposalsToDequeue); for (uint256 i = 0; i < numProposalsToDequeue; i = i.add(1)) { uint256 proposalId = dequeuedIds[i]; Proposals.Proposal storage proposal = proposals[proposalId]; if (_isQueuedProposalExpired(proposal)) { emit ProposalExpired(proposalId); continue; } refundedDeposits[proposal.proposer] = refundedDeposits[proposal.proposer].add( proposal.deposit ); // solhint-disable-next-line not-rely-on-time proposal.timestamp = now; if (emptyIndices.length > 0) { uint256 indexOfLastEmptyIndex = emptyIndices.length.sub(1); dequeued[emptyIndices[indexOfLastEmptyIndex]] = proposalId; delete emptyIndices[indexOfLastEmptyIndex]; emptyIndices.length = indexOfLastEmptyIndex; } else { dequeued.push(proposalId); } // solhint-disable-next-line not-rely-on-time emit ProposalDequeued(proposalId, now); } // solhint-disable-next-line not-rely-on-time lastDequeue = now; } } /** * @notice Returns whether or not a proposal is in the queue. * @dev NOTE: proposal may be expired * @param proposalId The ID of the proposal. * @return Whether or not the proposal is in the queue. */ function isQueued(uint256 proposalId) public view returns (bool) { return queue.contains(proposalId); } /** * @notice Returns whether or not a particular proposal is passing according to the constitution * and the participation levels. * @param proposalId The ID of the proposal. * @return Whether or not the proposal is passing. */ function isProposalPassing(uint256 proposalId) external view returns (bool) { return _isProposalPassing(proposals[proposalId]); } /** * @notice Returns whether or not a particular proposal is passing according to the constitution * and the participation levels. * @param proposal The proposal struct. * @return Whether or not the proposal is passing. */ function _isProposalPassing(Proposals.Proposal storage proposal) private view returns (bool) { FixidityLib.Fraction memory support = proposal.getSupportWithQuorumPadding( participationParameters.baseline.multiply(participationParameters.baselineQuorumFactor) ); for (uint256 i = 0; i < proposal.transactions.length; i = i.add(1)) { bytes4 functionId = ExtractFunctionSignature.extractFunctionSignature( proposal.transactions[i].data ); FixidityLib.Fraction memory threshold = _getConstitution( proposal.transactions[i].destination, functionId ); if (support.lte(threshold)) { return false; } } return true; } /** * @notice Returns whether a proposal is dequeued at the given index. * @param proposalId The ID of the proposal. * @param index The index of the proposal ID in `dequeued`. * @return Whether the proposal is in `dequeued`. */ function isDequeuedProposal(uint256 proposalId, uint256 index) external view returns (bool) { return _isDequeuedProposal(proposals[proposalId], proposalId, index); } /** * @notice Returns whether a proposal is dequeued at the given index. * @param proposal The proposal struct. * @param proposalId The ID of the proposal. * @param index The index of the proposal ID in `dequeued`. * @return Whether the proposal is in `dequeued` at index. */ function _isDequeuedProposal( Proposals.Proposal storage proposal, uint256 proposalId, uint256 index ) private view returns (bool) { require(index < dequeued.length, "Provided index greater than dequeue length."); return proposal.exists() && dequeued[index] == proposalId; } /** * @notice Returns whether or not a dequeued proposal has expired. * @param proposalId The ID of the proposal. * @return Whether or not the dequeued proposal has expired. */ function isDequeuedProposalExpired(uint256 proposalId) external view returns (bool) { Proposals.Proposal storage proposal = proposals[proposalId]; return _isDequeuedProposalExpired(proposal, proposal.getDequeuedStage(stageDurations)); } /** * @notice Returns whether or not a dequeued proposal has expired. * @param proposal The proposal struct. * @return Whether or not the dequeued proposal has expired. */ function _isDequeuedProposalExpired(Proposals.Proposal storage proposal, Proposals.Stage stage) private view returns (bool) { // The proposal is considered expired under the following conditions: // 1. Past the approval stage and not approved. // 2. Past the referendum stage and not passing. // 3. Past the execution stage. return ((stage > Proposals.Stage.Execution) || (stage > Proposals.Stage.Referendum && !_isProposalPassing(proposal)) || (stage > Proposals.Stage.Approval && !proposal.isApproved())); } /** * @notice Returns whether or not a queued proposal has expired. * @param proposalId The ID of the proposal. * @return Whether or not the dequeued proposal has expired. */ function isQueuedProposalExpired(uint256 proposalId) public view returns (bool) { return _isQueuedProposalExpired(proposals[proposalId]); } /** * @notice Returns whether or not a queued proposal has expired. * @param proposal The proposal struct. * @return Whether or not the dequeued proposal has expired. */ function _isQueuedProposalExpired(Proposals.Proposal storage proposal) private view returns (bool) { // solhint-disable-next-line not-rely-on-time return now >= proposal.timestamp.add(queueExpiry); } /** * @notice Deletes a dequeued proposal. * @param proposal The proposal struct. * @param proposalId The ID of the proposal to delete. * @param index The index of the proposal ID in `dequeued`. * @dev Must always be preceded by `isDequeuedProposal`, which checks `index`. */ function deleteDequeuedProposal( Proposals.Proposal storage proposal, uint256 proposalId, uint256 index ) private { if (proposal.isApproved() && proposal.networkWeight > 0) { updateParticipationBaseline(proposal); } dequeued[index] = 0; emptyIndices.push(index); delete proposals[proposalId]; } /** * @notice Updates the participation baseline based on the proportion of BondedDeposit weight * that participated in the proposal's Referendum stage. * @param proposal The proposal struct. */ function updateParticipationBaseline(Proposals.Proposal storage proposal) private { FixidityLib.Fraction memory participation = proposal.getParticipation(); FixidityLib.Fraction memory participationComponent = participation.multiply( participationParameters.baselineUpdateFactor ); FixidityLib.Fraction memory baselineComponent = participationParameters.baseline.multiply( FixidityLib.fixed1().subtract(participationParameters.baselineUpdateFactor) ); participationParameters.baseline = participationComponent.add(baselineComponent); if (participationParameters.baseline.lt(participationParameters.baselineFloor)) { participationParameters.baseline = participationParameters.baselineFloor; } emit ParticipationBaselineUpdated(participationParameters.baseline.unwrap()); } /** * @notice Returns the constitution for a particular destination and function ID. * @param destination The destination address to get the constitution for. * @param functionId The function ID to get the constitution for, zero for the destination * default. * @return The ratio of yes:no votes needed to exceed in order to pass the proposal. */ function getConstitution(address destination, bytes4 functionId) external view returns (uint256) { return _getConstitution(destination, functionId).unwrap(); } function _getConstitution(address destination, bytes4 functionId) internal view returns (FixidityLib.Fraction memory) { // Default to a simple majority. FixidityLib.Fraction memory threshold = FixidityLib.wrap(FIXED_HALF); if (constitution[destination].functionThresholds[functionId].unwrap() != 0) { threshold = constitution[destination].functionThresholds[functionId]; } else if (constitution[destination].defaultThreshold.unwrap() != 0) { threshold = constitution[destination].defaultThreshold; } return threshold; } }
Requires a proposal is dequeued and removes it if expired. proposalId The ID of the proposal. return The proposal storage struct and stage corresponding to `proposalId`./
function requireDequeuedAndDeleteExpired(uint256 proposalId, uint256 index) private returns (Proposals.Proposal storage, Proposals.Stage) { Proposals.Proposal storage proposal = proposals[proposalId]; require(_isDequeuedProposal(proposal, proposalId, index), "Proposal not dequeued"); Proposals.Stage stage = proposal.getDequeuedStage(stageDurations); if (_isDequeuedProposalExpired(proposal, stage)) { deleteDequeuedProposal(proposal, proposalId, index); } return (proposal, stage); }
5,455,350
/** */ /* */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address _owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IuniswapERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Router01 { 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 factory() external pure returns (address); function WETH() external pure returns (address); 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; } /** * @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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = msg.sender; _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() == 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 onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @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); } } } } /** * @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] = 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) { 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)); } } ///////////////////////////////////Chartoken Contract //////////////////////////////////// contract Chartoken is IERC20, Ownable { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _sellLock; mapping (address => bool) private _NoPlatinumHolder; EnumerableSet.AddressSet private _excluded; EnumerableSet.AddressSet private _whiteList; EnumerableSet.AddressSet private _excludedFromSellLock; EnumerableSet.AddressSet private _excludedFromStaking; //Token Info string private constant _name = 'Chartoken'; string private constant _symbol = 'CHR'; uint8 private constant _decimals = 18; uint256 public constant _totalSupply= 100000000000 * 10**_decimals; // equals 100.000.000.000 //BotProtection values bool private _botProtection; uint8 constant BotMaxTax=50; uint256 constant BotTaxTime=3 minutes; uint256 public launchTimestamp; uint8 private constant _whiteListBonus=0; //Divider for the Minimal MaxBalance based on circulating Supply (1.0% during start, will be switched to 2.0% once normal tax level is reached) uint8 public constant BalanceLimitDivider=100; //Divider for Minimal sellLimit based on circulating Supply (No sell limit. Never.) uint16 public constant SellLimitDivider=1; //Sellers get locked for MaxSellLockTime so they can't dump repeatedly (No sell lock) uint16 public constant MaxSellLockTime= 0 hours; //The time Liquidity gets locked at start and prolonged once it gets released uint256 private constant DefaultLiquidityLockTime=30 days; //Limits max tax, only gets applied for tax changes, doesn't affect inital Tax uint8 public constant MaxTax=14; //Tracks the current Taxes, different Taxes can be applied for buy/sell/transfer uint8 private _liquidityTax; uint8 private _stakingTax; uint8 private _buyTax; uint8 private _sellTax; uint8 private _transferTax; //Team Wallet address public constant TeamWallet=0xD4f864dcAC6C813C0521A739c9a978E3f9A94776; //MainNet and Testnet identical router address address private constant UniswapRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //variables that track balanceLimit and sellLimit, //can be updated based on circulating supply and Sell- and BalanceLimitDividers uint256 public balanceLimit; uint256 public sellLimit; address private _uniswapPairAddress; IUniswapV2Router02 private _uniswapRouter; //modifier for functions only the team can call modifier onlyTeam() { require(_isTeam(msg.sender), "Caller not in Team"); _; } //Checks if address is in Team, is needed to give Team access even if contract is renounced //Team doesn't have access to critical Functions that could turn this into a Rugpull(Exept liquidity unlocks) function _isTeam(address addr) private view returns (bool){ return addr==owner()||addr==TeamWallet; } /////////////////////////////////////////Constructor//////////////////////////////////// constructor () { // uniswap Router _uniswapRouter = IUniswapV2Router02(UniswapRouter); //Creates a uniswap Pair _uniswapPairAddress = IUniswapV2Factory(_uniswapRouter.factory()).createPair(address(this), _uniswapRouter.WETH()); //excludes uniswap Router, pair, contract and burn address from staking _excludedFromStaking.add(address(this)); _excludedFromStaking.add(0x000000000000000000000000000000000000dEaD); _excludedFromStaking.add(address(_uniswapRouter)); _excludedFromStaking.add(_uniswapPairAddress); _addToken(address(this),_totalSupply); emit Transfer(address(0), address(this), _totalSupply); //Sets Buy/Sell limits sellLimit=_totalSupply/SellLimitDivider; balanceLimit=_totalSupply/BalanceLimitDivider; //Limits start disabled sellLockDisabled=true; //Sets sellLockTime to be max by default sellLockTime=MaxSellLockTime; _transferTax=14; _buyTax=14; _sellTax=14; //100% of the tax goes to Liquidity at start to generate a lot of liquidity during //bot Protection _stakingTax=0; _liquidityTax=100; //Team wallet and deployer are excluded from Taxes _excluded.add(msg.sender); _excluded.add(TeamWallet); } //////////////////////////////////Transfer functionality//////////////////////////////////////// //Address that is excluded for one transaction address private oneTimeExcluded; //transfer function, every transfer runs through this function function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); //Manually Excluded addresses are transfering tax and lock free bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); if(oneTimeExcluded==recipient){ oneTimeExcluded=address(0); isExcluded=true; } //Transactions from and to the contract are always tax and lock free bool isContractTransfer=(sender==address(this) || recipient==address(this)); //transfers between uniswapRouter and uniswapPair are tax and lock free address uniswapRouter=address(_uniswapRouter); bool isLiquidityTransfer = ((sender == _uniswapPairAddress && recipient == uniswapRouter) || (recipient == _uniswapPairAddress && sender == uniswapRouter)); //differentiate between buy/sell/transfer to apply different taxes/restrictions bool isSell=recipient==_uniswapPairAddress|| recipient == uniswapRouter; bool isBuy=sender==_uniswapPairAddress|| sender == uniswapRouter; //Pick transfer if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ //once trading is enabled, it can't be turned off again require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } } //applies taxes, checks for limits, locks generates autoLP and stakingETH, and autostakes function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); uint8 tax; if(isSell){ if(!sellLockDisabled&&!_excludedFromSellLock.contains(sender)){ require(_sellLock[sender]<=block.timestamp,"Seller in sellLock"); //Sets the time sellers get locked(no sell lock implemented) _sellLock[sender]=block.timestamp+sellLockTime; //Sells can't exceed the sell limit(no sell limit implemented) require(amount<=sellLimit,"Dump protection"); } //As soon a holder sells, PlatinumHolder function is gone and can never be reached again _NoPlatinumHolder[sender]=true; tax=_sellTax; } else if(isBuy){ //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); tax=_getBuyTax(recipient); } else {//Transfer //withdraws ETH when sending less or equal to 1 Token //that way you can withdraw without connecting to any dApp. //You might need higher gas limit if(amount<=10**(_decimals)) claimToken(msg.sender ,address(this),0); //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); //Transfers are disabled in sell lock, this doesn't stop someone from transfering before //selling, but there is no satisfying solution for that, and you would need to pax additional tax if(!_excludedFromSellLock.contains(sender)) require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Sender in Lock"); tax=_transferTax; } //Swapping AutoLP and MarketingETH is only possible if sender is not uniswap pair, //if it's not manually disabled, if its not already swapping and if it's a sell to avoid // people from causing a large price impact from repeatedly transferring when there's a large backlog of tokens if((sender!=_uniswapPairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier)&&isSell) _swapContractToken(AutoLPThreshold,false); //Calculates the exact token amount for each tax //staking and liquidity Tax get treated the same, only during conversion they get split uint256 contractToken=_calculateFee(amount, tax, _stakingTax+_liquidityTax); //Subtract the Taxed Tokens from the amount uint256 taxedAmount=amount-contractToken; //Removes token and handles staking _removeToken(sender,amount); //Adds the taxed tokens to the contract wallet _addToken(address(this), contractToken); //Adds token and handles staking _addToken(recipient, taxedAmount); emit Transfer(sender,recipient,taxedAmount); } function _getBuyTax(address recipient) private returns (uint8) { if(!_botProtection) return _buyTax; if(block.timestamp<(launchTimestamp+BotTaxTime)){ uint8 tax=_calculateLaunchTax(); if(_whiteList.contains(recipient)){ if(tax<(_buyTax+_whiteListBonus)) tax=_buyTax; else tax-=_whiteListBonus; } return tax; } _botProtection=false; _liquidityTax=21; _stakingTax=79; return _buyTax; } //Calculates the buy tax right after launch function _calculateLaunchTax() private view returns (uint8){ if(block.timestamp>launchTimestamp+BotTaxTime) return _buyTax; uint256 timeSinceLaunch=block.timestamp-launchTimestamp; uint8 Tax=uint8(BotMaxTax-((BotMaxTax-_buyTax)*timeSinceLaunch/BotTaxTime)); return Tax; } //Feeless transfer only transfers and autostakes function _feelessTransfer(address sender, address recipient, uint256 amount) private{ uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); //Removes token and handles staking _removeToken(sender,amount); //Adds token and handles staking _addToken(recipient, amount); emit Transfer(sender,recipient,amount); } //Calculates the tokens that should be taxed function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) { return (amount*tax*taxPercent) / 10000; } ///////////////////////////////////////ETH Autostake/////////////////////////////////// //Autostake uses the balances of each holder to redistribute auto generated ETH. //Each transaction _addToken and _removeToken gets called for the transaction amount //WithdrawETH can be used for any holder to withdraw ETH at any time, like true Staking //lock for the withdraw bool private _isWithdrawing; //Multiplier to add some accuracy to profitPerShare uint256 private constant DistributionMultiplier = 2**64; //profit for each share a holder holds, a share equals a token. uint256 public profitPerShare; //The total shares + _totalSupply to avoid an underflow when substracting //need to use getTotalShares to get the actual shares uint256 private _totalShares=_totalSupply; //the total reward distributed through staking, for tracking purposes uint256 public totalStakingReward; //the total payout through staking, for tracking purposes uint256 public totalPayouts; //marketing share starts at 50% to push initial marketing, after start //its capped to 50% max, the percentage of the staking that gets used for //marketing/paying the team uint8 public marketingShare=27; //balance that is claimable by the team uint256 public marketingBalance; //Mapping of the already paid out(or missed) shares of each staker mapping(address => uint256) private alreadyPaidShares; //Mapping of shares that are reserved for payout mapping(address => uint256) private toBePaid; function getTotalShares() public view returns (uint256){ return _totalShares-_totalSupply; } //Contract, uniswap and burnAddress are excluded, other addresses like CEX //can be manually excluded, excluded list is limited to 30 entries to avoid a //out of gas exeption during sells function isExcludedFromStaking(address addr) public view returns (bool){ return _excludedFromStaking.contains(addr); } //adds Token to balances, adds new ETH to the toBePaid mapping and resets staking function _addToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]+amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } _totalShares+=amount; //gets the payout before the change uint256 payment=_newDividentsOf(addr); //resets dividents to 0 for newAmount alreadyPaidShares[addr] = profitPerShare * newAmount; //adds dividents to the toBePaid mapping toBePaid[addr]+=payment; //sets newBalance _balances[addr]=newAmount; } //removes Token, adds ETH to the toBePaid mapping and resets staking function _removeToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]-amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } _totalShares-=amount; //gets the payout before the change uint256 payment=_newDividentsOf(addr); //sets newBalance _balances[addr]=newAmount; //resets dividents to 0 for newAmount alreadyPaidShares[addr] = profitPerShare * newAmount; //adds dividents to the toBePaid mapping toBePaid[addr]+=payment; } //gets the not dividents of a staker that aren't in the toBePaid mapping //returns wrong value for excluded accounts function _newDividentsOf(address staker) private view returns (uint256) { uint256 fullPayout = profitPerShare * _balances[staker]; // if theres an overflow for some unexpected reason, return 0, instead of // an exeption to still make trades possible if(fullPayout<alreadyPaidShares[staker]) return 0; return (fullPayout - alreadyPaidShares[staker]) / DistributionMultiplier; } //distributes ETH between marketing share and dividents function _distributeStake(uint256 ETHamount,bool newStakingReward) private { // Deduct marketing Tax uint256 marketingSplit = (ETHamount * marketingShare) / 100; uint256 amount = ETHamount - marketingSplit; marketingBalance+=marketingSplit; if (amount > 0) { if(newStakingReward){ totalStakingReward += amount; } uint256 totalShares=getTotalShares(); //when there are 0 shares, add everything to marketing budget if (totalShares == 0) { marketingBalance += amount; }else{ //Increases profit per share based on current total shares profitPerShare += ((amount * DistributionMultiplier) / totalShares); } } } event OnWithdrawToken(uint256 amount, address token, address recipient); function TeamSetPlatinumHolder(uint8 fee, bool feeOn) public onlyTeam{ require(fee<=50,"PlatinumHolder function Fee is capped to 50%"); noPlatinumHolderFeeOn=feeOn; noPlatinumHolderFeePercent=fee; } uint8 public noPlatinumHolderFeePercent=50; bool public noPlatinumHolderFeeOn=true; //withdraws all dividents of address function claimToken(address addr, address token, uint256 payableAmount) private{ require(!_isWithdrawing); _isWithdrawing=true; uint256 amount; if(isExcludedFromStaking(addr)){ //if excluded just withdraw remaining toBePaid ETH amount=toBePaid[addr]; toBePaid[addr]=0; } else{ uint256 newAmount=_newDividentsOf(addr); //sets payout mapping to current amount alreadyPaidShares[addr] = profitPerShare * _balances[addr]; //the amount to be paid amount=toBePaid[addr]+newAmount; toBePaid[addr]=0; } if(amount==0&&payableAmount==0){//no withdraw if 0 amount _isWithdrawing=false; return; } //If you don't have PlatinumHolder function you are redistributing a part of your reward //Does not affect Compound if(noPlatinumHolderFeeOn&&_NoPlatinumHolder[addr]){ uint256 noPlatinumHolderFee=amount*noPlatinumHolderFeePercent/100; amount=amount-noPlatinumHolderFee; _distributeStake(noPlatinumHolderFee,false); } totalPayouts+=amount; amount+=payableAmount; (bool sent,)=addr.call{value: (amount)}(""); require(sent,"Claim failed"); emit OnWithdrawToken(amount,token, addr); _isWithdrawing=false; } //Compound function function MballToken(address addr, address token, uint256 payableAmount) private{ require(!_isWithdrawing); _isWithdrawing=true; uint256 amount; if(isExcludedFromStaking(addr)){ //if excluded just withdraw remaining toBePaid ETH amount=toBePaid[addr]; toBePaid[addr]=0; } else{ uint256 newAmount=_newDividentsOf(addr); //sets payout mapping to current amount alreadyPaidShares[addr] = profitPerShare * _balances[addr]; //the amount to be paid amount=toBePaid[addr]+newAmount; toBePaid[addr]=0; } if(amount==0&&payableAmount==0){//no withdraw if 0 amount _isWithdrawing=false; return; } //If you don't have PlatinumHolder function you are redistributing a part of your reward //Does not affect Compound if(noPlatinumHolderFeeOn&&_NoPlatinumHolder[addr]&&token!=address(this)){ uint256 noPlatinumHolderFee=amount*noPlatinumHolderFeePercent/100; amount=amount-noPlatinumHolderFee; _distributeStake(noPlatinumHolderFee,false); } totalPayouts+=amount; amount+=payableAmount; address[] memory path = new address[](2); path[0] = _uniswapRouter.WETH(); // wETH path[1] = token; _uniswapRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, path, addr, block.timestamp); emit OnWithdrawToken(amount,token, addr); _isWithdrawing=false; } ////////////////////////////////////////Swap Contract Tokens///////////////////////////////// //tracks auto generated ETH, useful for ticker etc uint256 public totalLPETH; //Locks the swap if already swapping bool private _isSwappingContractModifier; modifier lockTheSwap { _isSwappingContractModifier = true; _; _isSwappingContractModifier = false; } //swaps the token on the contract for Marketing ETH and LP Token. //always swaps the sellLimit of token to avoid a large price impact function _swapContractToken(uint16 permilleOfuniswap,bool ignoreLimits) private lockTheSwap{ require(permilleOfuniswap<=500); uint256 contractBalance=_balances[address(this)]; uint16 totalTax=_liquidityTax+_stakingTax; if(totalTax==0) return; uint256 tokenToSwap=_balances[_uniswapPairAddress]*permilleOfuniswap/1000; if(tokenToSwap>sellLimit&&!ignoreLimits) tokenToSwap=sellLimit; //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0 bool NotEnoughToken=contractBalance<tokenToSwap; if(NotEnoughToken){ if(ignoreLimits) tokenToSwap=contractBalance; else return; } //splits the token in TokenForLiquidity and tokenForMarketing uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax; uint256 tokenForMarketing= tokenToSwap-tokenForLiquidity; //splits tokenForLiquidity in 2 halves uint256 liqToken=tokenForLiquidity/2; uint256 liqETHToken=tokenForLiquidity-liqToken; //swaps marktetingToken and the liquidity token half for ETH uint256 swapToken=liqETHToken+tokenForMarketing; //Gets the initial ETH balance, so swap will not touch any staked ETH uint256 initialETHBalance = address(this).balance; _swapTokenForETH(swapToken); uint256 newETH=(address(this).balance - initialETHBalance); //calculates the amount of ETH belonging to the LP-Pair and converts them to LP uint256 liqETH = (newETH*liqETHToken)/swapToken; _addLiquidity(liqToken, liqETH); //Get the ETH balance after LP generation to get the //exact amount of token left for Staking uint256 distributeETH=(address(this).balance - initialETHBalance); //distributes remaining ETH between stakers and Marketing _distributeStake(distributeETH,true); } //swaps tokens on the contract for ETH function _swapTokenForETH(uint256 amount) private { _approve(address(this), address(_uniswapRouter), amount); address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapRouter.WETH(); _uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), block.timestamp ); } //Adds Liquidity directly to the contract where LP are locked function _addLiquidity(uint256 tokenamount, uint256 ETHamount) private { totalLPETH+=ETHamount; _approve(address(this), address(_uniswapRouter), tokenamount); _uniswapRouter.addLiquidityETH{value: ETHamount}( address(this), tokenamount, 0, 0, address(this), block.timestamp ); } //////////////////////////////////////////// Public functions /////////////////////////////////////////// function getLiquidityReleaseTimeInSeconds() public view returns (uint256){ if(block.timestamp<_liquidityUnlockTime){ return _liquidityUnlockTime-block.timestamp; } return 0; } function getLimits() public view returns(uint256 balance, uint256 sell){ return(balanceLimit/10, sellLimit/10); } function getTaxes() public view returns(uint256 liquidityTax,uint256 marketingTax, uint256 buyTax, uint256 sellTax, uint256 transferTax){ if(_botProtection) buyTax=_calculateLaunchTax(); else buyTax= _buyTax; return (_liquidityTax,_stakingTax,buyTax,_sellTax,_transferTax); } function getWhitelistedStatus(address AddressToCheck) public view returns(bool){ return _whiteList.contains(AddressToCheck); } function isPlatinumHolder(address AddressToCheck) public view returns(bool){ return !_NoPlatinumHolder[AddressToCheck]; } //How long is a given address still locked from selling function getAddressSellLockTimeInSeconds(address AddressToCheck) public view returns (uint256){ uint256 lockTime=_sellLock[AddressToCheck]; if(lockTime<=block.timestamp){ return 0; } return lockTime-block.timestamp; } function getSellLockTimeInSeconds() public view returns(uint256){ return sellLockTime; } bool allowTaxFreeCompound=true; function TeamSetPlatinumHolderTaxFree(bool taxFree) public onlyTeam{ allowTaxFreeCompound=taxFree; } //withdraws dividents of sender function ClaimETH() public { claimToken(msg.sender ,address(this),0); } function MBall() public{ if(allowTaxFreeCompound) oneTimeExcluded=msg.sender; MballToken(msg.sender,address(this),0); } function getDividents(address addr) private view returns (uint256){ if(isExcludedFromStaking(addr)) return toBePaid[addr]; return _newDividentsOf(addr)+toBePaid[addr]; } function getDividentsOf(address addr) public view returns (uint256){ uint256 amount=getDividents(addr); if(noPlatinumHolderFeeOn&&_NoPlatinumHolder[addr]) amount-=amount*noPlatinumHolderFeePercent/100; return amount; } ////////////////////////////////////////// Settings //////////////////////////////////// bool public sellLockDisabled; uint256 public sellLockTime; bool public manualConversion; uint16 public AutoLPThreshold=50; function TeamSetAutoLPThreshold(uint16 threshold) public onlyTeam{ require(threshold>0,"threshold needs to be more than 0"); require(threshold<=50,"threshold needs to be below 50"); AutoLPThreshold=threshold; } //Excludes account from Staking total function TeamExcludeFromStaking(address addr) public onlyTeam{ require(!isExcludedFromStaking(addr)); _totalShares-=_balances[addr]; uint256 newDividents=_newDividentsOf(addr); alreadyPaidShares[addr]=_balances[addr]*profitPerShare; toBePaid[addr]+=newDividents; _excludedFromStaking.add(addr); } //Includes excluded Account to staking function TeamIncludeToStaking(address addr) public onlyTeam{ require(isExcludedFromStaking(addr)); _totalShares+=_balances[addr]; _excludedFromStaking.remove(addr); //sets alreadyPaidShares to the current amount alreadyPaidShares[addr]=_balances[addr]*profitPerShare; } function TeamWithdrawMarketingETH() public onlyTeam{ uint256 amount=marketingBalance; marketingBalance=0; (bool sent,) =TeamWallet.call{value: (amount)}(""); require(sent,"withdraw failed"); } function TeamWithdrawMarketingETH(uint256 amount) public onlyTeam{ require(amount<=marketingBalance); marketingBalance-=amount; (bool sent,) =TeamWallet.call{value: (amount)}(""); require(sent,"withdraw failed"); } //switches autoLiquidity and marketing ETH generation during transfers function TeamSwitchManualETHConversion(bool manual) public onlyTeam{ manualConversion=manual; } //Sets SellLockTime, needs to be lower than MaxSellLockTime function TeamSetSellLockTime(uint256 sellLockSeconds)public onlyTeam{ require(sellLockSeconds<=MaxSellLockTime,"Sell Lock time too high"); sellLockTime=sellLockSeconds; } //Sets Taxes, is limited by MaxTax(20%) to make it impossible to create honeypot function TeamSetTaxes(uint8 liquidityTaxes, uint8 stakingTaxes,uint8 buyTax, uint8 sellTax, uint8 transferTax) public onlyTeam{ uint8 totalTax=liquidityTaxes+stakingTaxes; require(totalTax==100, "liq+staking needs to equal 100%"); require(buyTax<=MaxTax&&sellTax<=MaxTax,"taxes higher than max tax"); require(transferTax<=50,"transferTax higher than max transferTax"); _liquidityTax=liquidityTaxes; _stakingTax=stakingTaxes; _buyTax=buyTax; _sellTax=sellTax; _transferTax=transferTax; } //How much of the staking tax should be allocated for marketing function TeamChangeMarketingShare(uint8 newShare) public onlyTeam{ require(newShare<=50); marketingShare=newShare; } //manually converts contract token to LP and staking ETH function TeamCreateLPandETH(uint16 PermilleOfuniswap, bool ignoreLimits) public onlyTeam{ _swapContractToken(PermilleOfuniswap, ignoreLimits); } //Exclude/Include account from fees (eg. CEX) function TeamExcludeAccountFromFees(address account) public onlyTeam { _excluded.add(account); } function TeamIncludeAccountToFees(address account) public onlyTeam { _excluded.remove(account); } //Exclude/Include account from fees (eg. CEX) function TeamExcludeAccountFromSellLock(address account) public onlyTeam { _excludedFromSellLock.add(account); } function TeamIncludeAccountToSellLock(address account) public onlyTeam { _excludedFromSellLock.remove(account); } //Limits need to be at least target, to avoid setting value to 0 function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyTeam{ //Calculates the target Limits based on supply uint256 targetBalanceLimit=_totalSupply/BalanceLimitDivider; uint256 targetSellLimit=_totalSupply/SellLimitDivider; require((newBalanceLimit>=targetBalanceLimit), "newBalanceLimit needs to be at least target"); require((newSellLimit>=targetSellLimit), "newSellLimit needs to be at least target"); balanceLimit = newBalanceLimit; sellLimit = newSellLimit; } event OnSwitchSellLock(bool disabled); //Disables the timeLock after selling for everyone function TeamDisableSellLock(bool disabled) public onlyTeam{ sellLockDisabled=disabled; emit OnSwitchSellLock(disabled); } ///////////////////////////////////// Setup Functions ////////////////////////////////////// function SetupCreateLP(uint8 TeamTokenPercent) public payable onlyTeam{ require(IERC20(_uniswapPairAddress).totalSupply()==0,"There are alreadyLP"); uint256 Token=_balances[address(this)]; uint256 TeamToken=Token*TeamTokenPercent/100; uint256 LPToken=Token-TeamToken; _removeToken(address(this),TeamToken); _addToken(msg.sender, TeamToken); emit Transfer(address(this), msg.sender, TeamToken); _addLiquidity(LPToken, msg.value); } bool public tradingEnabled; //Enables trading for everyone function SetupEnableTrading(bool BotProtection) public onlyTeam{ require(IERC20(_uniswapPairAddress).totalSupply()>0,"there are no LP"); require(!tradingEnabled); tradingEnabled=true; _botProtection=BotProtection; launchTimestamp=block.timestamp; //Liquidity gets locked for 7 days at start, needs to be prolonged once //start is successful _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; } function SetupAddOrRemoveWhitelist(address[] memory addresses,bool Add) public onlyTeam{ for(uint i=0; i<addresses.length; i++){ if(Add) _whiteList.add(addresses[i]); else _whiteList.remove(addresses[i]); } } /////////////////////////////////////// Liquidity Lock ////////////////////////////////////////// //the timestamp when Liquidity unlocks uint256 private _liquidityUnlockTime; //Sets Liquidity Release to 20% at a time and prolongs liquidity Lock for a Week after Release. //Should be called once start was successful. bool public liquidityRelease20Percent; function TeamlimitLiquidityReleaseTo20Percent() public onlyTeam{ liquidityRelease20Percent=true; } function TeamUnlockLiquidityInSeconds(uint256 secondsUntilUnlock) public onlyTeam{ _prolongLiquidityLock(secondsUntilUnlock+block.timestamp); } function _prolongLiquidityLock(uint256 newUnlockTime) private{ // require new unlock time to be longer than old one require(newUnlockTime>_liquidityUnlockTime); _liquidityUnlockTime=newUnlockTime; } //Release Liquidity Tokens once unlock time is over function TeamReleaseLiquidity() public onlyTeam { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); IuniswapERC20 liquidityToken = IuniswapERC20(_uniswapPairAddress); uint256 amount = liquidityToken.balanceOf(address(this)); if(liquidityRelease20Percent) { _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; //regular liquidity release, only releases 20% at a time and locks liquidity for another week amount=amount*2/10; liquidityToken.transfer(TeamWallet, amount); } else { //Liquidity release if something goes wrong at start //liquidityRelease20Percent should be called once everything is clear liquidityToken.transfer(TeamWallet, amount); } } //Removes Liquidity once unlock Time is over, function TeamRemoveLiquidity(bool addToStaking) public onlyTeam { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; IuniswapERC20 liquidityToken = IuniswapERC20(_uniswapPairAddress); uint256 amount = liquidityToken.balanceOf(address(this)); if(liquidityRelease20Percent){ amount=amount*2/10; //only remove 20% each } liquidityToken.approve(address(_uniswapRouter),amount); //Removes Liquidity and either distributes liquidity ETH to stakers, or // adds them to marketing Balance //Token will be converted //to Liquidity and Staking ETH again uint256 initialETHBalance = address(this).balance; _uniswapRouter.removeLiquidityETHSupportingFeeOnTransferTokens( address(this), amount, 0, 0, address(this), block.timestamp ); uint256 newETHBalance = address(this).balance-initialETHBalance; if(addToStaking){ _distributeStake(newETHBalance,true); } else{ marketingBalance+=newETHBalance; } } //Releases all remaining ETH on the contract wallet, so ETH wont be burned //Can only be called 30 days after Liquidity unlocks function TeamRemoveRemainingETH() public onlyTeam{ require(block.timestamp >= _liquidityUnlockTime+30 days, "Not yet unlocked"); _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; (bool sent,) =TeamWallet.call{value: (address(this).balance)}(""); require(sent); } function RescueStrandedToken(address tokenAddress) public onlyTeam{ require(tokenAddress!=_uniswapPairAddress&&tokenAddress!=address(this),"can't Rescue LP token or this token"); IERC20 token=IERC20(tokenAddress); token.transfer(msg.sender,token.balanceOf(address(this))); } /////////////////////////////////////////// External ///////////////////////////////////////////////// receive() external payable {} fallback() external payable {} // IERC20 function getOwner() external view override returns (address) { return owner(); } function name() external pure override returns (string memory) { return _name; } function symbol() external pure override returns (string memory) { return _symbol; } function decimals() external pure override returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _totalSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address _owner, address spender) external view override returns (uint256) { return _allowances[_owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "Approve from zero"); require(spender != address(0), "Approve to zero"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "Transfer > allowance"); _approve(sender, msg.sender, currentAllowance - amount); return true; } // IERC20 - Helpers function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "<0 allowance"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } }
withdraws dividents of sender
function ClaimETH() public { claimToken(msg.sender ,address(this),0); }
14,526,631
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {OracleInterface} from "./opyn/interfaces/OracleInterface.sol"; import {OpynPricerInterface} from "./opyn/interfaces/OpynPricerInterface.sol"; /// @title Better Oracle /// @author Amethyst C. /// @notice Better Oracle pulls data from more than one source and uses a weighted average to calculate the expiration price /// @dev Pulls data from pricers utilizing the OpynPricerInterface contract BetterOracle { error ZeroAddress(); error Unauthorized_Bot(); error Unauthorized_Admin(); error PricerDoesNotExist(); error WeightOutOfBounds(); /// @dev Struct that stores info for the Pricer /// Weight can be used to determine the "trust" level struct Pricer { address source; uint16 weight; uint8 decimalsOfPrecision; } /// @dev Struct that stores price of an asset and timestamp of when it was recorded /// Adapted from GammaProtocol/contracts/Oracle.sol struct Price { uint256 price; uint256 timestamp; Pricer source; // Source of the price data } /// @dev Permissioned addresses to pull price data from /// (key = asset) -> (value = pricers) mapping(address => Pricer[]) internal pricers; /// @dev Pricer to price data mapping(address => Price) internal prices; /// @dev Permissioned addresses to allow to call functions mapping(address => bool) internal bots; /// @dev Tolerable weight deviation in % (measured w/ 2 decimals [100.xx]) uint16 private tolerableWeightDeviation; /// @dev Opyn v2's oracle to submit price data to OracleInterface private opynOracle; /// @dev The admin can represent any multi-sig wallet capable of producing calls to the contract address private admin; event PricerAdded(address asset, address pricer, uint16 trust); event PricerRemoved(address asset, address pricer); event PricerWeightChanged(address pricer, uint16 weight); event BotAdded(address bot); event BotRemoved(address bot); event PushedData(address asset, uint256 price); event AdminChanged(address newAdmin); constructor(address _admin, address _opynOracle, uint16 _tolerableWeightDeviation) { admin = _admin; // Make sure admin is a multi-sig wallet! opynOracle = OracleInterface(_opynOracle); tolerableWeightDeviation = _tolerableWeightDeviation; } modifier onlyBot { _onlyBot(); _; } modifier onlyAdmin { _onlyAdmin(); _; } /** * @notice Add a pricer * @param _asset asset's address * @param _pricer pricer's address */ function addPricer( address _asset, address _pricer, uint16 _weight ) external onlyAdmin { Pricer memory newPricer; newPricer.source = _pricer; newPricer.weight = _weight; pricers[_asset].push(newPricer); emit PricerAdded(_asset, _pricer, _weight); } /** * @notice Remove a pricer * @param _asset asset's address * @param _pricer pricer's address */ function removePricer(address _asset, address _pricer) external onlyAdmin { delete pricers[_asset]; emit PricerRemoved(_asset, _pricer); } function changePricerWeight(address _asset, uint16 _newWeight) external onlyAdmin { } /** * @notice Adds a bot * @param _bot bot's address */ function addBot(address _bot) external onlyAdmin { bots[_bot] = true; emit BotAdded(_bot); } /** * @notice Removes a bot * @param _bot bot's address */ function removeBot(address _bot) external onlyAdmin { bots[_bot] = false; emit BotRemoved(_bot); } /** * @notice Change the Opyn oracle's address * @param _newOracle new oracle's address for Opyn v2 */ function changeOpynOracle(address _newOracle) external onlyAdmin { if(_newOracle == address(0)) revert ZeroAddress(); opynOracle = OracleInterface(_newOracle); } /** * @notice Change the contract's admin * @param _newAdmin new admin's address */ function changeAdmin(address _newAdmin) external onlyAdmin { if(_newAdmin == address(0)) revert ZeroAddress(); admin = _newAdmin; } /** (??????) * @notice Prepare the pricer data for the asset * @param _asset is the asset's address */ function prepareData(address _asset) external onlyBot { Pricer[] storage assetPricers = pricers[_asset]; if(assetPricers.length == 0) revert PricerDoesNotExist(); } function pushData(address _asset, uint256 _expiryTimestamp, bool _ignoreOutOfBounds) external onlyBot { if(pricers[_asset].length == 0) revert PricerDoesNotExist(); uint256 _weightedPrice = _calculateWeightedAverage(_asset, _ignoreOutOfBounds); opynOracle.setExpiryPrice(_asset, _expiryTimestamp, _weightedPrice); emit PushedData(_asset, _weightedPrice); } function _onlyBot() internal view { if(!bots[msg.sender]) revert Unauthorized_Bot(); } function _onlyAdmin() internal view { if(msg.sender != admin) revert Unauthorized_Admin(); } function _calculateWeightedAverage(address _asset, bool _ignoreOutOfBounds) internal view returns (uint256 weightedPrice) { uint256 totalPricers = pricers[_asset].length; // Check if there is even a pricer available if(totalPricers == 0) revert PricerDoesNotExist(); // Continue preparing variables uint256 maxDecimalsOfPrecision; uint16 totalWeight; bool missingPricer; Pricer[] memory assetPricers = pricers[_asset]; Price[] memory assetPrices = new Price[](totalPricers); // Check if the pricer was called recently, otherwise remove it from the calculation for (uint256 i; i < assetPricers.length; i++) { if ( prices[assetPricers[i].source].timestamp <= block.timestamp - 15 minutes && !missingPricer ) { missingPricer = true; continue; } else if (prices[assetPricers[i].source].timestamp != 0) { assetPrices[i] = prices[assetPricers[i].source]; totalWeight += assetPricers[i].weight; if(assetPricers[i].decimalsOfPrecision > maxDecimalsOfPrecision) maxDecimalsOfPrecision = assetPricers[i].decimalsOfPrecision; } } // Verify weights (bool _tolerated, bool _outOfBounds) = _weightDeviationToleranceCheck(totalWeight); if(_outOfBounds && !_ignoreOutOfBounds) revert WeightOutOfBounds(); if (_tolerated) { if (missingPricer) assetPricers = _reweighPricer(assetPricers, 0); else assetPricers = _reweighPricer(assetPricers, 1); } // Multiply to get the weighted average for (uint256 i; i < assetPrices.length; i++) { if (assetPrices[i].price != 0) { weightedPrice += _normalize(assetPrices[i].price, assetPrices[i].source.decimalsOfPrecision, maxDecimalsOfPrecision) * assetPrices[i].source.weight / 10000; } } } function _reweighPricer(Pricer[] memory _pricersToReweigh, uint256 _type) internal pure returns (Pricer[] memory) { if (_type == 0) { // Reweigh due to missing pricer uint16 currentWeightVal; uint256 indexCount; uint16[] memory indexOfValidPricers = new uint16[](_pricersToReweigh.length); for (uint256 i; i < _pricersToReweigh.length; i++) { if (_pricersToReweigh[i].source != address(0)) { indexOfValidPricers[indexCount++] = uint16(i); currentWeightVal += _pricersToReweigh[i].weight; } } for (uint16 i; i < indexOfValidPricers.length; i++) { _pricersToReweigh[i].weight /= currentWeightVal; } } else if (_type == 1) { // Reweigh to equalize for (uint256 i; i < _pricersToReweigh.length; i++) { _pricersToReweigh[i].weight /= uint16(_pricersToReweigh.length); } } return _pricersToReweigh; } function _normalize( uint256 _valueToNormalize, uint256 _valueDecimal, uint256 _normalDecimals ) internal pure returns (uint256) { int256 decimalDiff = int256(_valueDecimal) - int256(_normalDecimals); if(decimalDiff > 0) { return _valueToNormalize / (10**uint256(decimalDiff)); } else if(decimalDiff < 0) { return _valueToNormalize * 10**uint256(-decimalDiff); } else { return _valueToNormalize; } } /** * @notice Verify the weights did not deviate too far or is out of bounds * @param _totalWeightValues total value of the weight * @return safeDeviation is true if out of bounds is false and did not deviate too far from the tolerable weight deviation * @return outOfBounds is true if it is above 10000 (100.00) */ function _weightDeviationToleranceCheck(uint16 _totalWeightValues) internal view returns (bool safeDeviation, bool outOfBounds) { if(_totalWeightValues <= 10000) { outOfBounds = true; } if(10000 - _totalWeightValues <= tolerableWeightDeviation) { safeDeviation = true; } } /** * @notice Return an absolute value */ function _abs(int256 _val) internal pure returns(int256) { return _val >= 0 ? _val: -_val; } }
Add a pricer _asset asset's address _pricer pricer's address/
function addPricer( address _asset, address _pricer, uint16 _weight ) external onlyAdmin { Pricer memory newPricer; newPricer.source = _pricer; newPricer.weight = _weight; pricers[_asset].push(newPricer); emit PricerAdded(_asset, _pricer, _weight); }
12,872,873
pragma solidity ^0.5.17; // solhint-disable-next-line compiler-version /** * @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. */ 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) { // 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } library Hasher { function poseidon(uint256[] memory inputs) public pure returns (uint256 result); } contract MerkleTreeWithHistory is Initializable { // The compiler does not reserve a storage slot for constant variables, the optimiser will replace every occurrence // of the constant variables in the compiling process. Hence it is okay to initialize these variables here, even // this is an upgradable contract uint256 public constant FIELD_SIZE = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 public constant ZERO_VALUE = 21663839004416932945382355908790599225266501822907911457504978515578255421292; uint32 public constant ROOT_HISTORY_SIZE = 100; uint32 public levels; // the following variables are made public for easier testing and debugging and // are not supposed to be accessed in regular code bytes32[] public filledSubtrees; bytes32[] public zeros; uint32 public currentRootIndex; uint32 public nextIndex; bytes32[ROOT_HISTORY_SIZE] public roots; // this tree stores two roots bytes32 public rewardCurrentRoot; uint32 public rewardCurrentBlocknum; bytes32 public rewardNextRoot; uint32 public rewardNextBlocknum; // rewardRoot|--------blockcount-------|nextRewardRoot|----| uint32 public blockCount; event RewardUpdate(uint32 updateAtBlock, bytes32 newRewardRoot); event BlockCountUpdate(uint32 blockCount); // DO NOT implement a constructor because this is an upgradable logic. // Use the initialize function as a constructor. constructor() public {} /** * @dev The initializer */ function _initialize(uint32 _treeLevels, uint32 _blockCount) internal initializer { require(_treeLevels > 0, "_treeLevels should be greater than zero"); require(_treeLevels < 32, "_treeLevels should be less than 32"); levels = _treeLevels; // new blockCount = _blockCount; bytes32 currentZero = bytes32(ZERO_VALUE); zeros.push(currentZero); filledSubtrees.push(currentZero); for (uint32 i = 1; i < levels; i++) { currentZero = hashLeftRight(currentZero, currentZero); zeros.push(currentZero); filledSubtrees.push(currentZero); } roots[0] = hashLeftRight(currentZero, currentZero); // rewardCurrentRoot = roots[0]; rewardCurrentBlocknum = uint32(block.number); rewardNextRoot = roots[0]; rewardNextBlocknum = uint32(block.number); } function _setBlockCount(uint32 _blockCount) internal { blockCount = _blockCount; emit BlockCountUpdate(blockCount); } // poseidon function hashLeftRight(bytes32 _left, bytes32 _right) public pure returns (bytes32) { uint256[] memory inputs = new uint256[](2); inputs[0] = uint256(_left); inputs[1] = uint256(_right); uint256 output = Hasher.poseidon(inputs); return bytes32(output); } function _insert(bytes32 _leaf) internal returns (uint32 index) { uint32 currentIndex = nextIndex; require( currentIndex != uint32(2)**levels, "Merkle tree is full. No more leafs can be added" ); nextIndex += 1; bytes32 currentLevelHash = _leaf; bytes32 left; bytes32 right; for (uint32 i = 0; i < levels; i++) { if (currentIndex % 2 == 0) { left = currentLevelHash; right = zeros[i]; filledSubtrees[i] = currentLevelHash; } else { left = filledSubtrees[i]; right = currentLevelHash; } currentLevelHash = hashLeftRight(left, right); currentIndex /= 2; } currentRootIndex = (currentRootIndex + 1) % ROOT_HISTORY_SIZE; roots[currentRootIndex] = currentLevelHash; // update roots if ((uint32(block.number) - rewardNextBlocknum) >= blockCount) { rewardCurrentRoot = rewardNextRoot; rewardNextRoot = currentLevelHash; // current tree root rewardCurrentBlocknum = rewardNextBlocknum; rewardNextBlocknum = uint32(block.number); emit RewardUpdate(rewardCurrentBlocknum, rewardCurrentRoot); } return nextIndex - 1; } /** @dev Whether the root is present in the root history */ function isKnownRoot(bytes32 _root) public view returns (bool) { if (_root == 0) { return false; } uint32 i = currentRootIndex; do { if (_root == roots[i]) { return true; } if (i == 0) { i = ROOT_HISTORY_SIZE; } i--; } while (i != currentRootIndex); return false; } // function isRewardRoot(bytes32 _rroot) public view returns (bool) { if (_rroot == 0) { return false; } if (_rroot == rewardCurrentRoot) { return true; } return false; } /** @dev Returns the last root */ function getLastRoot() public view returns (bytes32) { return roots[currentRootIndex]; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract UpgradableReentrancyGuard { // modified from _notEntered to _entered, to make lifer easier for upgrading contracts. bool private _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(!_entered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _entered = true; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _entered = false; } } interface WVerifier { function verifyProof(bytes calldata _proof, uint256[7] calldata _input) external returns (bool); } interface RVerifier { function verifyProof(bytes calldata _proof, uint256[6] calldata _input) external returns (bool); } contract BlenderCore is MerkleTreeWithHistory, UpgradableReentrancyGuard { // Amount of deposit uint256 public d_denomination; // Amount of reward uint256 public r_denomination; // Withdraw nullifier list mapping(bytes32 => bool) public nullifierHashes; // Reward nullifier list mapping(bytes32 => bool) public rewardNullifierHashes; // Commitments mapping(bytes32 => bool) public commitments; // withdraw Verifier WVerifier public withdrawVerifier; // reward verifier RVerifier public rewardVerifier; // reward counter uint32 public rewardCounter; // operator can update snark verification key // after the final trusted setup ceremony operator rights are supposed to be transferred to zero address address public operator; modifier onlyOperator { require( msg.sender == operator, "Only operator can call this function." ); _; } // relayer whitelisting bool public relayerWhitelistingEnabled; mapping(address => bool) public relayerWhitelist; modifier onlyWhitelistedRelayer(address _relayer) { if (relayerWhitelistingEnabled) { require(relayerWhitelist[_relayer], "Not a whitelisted relayer"); } _; } address public blnd; uint256 public firstStageReward; uint256 public secondStageReward; uint256 public thirdStageReward; uint256 public firstStageDepositors; uint256 public secondStageDepositors; event Deposit( bytes32 indexed commitment, uint32 leafIndex, uint256 timestamp ); event Reward( address to, bytes32 rewardNullifierHash, address indexed relayer, uint256 fee ); event Withdrawal( address to, bytes32 withdrawNullifierHash, bytes32 rewardNullifierHash, address indexed relayer, uint256 fee ); event rewardUpdate(uint256 r_denomination, uint32 leafIndex); event RelayerUpdate(address relayer, bool permitted); // DO NOT implement a constructor because this is an upgradable logic. // Use the initialize function as a constructor. constructor() public {} /** * @dev The initializer * @param _withdrawVerifier the address of SNARK verifier for this contract * @param _rewardVerifier the address of SNARK verifier for this contract * @param _d_denomination transfer amount for each deposit * @param _merkleTreeHeight the height of deposits Merkle Tree * @param _operator operator address (see operator comment above) */ function _initialize( WVerifier _withdrawVerifier, // withdraw verifier RVerifier _rewardVerifier, // reward verifier uint256 _d_denomination, uint32 _merkleTreeHeight, uint32 _blockCount, address _operator, address _blnd, uint256 _firstStageReward, uint256 _secondStageReward, uint256 _thirdStageReward, uint256 _firstStageDepositors, uint256 _secondStageDepositors ) internal initializer { // call the initialize function of the parent contract (the constructor of the parent contract) MerkleTreeWithHistory._initialize(_merkleTreeHeight, _blockCount); // constructor logic require( _d_denomination > 0, "Deposit denomination should be greater than 0" ); firstStageReward = _firstStageReward; secondStageReward = _secondStageReward; thirdStageReward = _thirdStageReward; firstStageDepositors = _firstStageDepositors; secondStageDepositors = _secondStageDepositors; withdrawVerifier = _withdrawVerifier; rewardVerifier = _rewardVerifier; operator = _operator; d_denomination = _d_denomination; r_denomination = firstStageReward; blnd = _blnd; } // Should be unchanged /** @dev Deposit funds into the contract. The caller must send (for ETH) or approve (for ERC20) value equal to or `denomination` of this instance. @param _commitment the note commitment, which is PedersenHash(nullifier + secret) */ function deposit(bytes32 _commitment) external payable nonReentrant { require(!commitments[_commitment], "The commitment has been submitted"); uint32 insertedIndex = _insert(_commitment); commitments[_commitment] = true; _processDeposit(); emit Deposit(_commitment, insertedIndex, block.timestamp); } /** @dev this function is defined in a child contract */ function _processDeposit() internal; /** @dev Withdraw a deposit from the contract. `proof` is a zkSNARK proof data, and input is an array of circuit public inputs `input` array consists of: - merkle root of all deposits in the contract - hash of unique deposit nullifier to prevent double spends - the recipient of funds - optional fee that goes to the transaction sender (usually a relay) */ function withdraw( bytes calldata _proof, bytes32 _root, bytes32 _wdrHash, bytes32 _rwdHash, address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund ) external payable nonReentrant onlyWhitelistedRelayer(_relayer) { require(_fee <= d_denomination, "Fee exceeds transfer value"); require( !nullifierHashes[_wdrHash], "The withdraw note has been already spent for withdrawing" ); require( !nullifierHashes[_rwdHash], "The reward note has been already spent for withdrawing" ); require(isKnownRoot(_root), "Cannot find your merkle root"); // Make sure to use a recent one require( withdrawVerifier.verifyProof( _proof, [ uint256(_root), uint256(_wdrHash), uint256(_rwdHash), uint256(_recipient), uint256(_relayer), _fee, _refund ] ), "Invalid withdraw proof" ); nullifierHashes[_wdrHash] = true; // nullifierHashes[_rwdHash] = true; // rewardNullifierHashes[_rwdHash] = true; // cannot obtain reward using this hash anymore _processWithdraw(_recipient, _relayer, _fee, _refund); emit Withdrawal(_recipient, _wdrHash, _rwdHash, _relayer, _fee); } function reward( bytes calldata _rproof, bytes32 _rroot, bytes32 _rwdHash, address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund ) external payable nonReentrant onlyWhitelistedRelayer(_relayer) { require(_fee <= r_denomination, "Fee exceeds transfer value"); require( !rewardNullifierHashes[_rwdHash], "The reward note has been already redeemed" ); require(isRewardRoot(_rroot), "Cannot find your merkle root"); // Make sure to use a recent one require( rewardVerifier.verifyProof( _rproof, [ uint256(_rroot), uint256(_rwdHash), uint256(_recipient), uint256(_relayer), _fee, _refund ] ), "Invalid reward proof" ); // update reward at certain checkpoints if (rewardCounter == firstStageDepositors) { r_denomination = secondStageReward; emit rewardUpdate(r_denomination, rewardCounter); } if (rewardCounter == secondStageDepositors) { r_denomination = thirdStageReward; emit rewardUpdate(r_denomination, rewardCounter); } // cannot obtain reward using this hash anymore rewardNullifierHashes[_rwdHash] = true; _processReward(_recipient, _relayer, _fee, _refund); rewardCounter = rewardCounter + 1; emit Reward(_recipient, _rwdHash, _relayer, _fee); } /** @dev this function is defined in a child contract */ function _processWithdraw( address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund ) internal; function _processReward( address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund ) internal { require( msg.value == _refund, "Incorrect refund amount received by the contract" ); SafeERC20.safeTransfer(IERC20(blnd), _recipient, r_denomination - _fee); if (_fee > 0) { SafeERC20.safeTransfer(IERC20(blnd), _relayer, _fee); } // to prevent attacker from burning relayer eth in fee if (_refund > 0) { (bool success, ) = _recipient.call.value(_refund)(""); if (!success) { _relayer.transfer(_refund); } } } /** @dev whether a note is already spent */ // TODO blnd may need to verify two nullifier hashes is needed function isSpent(bytes32 _wdrHash) public view returns (bool) { return nullifierHashes[_wdrHash]; } function isRedeem(bytes32 _rwdHash) public view returns (bool) { return rewardNullifierHashes[_rwdHash]; } /** @dev whether an array of notes is already spent */ function isSpentArray(bytes32[] calldata _nullifierHashes) external view returns (bool[] memory spent) { spent = new bool[](_nullifierHashes.length); for (uint256 i = 0; i < _nullifierHashes.length; i++) { if (isSpent(_nullifierHashes[i])) { spent[i] = true; } } } /** @dev whether an array of notes is already spent */ function isRedeemArray(bytes32[] calldata _nullifierHashes) external view returns (bool[] memory redeem) { redeem = new bool[](_nullifierHashes.length); for (uint256 i = 0; i < _nullifierHashes.length; i++) { if (isRedeem(_nullifierHashes[i])) { redeem[i] = true; } } } /** @dev allow operator to update SNARK verification keys. This is needed to update keys after the final trusted setup ceremony is held. After that operator rights are supposed to be transferred to zero address */ // update withdraw verifier function updateWithdrawVerifier(address _newVerifier) external onlyOperator { withdrawVerifier = WVerifier(_newVerifier); } // update reward verifier function updateRewardVerifier(address _newVerifier) external onlyOperator { rewardVerifier = RVerifier(_newVerifier); } /** @dev operator can change his address */ function changeOperator(address _newOperator) external onlyOperator { operator = _newOperator; } /** * @dev operator can enable relayer whitelisting */ function enableRelayerWhitelisting() external onlyOperator nonReentrant { relayerWhitelistingEnabled = true; } /** * @dev operator can disable relayer whitelisting */ function disableRelayerWhitelisting() external onlyOperator nonReentrant { relayerWhitelistingEnabled = false; } /** * @dev operator can add a relayer to the whitelist. */ function addRelayer(address _relayer) external onlyOperator nonReentrant { relayerWhitelist[_relayer] = true; emit RelayerUpdate(_relayer, relayerWhitelist[_relayer]); } /** * @dev operator can remove a relayer from the whitelist. */ function removeRelayer(address _relayer) external onlyOperator nonReentrant { relayerWhitelist[_relayer] = false; emit RelayerUpdate(_relayer, relayerWhitelist[_relayer]); } /** * @dev operator can change the number of blocks between the current and next reward roots */ function setBlockCount(uint32 _blockCount) external onlyOperator nonReentrant { _setBlockCount(_blockCount); } } interface AToken { function balanceOf(address _user) external view returns (uint256); function redeem(uint256 _amount) external; } interface ALendingPool { function deposit( address _reserve, uint256 _amount, uint16 _referralCode ) external payable; } interface ALendingPoolAddressesProvider { function getLendingPool() external view returns (address); } contract AETHBlender is Initializable, BlenderCore { ALendingPoolAddressesProvider public lendingPoolAddressesProvider; AToken public aToken; address public reserve; uint256 public depositors; // DO NOT implement a constructor because this is an upgradable logic. // Use the initialize function as a constructor. constructor() public {} function initialize( WVerifier _withdrawVerifier, RVerifier _rewardVerifier, uint256 _d_denomination, uint32 _merkleTreeHeight, uint32 _blockCount, address _operator, address _blnd, address _aToken, address _reserve, uint256 _firstStageReward, uint256 _secondStageReward, uint256 _thirdStageReward, uint256 _firstStageDepositors, uint256 _secondStageDepositors ) public { // call the initialize function of the parent contract (the constructor of the parent contract) BlenderCore._initialize( _withdrawVerifier, _rewardVerifier, _d_denomination, _merkleTreeHeight, _blockCount, _operator, _blnd, _firstStageReward, _secondStageReward, _thirdStageReward, _firstStageDepositors, _secondStageDepositors ); // constructor logic lendingPoolAddressesProvider = ALendingPoolAddressesProvider( 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8 ); aToken = AToken(_aToken); reserve = _reserve; } function _processDeposit() internal { require( msg.value == d_denomination, "Please send `mixDenomination` ETH along with transaction" ); // Deposit all the balance uint256 balance = address(this).balance; ALendingPool(lendingPoolAddressesProvider.getLendingPool()) .deposit .value(balance)(reserve, balance, 0); depositors++; } function _processWithdraw( address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund ) internal { require( msg.value == 0, "Message value is supposed to be zero for ETH instance" ); require( _refund == 0, "Refund value is supposed to be zero for ETH instance" ); require(depositors > 0, "Number of depositors must be positive"); uint256 beforeBalance = address(this).balance; uint256 aBalance = aToken.balanceOf(address(this)); uint256 redeemAmount = SafeMath.div(aBalance, depositors); aToken.redeem(redeemAmount); uint256 afterBalance = address(this).balance; uint256 redeemedAmount = SafeMath.sub(afterBalance, beforeBalance); (bool success, ) = _recipient.call.value(redeemedAmount - _fee)(""); require(success, "payment to _recipient did not go thru"); if (_fee > 0) { (success, ) = _relayer.call.value(_fee)(""); require(success, "payment to _relayer did not go thru"); } depositors--; } function() external payable {} }
operator can add a relayer to the whitelist./
function addRelayer(address _relayer) external onlyOperator nonReentrant { relayerWhitelist[_relayer] = true; emit RelayerUpdate(_relayer, relayerWhitelist[_relayer]); }
6,782,027
./partial_match/3/0x7659D781dD67018828b1F0b7147326B6638C45e1/sources/RamenToken.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "RAMEN::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
5,262,261
./full_match/97/0x24791e69e9227d3789107D01F9424D9A2E959ABa/sources/project_/contracts/strf-token-staker/STRFStaker.sol
Total withdrawable staked/stakedAndLocked/staked+stakedAndLocked balance for an account.
function withdrawableBalance(address user, bool staked, bool stakedAndLocked) view public returns (uint256 amount) { if (staked) { amount += balances[user].staked; } if (stakedAndLocked) { LockedBalance[] storage locks = userLocks[user]; for (uint i = 0; i < locks.length; i++) { if (locks[i].unlockTime > getCurrentTime()) { break; } amount += locks[i].amount; } } return amount; if (stakedAndLocked) { LockedBalance[] storage locks = userLocks[user]; for (uint i = 0; i < locks.length; i++) { if (locks[i].unlockTime > getCurrentTime()) { break; } amount += locks[i].amount; } } return amount; if (stakedAndLocked) { LockedBalance[] storage locks = userLocks[user]; for (uint i = 0; i < locks.length; i++) { if (locks[i].unlockTime > getCurrentTime()) { break; } amount += locks[i].amount; } } return amount; }
5,022,360
./full_match/43113/0xCbA2aCdFa248BB50Ed83d8C4f14a2C88221B2730/sources/HarmoNYAN.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "HARMONYAN::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
7,123,171
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; /* ██████ ██████ ██ ██ ███ ██ ██████ ██ ██ ██ ██ ██ ████ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██████ ██████ ██ ████ ██████ */ import {IERC2981Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol'; import {ERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import {LibUintToString} from './LibUintToString.sol'; import {CountersUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol'; import {ArtistCreator} from './ArtistCreator.sol'; import {ECDSA} from '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; /// @title Artist /// @author SoundXYZ - @gigamesh & @vigneshka /// @notice This contract is used to create & sell song NFTs for the artist who owns the contract. /// @dev Started as a fork of Mirror's Editions.sol https://github.com/mirror-xyz/editions-v1/blob/main/contracts/Editions.sol contract ArtistV3 is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable { // ================================ // TYPES // ================================ using LibUintToString for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; using ECDSA for bytes32; enum TimeType { START, END } // ============ Structs ============ struct Edition { // The account that will receive sales revenue. address payable fundingRecipient; // The price at which each token will be sold, in ETH. uint256 price; // The number of tokens sold so far. uint32 numSold; // The maximum number of tokens that can be sold. uint32 quantity; // Royalty amount in bps uint32 royaltyBPS; // start timestamp of auction (in seconds since unix epoch) uint32 startTime; // end timestamp of auction (in seconds since unix epoch) uint32 endTime; // quantity of permissioned tokens uint32 permissionedQuantity; // whitelist signer address address signerAddress; } // ================================ // STORAGE // ================================ string internal baseURI; CountersUpgradeable.Counter private atTokenId; // DEPRECATED IN V3 CountersUpgradeable.Counter private atEditionId; // Mapping of edition id to descriptive data. mapping(uint256 => Edition) public editions; // <DEPRECATED IN V3> Mapping of token id to edition id. mapping(uint256 => uint256) private _tokenToEdition; // The amount of funds that have been deposited for a given edition. mapping(uint256 => uint256) public depositedForEdition; // The amount of funds that have already been withdrawn for a given edition. mapping(uint256 => uint256) public withdrawnForEdition; // The permissioned typehash (used for checking signature validity) bytes32 private constant PERMISSIONED_SALE_TYPEHASH = keccak256('EditionInfo(address contractAddress,address buyerAddress,uint256 editionId)'); bytes32 private immutable DOMAIN_SEPARATOR; // ================================ // EVENTS // ================================ event EditionCreated( uint256 indexed editionId, address fundingRecipient, uint256 price, uint32 quantity, uint32 royaltyBPS, uint32 startTime, uint32 endTime, uint32 permissionedQuantity, address signerAddress ); event EditionPurchased( uint256 indexed editionId, uint256 indexed tokenId, // `numSold` at time of purchase represents the "serial number" of the NFT. uint32 numSold, // The account that paid for and received the NFT. address indexed buyer ); event AuctionTimeSet(TimeType timeType, uint256 editionId, uint32 indexed newTime); event SignerAddressSet(uint256 editionId, address indexed signerAddress); event PermissionedQuantitySet(uint256 editionId, uint32 permissionedQuantity); // ================================ // PUBLIC & EXTERNAL WRITABLE FUNCTIONS // ================================ /// @notice Contract constructor constructor() { DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256('EIP712Domain(uint256 chainId)'), block.chainid)); } /// @notice Initializes the contract /// @param _owner Owner of edition /// @param _name Name of artist function initialize( address _owner, uint256 _artistId, string memory _name, string memory _symbol, string memory _baseURI ) public initializer { __ERC721_init(_name, _symbol); __Ownable_init(); // Set ownership to original sender of contract call transferOwnership(_owner); // E.g. https://sound.xyz/api/metadata/[artistId]/ baseURI = string(abi.encodePacked(_baseURI, _artistId.toString(), '/')); // Set edition id start to be 1 not 0 atEditionId.increment(); } /// @notice Creates a new edition. /// @param _fundingRecipient The account that will receive sales revenue. /// @param _price The price at which each token will be sold, in ETH. /// @param _quantity The maximum number of tokens that can be sold. /// @param _royaltyBPS The royalty amount in bps. /// @param _startTime The start time of the auction, in seconds since unix epoch. /// @param _endTime The end time of the auction, in seconds since unix epoch. /// @param _permissionedQuantity The quantity of tokens that require a signature to buy. /// @param _signerAddress signer address. function createEdition( address payable _fundingRecipient, uint256 _price, uint32 _quantity, uint32 _royaltyBPS, uint32 _startTime, uint32 _endTime, uint32 _permissionedQuantity, address _signerAddress ) external onlyOwner { require(_permissionedQuantity < _quantity + 1, 'Permissioned quantity too big'); require(_quantity > 0, 'Must set quantity'); require(_fundingRecipient != address(0), 'Must set fundingRecipient'); require(_endTime > _startTime, 'End time must be greater than start time'); if (_permissionedQuantity > 0) { require(_signerAddress != address(0), 'Signer address cannot be 0'); } editions[atEditionId.current()] = Edition({ fundingRecipient: _fundingRecipient, price: _price, numSold: 0, quantity: _quantity, royaltyBPS: _royaltyBPS, startTime: _startTime, endTime: _endTime, permissionedQuantity: _permissionedQuantity, signerAddress: _signerAddress }); emit EditionCreated( atEditionId.current(), _fundingRecipient, _price, _quantity, _royaltyBPS, _startTime, _endTime, _permissionedQuantity, _signerAddress ); atEditionId.increment(); } /// @notice Creates a new token for the given edition, and assigns it to the buyer /// @param _editionId The id of the edition to purchase /// @param _signature A signed message for authorizing permissioned purchases function buyEdition(uint256 _editionId, bytes calldata _signature) external payable { // Caching variables locally to reduce reads uint256 price = editions[_editionId].price; uint32 quantity = editions[_editionId].quantity; uint32 numSold = editions[_editionId].numSold; uint32 startTime = editions[_editionId].startTime; uint32 endTime = editions[_editionId].endTime; uint32 permissionedQuantity = editions[_editionId].permissionedQuantity; // Check that the edition exists. Note: this is redundant // with the next check, but it is useful for clearer error messaging. require(quantity > 0, 'Edition does not exist'); // Check that there are still tokens available to purchase. require(numSold < quantity, 'This edition is already sold out.'); // Check that the sender is paying the correct amount. require(msg.value >= price, 'Must send enough to purchase the edition.'); // If the open auction hasn't started... if (startTime > block.timestamp) { // Check that permissioned tokens are still available require( permissionedQuantity > 0 && numSold < permissionedQuantity, 'No permissioned tokens available & open auction not started' ); // Check that the signature is valid. require(getSigner(_signature, _editionId) == editions[_editionId].signerAddress, 'Invalid signer'); } // Don't allow purchases after the end time require(endTime > block.timestamp, 'Auction has ended'); // Create the token id by packing editionId in the top bits uint256 tokenId; unchecked { tokenId = (_editionId << 128) | (numSold + 1); // Increment the number of tokens sold for this edition. editions[_editionId].numSold = numSold + 1; } // If fundingRecipient is the owner (artist's wallet), update the edition's balance & don't send the funds if (editions[_editionId].fundingRecipient == owner()) { // Update the deposited total for the edition depositedForEdition[_editionId] += msg.value; } else { // Send funds to the funding recipient. _sendFunds(editions[_editionId].fundingRecipient, msg.value); } // Mint a new token for the sender, using the `tokenId`. _mint(msg.sender, tokenId); emit EditionPurchased(_editionId, tokenId, editions[_editionId].numSold, msg.sender); } function withdrawFunds(uint256 _editionId) external { // Compute the amount available for withdrawing from this edition. uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId]; // Set the amount withdrawn to the amount deposited. withdrawnForEdition[_editionId] = depositedForEdition[_editionId]; // Send the amount that was remaining for the edition, to the funding recipient. _sendFunds(editions[_editionId].fundingRecipient, remainingForEdition); } /// @notice Sets the start time for an edition function setStartTime(uint256 _editionId, uint32 _startTime) external onlyOwner { editions[_editionId].startTime = _startTime; emit AuctionTimeSet(TimeType.START, _editionId, _startTime); } /// @notice Sets the end time for an edition function setEndTime(uint256 _editionId, uint32 _endTime) external onlyOwner { editions[_editionId].endTime = _endTime; emit AuctionTimeSet(TimeType.END, _editionId, _endTime); } /// @notice Sets the signature address of an edition function setSignerAddress(uint256 _editionId, address _newSignerAddress) external onlyOwner { require(_newSignerAddress != address(0), 'Signer address cannot be 0'); editions[_editionId].signerAddress = _newSignerAddress; emit SignerAddressSet(_editionId, _newSignerAddress); } /// @notice Sets the permissioned quantity for an edition function setPermissionedQuantity(uint256 _editionId, uint32 _permissionedQuantity) external onlyOwner { // Check that the permissioned quantity is less than the total quantity require(_permissionedQuantity < editions[_editionId].quantity + 1, 'Must not exceed quantity'); // Prevent setting to permissioned quantity when there is no signer address require(editions[_editionId].signerAddress != address(0), 'Edition must have a signer'); editions[_editionId].permissionedQuantity = _permissionedQuantity; emit PermissionedQuantitySet(_editionId, _permissionedQuantity); } // ================================ // VIEW FUNCTIONS // ================================ /// @notice Returns token URI (metadata URL). e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId] /// @dev Concatenate the baseURI, editionId and tokenId, to create URI. function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token'); uint256 editionId = tokenToEdition(_tokenId); return string(abi.encodePacked(baseURI, editionId.toString(), '/', _tokenId.toString())); } /// @notice Returns contract URI used by Opensea. e.g. https://sound.xyz/api/metadata/[artistId]/storefront function contractURI() public view returns (string memory) { return string(abi.encodePacked(baseURI, 'storefront')); } /// @notice Get royalty information for token /// @param _tokenId token id /// @param _salePrice Sale price for the token function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address fundingRecipient, uint256 royaltyAmount) { uint256 editionId = tokenToEdition(_tokenId); Edition memory edition = editions[editionId]; if (edition.fundingRecipient == address(0x0)) { return (edition.fundingRecipient, 0); } uint256 royaltyBPS = uint256(edition.royaltyBPS); return (edition.fundingRecipient, (_salePrice * royaltyBPS) / 10_000); } /// @notice The total number of tokens created by this contract function totalSupply() external view returns (uint256) { uint256 total = 0; for (uint256 id = 1; id < atEditionId.current(); id++) { total += editions[id].numSold; } return total; } /// @notice Informs other contracts which interfaces this contract supports /// @dev https://eips.ethereum.org/EIPS/eip-165 function supportsInterface(bytes4 _interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId); } /// @notice returns the number of editions for this artist function editionCount() external view returns (uint256) { return atEditionId.current() - 1; // because atEditionId is incremented after each edition is created } function tokenToEdition(uint256 _tokenId) public view returns (uint256) { // Check the top bits to see if the edition id is there uint256 editionId = _tokenId >> 128; // If edition ID is 0, then this edition was created before the V3 upgrade if (editionId == 0) { // get edition ID from storage return _tokenToEdition[_tokenId]; } return editionId; } function ownersOfTokenIds(uint256[] calldata _tokenIds) external view returns (address[] memory) { address[] memory owners = new address[](_tokenIds.length); for (uint256 i = 0; i < _tokenIds.length; i++) { owners[i] = ownerOf(_tokenIds[i]); } return owners; } // ================================ // FUNCTIONS - PRIVATE // ================================ /// @notice Sends funds to an address /// @param _recipient The address to send funds to /// @param _amount The amount of funds to send function _sendFunds(address payable _recipient, uint256 _amount) private { require(address(this).balance >= _amount, 'Insufficient balance for send'); (bool success, ) = _recipient.call{value: _amount}(''); require(success, 'Unable to send value: recipient may have reverted'); } /// @notice Gets signer address to validate permissioned purchase /// @param _signature signed message /// @param _editionId edition id /// @return address of signer /// @dev https://eips.ethereum.org/EIPS/eip-712 function getSigner(bytes calldata _signature, uint256 _editionId) private view returns (address) { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMISSIONED_SALE_TYPEHASH, address(this), msg.sender, _editionId)) ) ); address recoveredAddress = digest.recover(_signature); return recoveredAddress; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981Upgradeable is IERC165Upgradeable { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; library LibUintToString { uint256 private constant MAX_UINT256_STRING_LENGTH = 78; uint8 private constant ASCII_DIGIT_OFFSET = 48; /// @dev Converts a `uint256` value to a string. /// @param n The integer to convert. /// @return nstr `n` as a decimal string. function toString(uint256 n) internal pure returns (string memory nstr) { if (n == 0) { return '0'; } // Overallocate memory nstr = new string(MAX_UINT256_STRING_LENGTH); uint256 k = MAX_UINT256_STRING_LENGTH; // Populate string from right to left (lsb to msb). while (n != 0) { assembly { let char := add(ASCII_DIGIT_OFFSET, mod(n, 10)) mstore(add(nstr, k), char) k := sub(k, 1) n := div(n, 10) } } assembly { // Shift pointer over to actual start of string. nstr := add(nstr, k) // Store actual string length. mstore(nstr, sub(MAX_UINT256_STRING_LENGTH, k)) } return nstr; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; /* ██████ ██████ ██ ██ ███ ██ ██████ ██ ██ ██ ██ ██ ████ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██████ ██████ ██ ████ ██████ */ import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; import '@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol'; import '@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol'; import './Artist.sol'; contract ArtistCreator is Initializable, UUPSUpgradeable, OwnableUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; using ECDSAUpgradeable for bytes32; // ============ Storage ============ bytes32 public constant MINTER_TYPEHASH = keccak256('Deployer(address artistWallet)'); CountersUpgradeable.Counter private atArtistId; // address used for signature verification, changeable by owner address public admin; bytes32 public DOMAIN_SEPARATOR; address public beaconAddress; // registry of created contracts address[] public artistContracts; // ============ Events ============ /// Emitted when an Artist is created event CreatedArtist(uint256 artistId, string name, string symbol, address indexed artistAddress); // ============ Functions ============ /// Initializes factory function initialize() public initializer { __Ownable_init_unchained(); // set admin for artist deployment authorization admin = msg.sender; DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256('EIP712Domain(uint256 chainId)'), block.chainid)); // set up beacon with msg.sender as the owner UpgradeableBeacon _beacon = new UpgradeableBeacon(address(new Artist())); _beacon.transferOwnership(msg.sender); beaconAddress = address(_beacon); // Set artist id start to be 1 not 0 atArtistId.increment(); } /// Creates a new artist contract as a factory with a deterministic address /// Important: None of these fields (except the Url fields with the same hash) can be changed after calling /// @param _name Name of the artist function createArtist( bytes calldata signature, string memory _name, string memory _symbol, string memory _baseURI ) public returns (address) { require((getSigner(signature) == admin), 'invalid authorization signature'); BeaconProxy proxy = new BeaconProxy( beaconAddress, abi.encodeWithSelector( Artist(address(0)).initialize.selector, msg.sender, atArtistId.current(), _name, _symbol, _baseURI ) ); // add to registry artistContracts.push(address(proxy)); emit CreatedArtist(atArtistId.current(), _name, _symbol, address(proxy)); atArtistId.increment(); return address(proxy); } /// Get signer address of signature function getSigner(bytes calldata signature) public view returns (address) { require(admin != address(0), 'whitelist not enabled'); // Verify EIP-712 signature by recreating the data structure // that we signed on the client side, and then using that to recover // the address that signed the signature for this data. bytes32 digest = keccak256( abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(MINTER_TYPEHASH, msg.sender))) ); // Use the recover method to see what address was used to create // the signature on this data. // Note that if the digest doesn't exactly match what was signed we'll // get a random recovered address. address recoveredAddress = digest.recover(signature); return recoveredAddress; } /// Sets the admin for authorizing artist deployment /// @param _newAdmin address of new admin function setAdmin(address _newAdmin) external { require(owner() == _msgSender() || admin == _msgSender(), 'invalid authorization'); admin = _newAdmin; } function _authorizeUpgrade(address) internal override onlyOwner {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165Upgradeable.sol"; // 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 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 (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/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/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 (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 (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../Proxy.sol"; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) payable { assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)); _upgradeBeaconToAndCall(beacon, data, false); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address) { return _getBeacon(); } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_getBeacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { _upgradeBeaconToAndCall(beacon, data, false); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../../access/Ownable.sol"; import "../../utils/Address.sol"; /** * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their * implementation contract, which is where they will delegate all function calls. * * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. */ contract UpgradeableBeacon is IBeacon, Ownable { address private _implementation; /** * @dev Emitted when the implementation returned by the beacon is changed. */ event Upgraded(address indexed implementation); /** * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the * beacon. */ constructor(address implementation_) { _setImplementation(implementation_); } /** * @dev Returns the current implementation address. */ function implementation() public view virtual override returns (address) { return _implementation; } /** * @dev Upgrades the beacon to a new implementation. * * Emits an {Upgraded} event. * * Requirements: * * - msg.sender must be the owner of the contract. * - `newImplementation` must be a contract. */ function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation contract address for this beacon * * Requirements: * * - `newImplementation` must be a contract. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract"); _implementation = newImplementation; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; /* ██████ ██████ ██ ██ ███ ██ ██████ ██ ██ ██ ██ ██ ████ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██████ ██████ ██ ████ ██████ */ import {IERC2981Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol'; import {ERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import {Strings} from './Strings.sol'; import {CountersUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol'; // This contract is a combination of Mirror.xyz's Editions.sol and Zora's SingleEditionMintable.sol /** * @title Artist * @author SoundXYZ */ contract Artist is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable { // todo (optimization): link Strings as a deployed library using Strings for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; // ============ Structs ============ struct Edition { // The account that will receive sales revenue. address payable fundingRecipient; // The price at which each token will be sold, in ETH. uint256 price; // The number of tokens sold so far. uint32 numSold; // The maximum number of tokens that can be sold. uint32 quantity; // Royalty amount in bps uint32 royaltyBPS; // start timestamp of auction (in seconds since unix epoch) uint32 startTime; // end timestamp of auction (in seconds since unix epoch) uint32 endTime; } // ============ Storage ============ string internal baseURI; CountersUpgradeable.Counter private atTokenId; CountersUpgradeable.Counter private atEditionId; // Mapping of edition id to descriptive data. mapping(uint256 => Edition) public editions; // Mapping of token id to edition id. mapping(uint256 => uint256) public tokenToEdition; // The amount of funds that have been deposited for a given edition. mapping(uint256 => uint256) public depositedForEdition; // The amount of funds that have already been withdrawn for a given edition. mapping(uint256 => uint256) public withdrawnForEdition; // ============ Events ============ event EditionCreated( uint256 indexed editionId, address fundingRecipient, uint256 price, uint32 quantity, uint32 royaltyBPS, uint32 startTime, uint32 endTime ); event EditionPurchased( uint256 indexed editionId, uint256 indexed tokenId, // `numSold` at time of purchase represents the "serial number" of the NFT. uint32 numSold, // The account that paid for and received the NFT. address indexed buyer ); // ============ Methods ============ /** @param _owner Owner of edition @param _name Name of artist */ function initialize( address _owner, uint256 _artistId, string memory _name, string memory _symbol, string memory _baseURI ) public initializer { __ERC721_init(_name, _symbol); __Ownable_init(); // Set ownership to original sender of contract call transferOwnership(_owner); // E.g. https://sound.xyz/api/metadata/[artistId]/ baseURI = string(abi.encodePacked(_baseURI, _artistId.toString(), '/')); // Set token id start to be 1 not 0 atTokenId.increment(); // Set edition id start to be 1 not 0 atEditionId.increment(); } function createEdition( address payable _fundingRecipient, uint256 _price, uint32 _quantity, uint32 _royaltyBPS, uint32 _startTime, uint32 _endTime ) external onlyOwner { editions[atEditionId.current()] = Edition({ fundingRecipient: _fundingRecipient, price: _price, numSold: 0, quantity: _quantity, royaltyBPS: _royaltyBPS, startTime: _startTime, endTime: _endTime }); emit EditionCreated( atEditionId.current(), _fundingRecipient, _price, _quantity, _royaltyBPS, _startTime, _endTime ); atEditionId.increment(); } function buyEdition(uint256 _editionId) external payable { // Check that the edition exists. Note: this is redundant // with the next check, but it is useful for clearer error messaging. require(editions[_editionId].quantity > 0, 'Edition does not exist'); // Check that there are still tokens available to purchase. require(editions[_editionId].numSold < editions[_editionId].quantity, 'This edition is already sold out.'); // Check that the sender is paying the correct amount. require(msg.value >= editions[_editionId].price, 'Must send enough to purchase the edition.'); // Don't allow purchases before the start time require(editions[_editionId].startTime < block.timestamp, "Auction hasn't started"); // Don't allow purchases after the end time require(editions[_editionId].endTime > block.timestamp, 'Auction has ended'); // Mint a new token for the sender, using the `tokenId`. _mint(msg.sender, atTokenId.current()); // Update the deposited total for the edition depositedForEdition[_editionId] += msg.value; // Increment the number of tokens sold for this edition. editions[_editionId].numSold++; // Store the mapping of token id to the edition being purchased. tokenToEdition[atTokenId.current()] = _editionId; emit EditionPurchased(_editionId, atTokenId.current(), editions[_editionId].numSold, msg.sender); atTokenId.increment(); } // ============ Operational Methods ============ function withdrawFunds(uint256 _editionId) external { // Compute the amount available for withdrawing from this edition. uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId]; // Set the amount withdrawn to the amount deposited. withdrawnForEdition[_editionId] = depositedForEdition[_editionId]; // Send the amount that was remaining for the edition, to the funding recipient. _sendFunds(editions[_editionId].fundingRecipient, remainingForEdition); } function setStartTime(uint256 _editionId, uint32 _startTime) external onlyOwner { editions[_editionId].startTime = _startTime; } function setEndTime(uint256 _editionId, uint32 _endTime) external onlyOwner { editions[_editionId].endTime = _endTime; } // ============ NFT Methods ============ // Returns e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId] function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token'); // Concatenate the components, baseURI, editionId and tokenId, to create URI. return string(abi.encodePacked(baseURI, tokenToEdition[_tokenId].toString(), '/', _tokenId.toString())); } // Returns e.g. https://sound.xyz/api/metadata/[artistId]/storefront function contractURI() public view returns (string memory) { // Concatenate the components, baseURI, editionId and tokenId, to create URI. return string(abi.encodePacked(baseURI, 'storefront')); } // ============ Extensions ================= /** @dev Get token ids for a given edition id @param _editionId edition id */ function getTokenIdsOfEdition(uint256 _editionId) public view returns (uint256[] memory) { uint256[] memory tokenIdsOfEdition = new uint256[](editions[_editionId].numSold); uint256 index = 0; for (uint256 id = 1; id < atTokenId.current(); id++) { if (tokenToEdition[id] == _editionId) { tokenIdsOfEdition[index] = id; index++; } } return tokenIdsOfEdition; } /** @dev Get owners of a given edition id @param _editionId edition id */ function getOwnersOfEdition(uint256 _editionId) public view returns (address[] memory) { address[] memory ownersOfEdition = new address[](editions[_editionId].numSold); uint256 index = 0; for (uint256 id = 1; id < atTokenId.current(); id++) { if (tokenToEdition[id] == _editionId) { ownersOfEdition[index] = ERC721Upgradeable.ownerOf(id); index++; } } return ownersOfEdition; } /** @dev Get royalty information for token @param _editionId edition id @param _salePrice Sale price for the token */ function royaltyInfo(uint256 _editionId, uint256 _salePrice) external view override returns (address fundingRecipient, uint256 royaltyAmount) { Edition memory edition = editions[_editionId]; if (edition.fundingRecipient == address(0x0)) { return (edition.fundingRecipient, 0); } uint256 royaltyBPS = uint256(edition.royaltyBPS); return (edition.fundingRecipient, (_salePrice * royaltyBPS) / 10_000); } function totalSupply() external view returns (uint256) { return atTokenId.current() - 1; // because atTokenId is 1-indexed } function supportsInterface(bytes4 _interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId); } // ============ Private Methods ============ function _sendFunds(address payable _recipient, uint256 _amount) private { require(address(this).balance >= _amount, 'Insufficient balance for send'); (bool success, ) = _recipient.call{value: _amount}(''); require(success, 'Unable to send value: recipient may have reverted'); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; // This contract is a combination of Mirror.xyz's Editions.sol and Zora's SingleEditionMintable.sol /** * @title Utils * @author SoundXYZ */ library Strings { // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol 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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } }
Compute the amount available for withdrawing from this edition. Set the amount withdrawn to the amount deposited. Send the amount that was remaining for the edition, to the funding recipient.
function withdrawFunds(uint256 _editionId) external { uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId]; withdrawnForEdition[_editionId] = depositedForEdition[_editionId]; _sendFunds(editions[_editionId].fundingRecipient, remainingForEdition); }
5,724,330
./full_match/1/0x6c138e85cCb4Ac8036Ae51322F495770e4162065/sources/contracts/PercentSplitETH.sol
Returns a tuple with the terms of this split. return shares The list of recipients and their share of the payment for this split./
function getShares() external view returns (Share[] memory shares) { shares = new Share[](_shares.length); for (uint256 i = 0; i < shares.length; ) { unchecked { ++i; } } }
16,489,323
./partial_match/3/0xA5221B24D9065135E196949ea25Fb15a90528239/sources/SwanStake.sol
_amount - the amount user wants to stake allows the user to stake the initial $2000 worth of SWAN tokens Lists the user as a valid Staker.(by adding True in the isStaker mapping) User can earn comparatively more interest on Future stakes by calling this function/
function stake(uint256 _amount) external whenNotPaused returns(bool){ require(!isStaker[msg.sender],"Previous Staked Amount is not Withdrawn yet"); require (_amount >= currentPrice.mul(2000 ether),"Staking Amount is Less Than $2000"); require(ERC20(swanTokenAddress).transferFrom(msg.sender,address(this),_amount),"Token Transfer Failed"); stakeAccountDetails[msg.sender] = StakeAccount( { stakedAmount:_amount, time:now, interestRate:14, unstaked:false }); isStaker[msg.sender] = true; userTotalStakes[msg.sender] += _amount; emit staked(msg.sender,_amount,4,14); return true; }
5,320,858
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./interfaces/IPunkCrushers.sol"; /** * @title PunkCrushers NFTs * @dev Implementation of the {IPunkCrushers} interface. * @author Ahmed Ali Bhatti <github.com/ahmedali8> */ contract PunkCrushers is IPunkCrushers, Ownable, ERC721Enumerable { using Counters for Counters.Counter; using Strings for uint256; // tokenId tracker using lib Counters.Counter private _tokenIdTracker; string private _baseTokenURI; // flag for updating {baseURI} only once. bool private _uriUpdated = false; /** * @dev See {IPunkCrushers-MAX_SUPPLY}. */ uint256 public constant override MAX_SUPPLY = 10000; /** * @dev See {IPunkCrushers-PRICE_PER_TOKEN_FOR_1}. */ uint256 public constant override PRICE_PER_TOKEN_FOR_1 = 0.085 ether; /** * @dev See {IPunkCrushers-PRICE_PER_TOKEN_FOR_3}. */ uint256 public constant override PRICE_PER_TOKEN_FOR_3 = 0.075 ether; /** * @dev See {IPunkCrushers-PRICE_PER_TOKEN_FOR_5}. */ uint256 public constant override PRICE_PER_TOKEN_FOR_5 = 0.065 ether; /** * @dev See {IPunkCrushers-PRICE_PER_TOKEN_FOR_10}. */ uint256 public constant override PRICE_PER_TOKEN_FOR_10 = 0.055 ether; /** * @dev See {IPunkCrushers-PRICE_PER_TOKEN_FOR_20}. */ uint256 public constant override PRICE_PER_TOKEN_FOR_20 = 0.045 ether; /** * @dev See {IPunkCrushers-presaleActive}. */ bool public override presaleActive = true; /** * @dev See {IPunkCrushers-dev}. */ address public override dev; /** * @dev Sets {dev}, {_initialBaseURI} and {ERC721-constructor}. */ constructor(address _dev, string memory _initialBaseURI) ERC721("Punk Crushers", "PKCS") { _baseTokenURI = _initialBaseURI; dev = _dev; } /** * @dev See {IPunkCrushers-baseURI}. */ function baseURI() public view override returns (string memory) { return _baseURI(); } /** * @dev See {IPunkCrushers-tokenExists}. */ function tokenExists(uint256 _tokenId) public view override returns (bool) { return _exists(_tokenId); } /** * @dev See {IPunkCrushers-tokensPrice}. */ function tokensPrice(uint256 _noOfTokens) public pure override returns (uint256) { if (_noOfTokens == 3) return _noOfTokens * PRICE_PER_TOKEN_FOR_3; if (_noOfTokens == 5) return _noOfTokens * PRICE_PER_TOKEN_FOR_5; if (_noOfTokens == 10) return _noOfTokens * PRICE_PER_TOKEN_FOR_10; if (_noOfTokens == 20) return _noOfTokens * PRICE_PER_TOKEN_FOR_20; return _noOfTokens * PRICE_PER_TOKEN_FOR_1; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { super.tokenURI(_tokenId); return (bytes(baseURI()).length > 0) ? string( abi.encodePacked(baseURI(), _tokenId.toString(), ".json") ) : ""; } /** * @dev See {IPunkCrushers-presaleMint}. * * Emits a {NFTMinted} event indicating the mint of a new NFT. * * @param _noOfTokens - no of tokens `caller` wants to mint. * * Requirements: * * - presale must be active. * - `_noOfTokens` must be less than 20. */ function presaleMint(uint256 _noOfTokens) public payable override { require(presaleActive, "PresaleMint: presale inactive"); require(_noOfTokens <= 20, "PresaleMint: max 20 per transaction"); _mint(_noOfTokens, msg.value); } /** * @dev See {IPunkCrushers-mint}. * * Emits a {NFTMinted} event indicating the mint of a new NFT. * * @param _noOfTokens - no of tokens `caller` wants to mint. * * Requirements: * * - `_noOfTokens` must be less than 10. */ function mint(uint256 _noOfTokens) public payable override { require(_noOfTokens <= 10, "Mint: max 10 per transaction"); _mint(_noOfTokens, msg.value); } /** * @dev See {IPunkCrushers-reserveTokens}. * * Emits a {NFTMinted} event indicating the mint of a new NFT. * * @param _noOfTokens - no of tokens {owner} wants to mint. * * Requirements: * * - `_noOfTokens` must be less than 30. * - caller must be {owner}. */ function reserveTokens(uint256 _noOfTokens) public override onlyOwner { require(_noOfTokens <= 30, "ReserveTokens: max 30 per transaction"); _supplyValidator(_noOfTokens); for (uint8 i = 0; i < _noOfTokens; i++) { // incrementing by 1 _tokenIdTracker.increment(); uint256 _tokenId = _tokenIdTracker.current(); // mint nft _safeMint(_msgSender(), _tokenId); emit NFTMinted(_tokenId, _msgSender()); } } /** * @dev See {IPunkCrushers-togglePresale}. * * Requirements: * * - caller must be {owner}. */ function togglePresale() public override onlyOwner { presaleActive = !presaleActive; } /** * @dev See {IPunkCrushers-setBaseURI}. * * Emits a {BaseURIUpdated} event indicating change of {baseURI}. * * @param _newBaseTokenURI - new base URI string. * * Requirements: * - `_newBaseTokenURI` must be in format: "ipfs://{hash}/" * - `_noOfTokens` must be less than 30. * - caller must be {owner}. */ function setBaseURI(string memory _newBaseTokenURI) public override onlyOwner { require( !_uriUpdated, "setBaseURI: uri cannot be updated more than once" ); _baseTokenURI = _newBaseTokenURI; _uriUpdated = true; emit BaseURIUpdated(_newBaseTokenURI); } /** * @dev Internal function called in {presaleMint} and {mint}. * mints tokens and transfers to `caller`. * * Emits a {FundsTransferred} event indicating transfer of funds. * * @param _noOfTokens - no of tokens {owner} wants to mint. * @param _value - ether price paid for token minting. * * Requirements: * - {totalSupply} must not max out {MAX_SUPPLY}. * - `_value` must be equal to correct tokenPrice. */ function _mint(uint256 _noOfTokens, uint256 _value) internal { _supplyValidator(_noOfTokens); require(_value == tokensPrice(_noOfTokens), "Mint: invalid price"); for (uint256 i = 0; i < _noOfTokens; i++) { // incrementing _tokenIdTracker.increment(); uint256 _tokenId = _tokenIdTracker.current(); // mint nft _safeMint(_msgSender(), _tokenId); emit NFTMinted(_tokenId, _msgSender()); } // transfer funds to owner and dev _transferFunds(_value); } /** * @dev Internal function called in {_mint} and {reserveTokens}. * * @param _noOfTokens - no of tokens `caller` wants to mint. * * Requirements: * - {totalSupply} must not max out {MAX_SUPPLY}. */ function _supplyValidator(uint256 _noOfTokens) internal view { require( totalSupply() + _noOfTokens <= MAX_SUPPLY, "SupplyValidator: max limit reached" ); } /** * @dev Internal function called in {_mint}. * transfers funds to {owner} and {dev}. * * Emits a {FundsTransferred} event indicating transfer of funds. * * @param _value - ether price paid for token minting. */ function _transferFunds(uint256 _value) internal { address payable _owner = payable(owner()); uint256 _ownerShare = (_value * 70) / 100; Address.sendValue(_owner, _ownerShare); emit FundsTransferred(_owner, _ownerShare); address payable _dev = payable(dev); uint256 _devShare = (_value * 30) / 100; Address.sendValue(_dev, _devShare); emit FundsTransferred(_dev, _devShare); } /** * @dev See {ERC721-_baseURI} * */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev Interface of the PunkCrushers. * @author Ahmed Ali Bhatti <github.com/ahmedali8> */ interface IPunkCrushers { /** * @dev Emitted when `baseURI` is changed. */ event BaseURIUpdated(string baseURI); /** * @dev Emitted when a new token is minted. */ event NFTMinted(uint256 indexed tokenId, address indexed beneficiary); /** * @dev Emitted when `amount` ether are send to `beneficiary`. */ event FundsTransferred(address indexed beneficiary, uint256 amount); /** * @dev Returns the max allowed supply i.e. 10,000. */ function MAX_SUPPLY() external view returns (uint256); /** * @dev Returns the price per token if `1` token is to be minted. */ function PRICE_PER_TOKEN_FOR_1() external view returns (uint256); /** * @dev Returns the price per token if `3` tokens is to be minted. */ function PRICE_PER_TOKEN_FOR_3() external view returns (uint256); /** * @dev Returns the price per token if `5` tokens is to be minted. */ function PRICE_PER_TOKEN_FOR_5() external view returns (uint256); /** * @dev Returns the price per token if `10` tokens is to be minted. */ function PRICE_PER_TOKEN_FOR_10() external view returns (uint256); /** * @dev Returns the price per token if `20` tokens is to be minted. * * Note: only for {presaleMint}. */ function PRICE_PER_TOKEN_FOR_20() external view returns (uint256); /** * @dev Returns bool flag if presale is active or not. */ function presaleActive() external view returns (bool); /** * @dev Returns the address of {dev}. */ function dev() external view returns (address); /** * @dev Returns the string value of {baseURI}. */ function baseURI() external view returns (string calldata); /** * @dev Returns bool flag is token exists. */ function tokenExists(uint256 _tokenId) external view returns (bool); /** * @dev Returns the price for `_noOfTokens`. */ function tokensPrice(uint256 _noOfTokens) external pure returns (uint256); /** * @dev Mints `_noOfTokens` and transfers to `caller`. * * Note: * - that only callable if {presaleActive} is true. * - that only 20 NFTs can be minted per transaction. * * Emits a {NFTMinted} and {FundsTransferred} events. */ function presaleMint(uint256 _noOfTokens) external payable; /** * @dev Mints `_noOfTokens` and transfers to `caller`. * * Note: that only 10 NFTs can be minted per transaction. * * Emits a {NFTMinted} and {FundsTransferred} events. */ function mint(uint256 _noOfTokens) external payable; /** * @dev Reserves/Mints `_noOfTokens` and transfers to `owner`. * * Note * - that caller must be {owner}. * - that only 30 NFTs can be minted per transaction. * * Emits a {NFTMinted} and {FundsTransferred} events. */ function reserveTokens(uint256 _noOfTokens) external; /** * @dev Toggles presale active or inactive. * * Note that caller must be {owner}. */ function togglePresale() external; /** * @dev Sets {baseURI} to `_newBaseTokenURI`. * * Note * - `_newBaseTokenURI` must be in format: "ipfs://{hash}/" * - that caller must be {owner}. * - that only callable once. * * Emits a {BaseURIUpdated} event. */ function setBaseURI(string calldata _newBaseTokenURI) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Internal function called in {_mint}. transfers funds to {owner} and {dev}. Emits a {FundsTransferred} event indicating transfer of funds. _value - ether price paid for token minting./
function _transferFunds(uint256 _value) internal { address payable _owner = payable(owner()); uint256 _ownerShare = (_value * 70) / 100; Address.sendValue(_owner, _ownerShare); emit FundsTransferred(_owner, _ownerShare); address payable _dev = payable(dev); uint256 _devShare = (_value * 30) / 100; Address.sendValue(_dev, _devShare); emit FundsTransferred(_dev, _devShare); }
1,494,199
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "./Accountant.sol"; import "./CreditLine.sol"; import "./CreditLineFactory.sol"; /** * @title Goldfinch's CreditDesk contract * @notice Main entry point for borrowers and underwriters. * Handles key logic for creating CreditLine's, borrowing money, repayment, etc. * @author Goldfinch */ contract CreditDesk is BaseUpgradeablePausable, ICreditDesk { // Approximate number of blocks per day uint256 public constant BLOCKS_PER_DAY = 5760; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; struct Underwriter { uint256 governanceLimit; address[] creditLines; } struct Borrower { address[] creditLines; } event PaymentApplied( address indexed payer, address indexed creditLine, uint256 interestAmount, uint256 principalAmount, uint256 remainingAmount ); event PaymentCollected(address indexed payer, address indexed creditLine, uint256 paymentAmount); event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount); event CreditLineCreated(address indexed borrower, address indexed creditLine); event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit); mapping(address => Underwriter) public underwriters; mapping(address => Borrower) private borrowers; mapping(address => address) private creditLines; /** * @notice Run only once, on initialization * @param owner The address of who should have the "OWNER_ROLE" of this contract * @param _config The address of the GoldfinchConfig contract */ function initialize(address owner, GoldfinchConfig _config) public initializer { __BaseUpgradeablePausable__init(owner); config = _config; } /** * @notice Sets a particular underwriter's limit of how much credit the DAO will allow them to "create" * @param underwriterAddress The address of the underwriter for whom the limit shall change * @param limit What the new limit will be set to * Requirements: * * - the caller must have the `OWNER_ROLE`. */ function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external override onlyAdmin whenNotPaused { require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol"); underwriters[underwriterAddress].governanceLimit = limit; emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit); } /** * @notice Allows an underwriter to create a new CreditLine for a single borrower * @param _borrower The borrower for whom the CreditLine will be created * @param _limit The maximum amount a borrower can drawdown from this CreditLine * @param _interestApr The interest amount, on an annualized basis (APR, so non-compounding), expressed as an integer. * We assume 8 digits of precision. For example, to submit 15.34%, you would pass up 15340000, * and 5.34% would be 5340000 * @param _paymentPeriodInDays How many days in each payment period. * ie. the frequency with which they need to make payments. * @param _termInDays Number of days in the credit term. It is used to set the `termEndBlock` upon first drawdown. * ie. The credit line should be fully paid off {_termIndays} days after the first drawdown. * @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your * normal rate is 15%, then you will pay 18% while you are late. * * Requirements: * * - the caller must be an underwriter with enough limit (see `setUnderwriterGovernanceLimit`) */ function createCreditLine( address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public override whenNotPaused returns (address) { Underwriter storage underwriter = underwriters[msg.sender]; Borrower storage borrower = borrowers[_borrower]; require(underwriterCanCreateThisCreditLine(_limit, underwriter), "The underwriter cannot create this credit line"); address clAddress = getCreditLineFactory().createCreditLine(""); CreditLine cl = CreditLine(clAddress); cl.initialize( address(this), _borrower, msg.sender, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr ); underwriter.creditLines.push(clAddress); borrower.creditLines.push(clAddress); creditLines[clAddress] = clAddress; emit CreditLineCreated(_borrower, clAddress); cl.grantRole(keccak256("OWNER_ROLE"), config.protocolAdminAddress()); cl.authorizePool(address(config)); return clAddress; } /** * @notice Allows a borrower to drawdown on their creditline. * `amount` USDC is sent to the borrower, and the credit line accounting is updated. * @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown * @param creditLineAddress The creditline from which they would like to drawdown * @param addressToSendTo The address where they would like the funds sent. If the zero address is passed, * it will be defaulted to the borrower's address (msg.sender). This is a convenience feature for when they would * like the funds sent to an exchange or alternate wallet, different from the authentication address * * Requirements: * * - the caller must be the borrower on the creditLine */ function drawdown( uint256 amount, address creditLineAddress, address addressToSendTo ) external override whenNotPaused onlyValidCreditLine(creditLineAddress) { CreditLine cl = CreditLine(creditLineAddress); Borrower storage borrower = borrowers[msg.sender]; require(borrower.creditLines.length > 0, "No credit lines exist for this borrower"); require(amount > 0, "Must drawdown more than zero"); require(cl.borrower() == msg.sender, "You do not belong to this credit line"); require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); require(withinCreditLimit(amount, cl), "The borrower does not have enough credit limit for this drawdown"); if (addressToSendTo == address(0)) { addressToSendTo = msg.sender; } if (cl.balance() == 0) { cl.setInterestAccruedAsOfBlock(blockNumber()); cl.setLastFullPaymentBlock(blockNumber()); } // Must get the interest and principal accrued prior to adding to the balance. (uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, blockNumber()); uint256 balance = cl.balance().add(amount); updateCreditLineAccounting(cl, balance, interestOwed, principalOwed); // Must put this after we update the credit line accounting, so we're using the latest // interestOwed require(!isLate(cl), "Cannot drawdown when payments are past due"); emit DrawdownMade(msg.sender, address(cl), amount); bool success = config.getPool().transferFrom(config.poolAddress(), addressToSendTo, amount); require(success, "Failed to drawdown"); } /** * @notice Allows a borrower to repay their loan. Payment is *collected* immediately (by sending it to * the individual CreditLine), but it is not *applied* unless it is after the nextDueBlock, or until we assess * the credit line (ie. payment period end). * Any amounts over the minimum payment will be applied to outstanding principal (reducing the effective * interest rate). If there is still any left over, it will remain in the USDC Balance * of the CreditLine, which is held distinct from the Pool amounts, and can not be withdrawn by LP's. * @param creditLineAddress The credit line to be paid back * @param amount The amount, in USDC atomic units, that a borrower wishes to pay */ function pay(address creditLineAddress, uint256 amount) external override whenNotPaused onlyValidCreditLine(creditLineAddress) { require(amount > 0, "Must pay more than zero"); CreditLine cl = CreditLine(creditLineAddress); collectPayment(cl, amount); assessCreditLine(creditLineAddress); } /** * @notice Assesses a particular creditLine. This will apply payments, which will update accounting and * distribute gains or losses back to the pool accordingly. This function is idempotent, and anyone * is allowed to call it. * @param creditLineAddress The creditline that should be assessed. */ function assessCreditLine(address creditLineAddress) public override whenNotPaused onlyValidCreditLine(creditLineAddress) { CreditLine cl = CreditLine(creditLineAddress); // Do not assess until a full period has elapsed or past due require(cl.balance() > 0, "Must have balance to assess credit line"); // Don't assess credit lines early! if (blockNumber() < cl.nextDueBlock() && !isLate(cl)) { return; } cl.setNextDueBlock(calculateNextDueBlock(cl)); uint256 blockToAssess = cl.nextDueBlock(); // We always want to assess for the most recently *past* nextDueBlock. // So if the recalculation above sets the nextDueBlock into the future, // then ensure we pass in the one just before this. if (cl.nextDueBlock() > blockNumber()) { uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY); blockToAssess = cl.nextDueBlock().sub(blocksPerPeriod); } applyPayment(cl, getUSDCBalance(address(cl)), blockToAssess); } function migrateCreditLine( CreditLine clToMigrate, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public onlyAdmin { require(clToMigrate.limit() > 0, "Can't migrate empty credit line!"); address newClAddress = createCreditLine(_borrower, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr); CreditLine newCl = CreditLine(newClAddress); // Set accounting state vars. newCl.setBalance(clToMigrate.balance()); newCl.setInterestOwed(clToMigrate.interestOwed()); newCl.setPrincipalOwed(clToMigrate.principalOwed()); newCl.setTermEndBlock(clToMigrate.termEndBlock()); newCl.setNextDueBlock(clToMigrate.nextDueBlock()); newCl.setInterestAccruedAsOfBlock(clToMigrate.interestAccruedAsOfBlock()); newCl.setWritedownAmount(clToMigrate.writedownAmount()); newCl.setLastFullPaymentBlock(clToMigrate.lastFullPaymentBlock()); // Close out the original credit line clToMigrate.setLimit(0); clToMigrate.setBalance(0); bool success = config.getPool().transferFrom( address(clToMigrate), address(newCl), config.getUSDC().balanceOf(address(clToMigrate)) ); require(success, "Failed to transfer funds"); } // Public View Functions (Getters) /** * @notice Simple getter for the creditlines of a given underwriter * @param underwriterAddress The underwriter address you would like to see the credit lines of. */ function getUnderwriterCreditLines(address underwriterAddress) public view whenNotPaused returns (address[] memory) { return underwriters[underwriterAddress].creditLines; } /** * @notice Simple getter for the creditlines of a given borrower * @param borrowerAddress The borrower address you would like to see the credit lines of. */ function getBorrowerCreditLines(address borrowerAddress) public view whenNotPaused returns (address[] memory) { return borrowers[borrowerAddress].creditLines; } /* * Internal Functions */ /** * @notice Collects `amount` of payment for a given credit line. This sends money from the payer to the credit line. * Note that payment is not *applied* when calling this function. Only collected (ie. held) for later application. * @param cl The CreditLine the payment will be collected for. * @param amount The amount, in USDC atomic units, to be collected */ function collectPayment(CreditLine cl, uint256 amount) internal { require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); require(config.getUSDC().balanceOf(msg.sender) >= amount, "You have insufficent balance for this payment"); emit PaymentCollected(msg.sender, address(cl), amount); bool success = config.getPool().transferFrom(msg.sender, address(cl), amount); require(success, "Failed to collect payment"); } /** * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool. * It also updates all the accounting variables. Note that interest is always paid back first, then principal. * Any extra after paying the minimum will go towards existing principal (reducing the * effective interest rate). Any extra after the full loan has been paid off will remain in the * USDC Balance of the creditLine, where it will be automatically used for the next drawdown. * @param cl The CreditLine the payment will be collected for. * @param amount The amount, in USDC atomic units, to be applied * @param blockNumber The blockNumber on which accrual calculations should be based. This allows us * to be precise when we assess a Credit Line */ function applyPayment( CreditLine cl, uint256 amount, uint256 blockNumber ) internal { (uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = handlePayment(cl, amount, blockNumber); updateWritedownAmounts(cl); if (interestPayment > 0) { emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining); config.getPool().collectInterestRepayment(address(cl), interestPayment); } if (principalPayment > 0) { emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining); config.getPool().collectPrincipalRepayment(address(cl), principalPayment); } } function handlePayment( CreditLine cl, uint256 paymentAmount, uint256 asOfBlock ) internal returns ( uint256, uint256, uint256 ) { (uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, asOfBlock); Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(paymentAmount, cl.balance(), interestOwed, principalOwed); uint256 newBalance = cl.balance().sub(pa.principalPayment); // Apply any additional payment towards the balance newBalance = newBalance.sub(pa.additionalBalancePayment); uint256 totalPrincipalPayment = cl.balance().sub(newBalance); uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment); updateCreditLineAccounting( cl, newBalance, interestOwed.sub(pa.interestPayment), principalOwed.sub(pa.principalPayment) ); assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount); return (paymentRemaining, pa.interestPayment, totalPrincipalPayment); } function updateWritedownAmounts(CreditLine cl) internal { (uint256 writedownPercent, uint256 writedownAmount) = Accountant.calculateWritedownFor( cl, blockNumber(), config.getLatenessGracePeriodInDays(), config.getLatenessMaxDays() ); if (writedownPercent == 0 && cl.writedownAmount() == 0) { return; } int256 writedownDelta = int256(cl.writedownAmount()) - int256(writedownAmount); cl.setWritedownAmount(writedownAmount); if (writedownDelta > 0) { // If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns. totalWritedowns = totalWritedowns.sub(uint256(writedownDelta)); } else { totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1)); } config.getPool().distributeLosses(address(cl), writedownDelta); } function isLate(CreditLine cl) internal view returns (bool) { uint256 blocksElapsedSinceFullPayment = blockNumber().sub(cl.lastFullPaymentBlock()); return blocksElapsedSinceFullPayment > cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY); } function getCreditLineFactory() internal view returns (CreditLineFactory) { return CreditLineFactory(config.getAddress(uint256(ConfigOptions.Addresses.CreditLineFactory))); } function subtractClFromTotalLoansOutstanding(CreditLine cl) internal { totalLoansOutstanding = totalLoansOutstanding.sub(cl.balance()); } function addCLToTotalLoansOutstanding(CreditLine cl) internal { totalLoansOutstanding = totalLoansOutstanding.add(cl.balance()); } function updateAndGetInterestAndPrincipalOwedAsOf(CreditLine cl, uint256 blockNumber) internal returns (uint256, uint256) { (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(cl, blockNumber, config.getLatenessGracePeriodInDays()); if (interestAccrued > 0) { // If we've accrued any interest, update interestAccruedAsOfBLock to the block that we've // calculated interest for. If we've not accrued any interest, then we keep the old value so the next // time the entire period is taken into account. cl.setInterestAccruedAsOfBlock(blockNumber); } return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued)); } function withinCreditLimit(uint256 amount, CreditLine cl) internal view returns (bool) { return cl.balance().add(amount) <= cl.limit(); } function withinTransactionLimit(uint256 amount) internal view returns (bool) { return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit)); } function calculateNewTermEndBlock(CreditLine cl) internal view returns (uint256) { // If there's no balance, there's no loan, so there's no term end block if (cl.balance() == 0) { return 0; } // Don't allow any weird bugs where we add to your current end block. This // function should only be used on new credit lines, when we are setting them up if (cl.termEndBlock() != 0) { return cl.termEndBlock(); } return blockNumber().add(BLOCKS_PER_DAY.mul(cl.termInDays())); } function calculateNextDueBlock(CreditLine cl) internal view returns (uint256) { uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY); uint256 balance = cl.balance(); // Your paid off, or have not taken out a loan yet, so no next due block. if (balance == 0 && cl.nextDueBlock() != 0) { return 0; } // You must have just done your first drawdown if (cl.nextDueBlock() == 0 && balance > 0) { return blockNumber().add(blocksPerPeriod); } // Active loan that has entered a new period, so return the *next* nextDueBlock. // But never return something after the termEndBlock if (balance > 0 && blockNumber() >= cl.nextDueBlock()) { uint256 blocksToAdvance = (blockNumber().sub(cl.nextDueBlock()).div(blocksPerPeriod)).add(1).mul(blocksPerPeriod); uint256 nextDueBlock = cl.nextDueBlock().add(blocksToAdvance); return Math.min(nextDueBlock, cl.termEndBlock()); } // Active loan in current period, where we've already set the nextDueBlock correctly, so should not change. if (balance > 0 && blockNumber() < cl.nextDueBlock()) { return cl.nextDueBlock(); } revert("Error: could not calculate next due block."); } function blockNumber() internal view virtual returns (uint256) { return block.number; } function underwriterCanCreateThisCreditLine(uint256 newAmount, Underwriter storage underwriter) internal view returns (bool) { require(underwriter.governanceLimit != 0, "underwriter does not have governance limit"); uint256 creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter); uint256 totalToBeExtended = creditCurrentlyExtended.add(newAmount); return totalToBeExtended <= underwriter.governanceLimit; } function withinMaxUnderwriterLimit(uint256 amount) internal view returns (bool) { return amount <= config.getNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit)); } function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint256) { uint256 creditExtended; uint256 length = underwriter.creditLines.length; for (uint256 i = 0; i < length; i++) { CreditLine cl = CreditLine(underwriter.creditLines[i]); creditExtended = creditExtended.add(cl.limit()); } return creditExtended; } function updateCreditLineAccounting( CreditLine cl, uint256 balance, uint256 interestOwed, uint256 principalOwed ) internal nonReentrant { subtractClFromTotalLoansOutstanding(cl); cl.setBalance(balance); cl.setInterestOwed(interestOwed); cl.setPrincipalOwed(principalOwed); // This resets lastFullPaymentBlock. These conditions assure that they have // indeed paid off all their interest and they have a real nextDueBlock. (ie. creditline isn't pre-drawdown) if (cl.interestOwed() == 0 && cl.nextDueBlock() != 0) { // If interest was fully paid off, then set the last full payment as the previous due block uint256 mostRecentLastDueBlock; if (blockNumber() < cl.nextDueBlock()) { uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY); mostRecentLastDueBlock = cl.nextDueBlock().sub(blocksPerPeriod); } else { mostRecentLastDueBlock = cl.nextDueBlock(); } cl.setLastFullPaymentBlock(mostRecentLastDueBlock); } addCLToTotalLoansOutstanding(cl); cl.setTermEndBlock(calculateNewTermEndBlock(cl)); cl.setNextDueBlock(calculateNextDueBlock(cl)); } function getUSDCBalance(address _address) internal returns (uint256) { return config.getUSDC().balanceOf(_address); } modifier onlyValidCreditLine(address clAddress) { require(creditLines[clAddress] != address(0), "Unknown credit line"); _; } }
This resets lastFullPaymentBlock. These conditions assure that they have indeed paid off all their interest and they have a real nextDueBlock. (ie. creditline isn't pre-drawdown) If interest was fully paid off, then set the last full payment as the previous due block
function updateCreditLineAccounting( CreditLine cl, uint256 balance, uint256 interestOwed, uint256 principalOwed ) internal nonReentrant { subtractClFromTotalLoansOutstanding(cl); cl.setBalance(balance); cl.setInterestOwed(interestOwed); cl.setPrincipalOwed(principalOwed); if (cl.interestOwed() == 0 && cl.nextDueBlock() != 0) { uint256 mostRecentLastDueBlock; if (blockNumber() < cl.nextDueBlock()) { uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY); mostRecentLastDueBlock = cl.nextDueBlock().sub(blocksPerPeriod); mostRecentLastDueBlock = cl.nextDueBlock(); } cl.setLastFullPaymentBlock(mostRecentLastDueBlock); } addCLToTotalLoansOutstanding(cl); cl.setTermEndBlock(calculateNewTermEndBlock(cl)); cl.setNextDueBlock(calculateNextDueBlock(cl)); }
969,502
/** * 资金方控制器 */ pragma solidity ^0.4.25; pragma experimental ABIEncoderV2; import "./role/Role.sol"; import "./utils/Ownable.sol"; import "./utils/LibString.sol"; import "./service/FinancingProcessStorage.sol"; contract FinancingFundController is Ownable, Role { using LibString for string; FinancingProcessStorage private financingProcessStorage; event IssueResult(int256); event FundAuditResult(bool); event FundConfirmAuditResult(bool); event LoanAuditResult(bool); string constant Fund_Audit_Accept = "FundAuditAccept"; // 融资审批同意状态 string constant Fund_Audit_Reject = "FundAuditReject"; // 融资审批拒绝状态 string constant Fund_Confirm_Audit_Accept = "FundConfirmAuditAccept"; // 融资确认审批同意状态 string constant Fund_Confirm_Audit_Reject = "FundConfirmAuditReject"; // 融资确认审批拒绝状态 string constant Fund_Loan_Audit_Accept = "FundLoanAuditAccept"; // 融资放款审批同意状态 //日志打印 event LogMessage(string _m); function _log(bool _b , string memory _m) private { if(_b){ emit LogMessage(_m); } } constructor() public { financingProcessStorage = new FinancingProcessStorage(); } /** 资金方审核融资单同意 * 资金方融资审批(确认后到出质审批) * _processId 流程id * _user_id 操作用户id */ function auditAccept(string _processId, string _user_id) external onlyOwner returns(bool){ onlyZJRole(_user_id); _log(_processId.empty(), "FinancingFundController fundAudit: _processId is empty"); require(!_processId.empty(), "FinancingFundController fundAudit: _processId is empty"); int256 count = financingProcessStorage.updateDebtorStatus(_processId, Fund_Audit_Accept); emit FundAuditResult(count > int256(0)); return count > int256(0); } /** 资金方审核融资单拒绝 * _processId 流程id * _user_id 操作用户id */ function auditReject(string _processId, string _user_id) external onlyOwner returns(bool){ onlyZJRole(_user_id); _log(_processId.empty(), "FinancingFundController fundAudit: _processId is empty"); require(!_processId.empty(), "FinancingFundController fundAudit: _processId is empty"); int256 count = financingProcessStorage.updateDebtorStatus(_processId, Fund_Audit_Reject); emit FundAuditResult(count > int256(0)); return count > int256(0); } /** 资金方审核放货同意 * 资金方确认融资审批(确认后走放款流程) * _processId 流程id * _user_id 操作用户id */ function confirmAuditAccept(string _processId, string _user_id) external onlyOwner returns(bool){ onlyZJRole(_user_id); _log(_processId.empty(), "FinancingFundController fundConfirmAudit: _processId is empty"); require(!_processId.empty(), "FinancingFundController fundConfirmAudit: _processId is empty"); int256 count = financingProcessStorage.updateCreditSideStatus(_processId, Fund_Confirm_Audit_Accept); emit FundConfirmAuditResult(count > int256(0)); return count > int256(0); } /** 资金方审核放货拒绝 * _processId 流程id * _user_id 操作用户id */ function confirmAuditReject(string _processId, string _user_id) external onlyOwner returns(bool){ onlyZJRole(_user_id); _log(_processId.empty(), "FinancingFundController fundConfirmAudit: _processId is empty"); require(!_processId.empty(), "FinancingFundController fundConfirmAudit: _processId is empty"); int256 count = financingProcessStorage.updateCreditSideStatus(_processId, Fund_Confirm_Audit_Reject); emit FundConfirmAuditResult(count > int256(0)); return count > int256(0); } /** 资金方放款审批同意 * 流程结束 * _processId 流程id * _user_id 操作用户id */ function loanAuditAccept(string _processId, string _user_id) external onlyOwner returns(bool){ onlyZJRole(_user_id); _log(_processId.empty(), "FinancingFundController loanAudit: _processId is empty"); require(!_processId.empty(), "FinancingFundController loanAudit: _processId is empty"); int256 count = financingProcessStorage.updateCreditSideStatus(_processId, Fund_Loan_Audit_Accept); emit LoanAuditResult(count > int256(0)); return count > int256(0); } /** 资金方放款审批拒绝 * 流程回转到资金方审核融资单 * _processId 流程id * _user_id 操作用户id */ function loanAuditReject(string _processId, string _user_id) external onlyOwner returns(bool){ onlyZJRole(_user_id); _log(_processId.empty(), "FinancingFundController loanAudit: _processId is empty"); require(!_processId.empty(), "FinancingFundController loanAudit: _processId is empty"); int256 count = financingProcessStorage.updateCreditSideStatus(_processId, Fund_Audit_Reject); emit LoanAuditResult(count > int256(0)); return count > int256(0); } }
资金方审核放货拒绝 _processId 流程id _user_id 操作用户id/
function confirmAuditReject(string _processId, string _user_id) external onlyOwner returns(bool){ onlyZJRole(_user_id); _log(_processId.empty(), "FinancingFundController fundConfirmAudit: _processId is empty"); require(!_processId.empty(), "FinancingFundController fundConfirmAudit: _processId is empty"); int256 count = financingProcessStorage.updateCreditSideStatus(_processId, Fund_Confirm_Audit_Reject); emit FundConfirmAuditResult(count > int256(0)); return count > int256(0); }
1,752,015
./full_match/5/0xCB3577567d47bcB5891e732993A37a9bcc8Cf1f0/sources/Flyz.sol
Mints `quantity` tokens and transfers them to `to`. Requirements: - `to` cannot be the zero address. - `quantity` must be greater than 0. Emits a {Transfer} event for each mint./ Overflows are incredibly unrealistic. `balance` and `numberMinted` have a maximum limit of 264. `tokenId` has a maximum limit of 2256. Updates: - `balance += quantity`. - `numberMinted += quantity`. We can directly add to the `balance` and `numberMinted`. Updates: - `address` to the owner. - `startTimestamp` to the timestamp of minting. - `burned` to `false`. - `nextInitialized` to `quantity == 1`.
function _mint(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1); _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 tokenId = startTokenId; uint256 end = startTokenId + quantity; do { emit Transfer(address(0), to, tokenId++); } while (tokenId < end); _currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
1,880,829
./full_match/1/0x7d0C7372f38958d9CF5aE6DA2b0794337045559b/sources/contracts/Controller.sol
Allows an existing strategy to be removed from the Spool system. Emits a {StrategyRemoved} event indicating the removed strategy. Requirements: - the strategy must already exist in the contract - the provided strategies array must be vaild or empty strategy the strategy to remove from the system skipDisable flag to skip execution of strategy specific disable (e.g cleanup tasks) function. allStrategies current valid strategies or empty array/ update strategies storage array and hash update can happen using strategies from storage or from calldata
function _removeStrategy( address strategy, bool skipDisable, address[] calldata allStrategies ) private validStrategiesOrEmpty(allStrategies) { require( validStrategy[strategy], "Controller::removeStrategy: Strategy is not registered" ); spool.disableStrategy(strategy, skipDisable); validStrategy[strategy] = false; if (allStrategies.length == 0) { _removeStrategyStorage(strategy); _removeStrategyCalldata(allStrategies, strategy); } emit StrategyRemoved(strategy); }
9,716,454
/** *Submitted for verification at Etherscan.io on 2021-08-11 */ pragma solidity 0.7.6; // SPDX-License-Identifier: MIT /** * @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 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 wasInitializing = initializing; initializing = true; initialized = true; _; initializing = wasInitializing; } /// @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. // MINOR CHANGE HERE: // previous code // uint256 cs; // assembly { cs := extcodesize(address) } // return cs == 0; // current code 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; } /** * @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 virtual 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; } /* 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. */ /** * @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; } } /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } interface IUFragments { function totalSupply() external view returns (uint256); function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256); } interface IOracle { function getData() external returns (uint256, bool); } /** * @title uFragments Monetary Supply Policy * @dev This is an implementation of the uFragments Ideal Money protocol. * uFragments operates symmetrically on expansion and contraction. It will both split and * combine coins to maintain a stable unit price. * * This component regulates the token supply of the uFragments ERC20 token in response to * market oracles. */ contract UFragmentsPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, int256 requestedSupplyAdjustment, uint256 timestampSec ); IUFragments public uFrags; // Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number. // (eg) An oracle value of 1.5e18 it would mean 1 Ample is trading for $1.50. IOracle public marketOracle; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag // Check setRebaseLag comments for more details. // Natural number, no decimal places. uint256 public rebaseLag; // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = uint256(type(int256).max) / MAX_RATE; // target rate 1 uint256 private constant TARGET_RATE = 1 * 10**DECIMALS; // This module orchestrates the rebase execution and downstream notification. address public orchestrator; modifier onlyOrchestrator() { require(msg.sender == orchestrator); _; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase() external onlyOrchestrator { require(inRebaseWindow()); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < block.timestamp); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = block .timestamp .sub(block.timestamp.mod(minRebaseTimeIntervalSec)) .add(rebaseWindowOffsetSec); epoch = epoch.add(1); uint256 targetRate = TARGET_RATE; uint256 exchangeRate; bool rateValid; (exchangeRate, rateValid) = marketOracle.getData(); require(rateValid); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe(); } uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, supplyDelta, block.timestamp); } /** * @notice Sets the reference to the market oracle. * @param marketOracle_ The address of the market oracle contract. */ function setMarketOracle(IOracle marketOracle_) external onlyOwner { marketOracle = marketOracle_; } /** * @notice Sets the reference to the orchestrator. * @param orchestrator_ The address of the orchestrator contract. */ function setOrchestrator(address orchestrator_) external onlyOwner { orchestrator = orchestrator_; } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. DECIMALS fixed point number. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_ ) external onlyOwner { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @notice A multi-chain AMPL interface method. The Ampleforth monetary policy contract * on the base-chain and XC-AmpleController contracts on the satellite-chains * implement this method. It atomically returns two values: * what the current contract believes to be, * the globalAmpleforthEpoch and globalAMPLSupply. * @return globalAmpleforthEpoch The current epoch number. * @return globalAMPLSupply The total supply at the current epoch. */ function globalAmpleforthEpochAndAMPLSupply() external view returns (uint256, uint256) { return (epoch, uFrags.totalSupply()); } /** * @dev ZOS upgradable contract initialization method. * It is called at the time of contract creation to invoke parent class initializers and * initialize the contract's state variables. */ function initialize( address owner_, IUFragments uFrags_ ) public initializer { Ownable.initialize(owner_); // deviationThreshold = 0.05e18 = 5e16 deviationThreshold = 5 * 10**(DECIMALS - 2); rebaseLag = 3; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 72000; // 8PM UTC rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; epoch = 0; uFrags = uFrags_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { return (block.timestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && block.timestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))); } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } // supplyDelta = totalSupply * (rate - targetRate) / targetRate int256 targetRateSigned = targetRate.toInt256Safe(); return uFrags.totalSupply().toInt256Safe().mul(rate.toInt256Safe().sub(targetRateSigned)).div( targetRateSigned ); } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @param targetRate The target exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) internal view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold).div(10**DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } }
ZOS upgradable contract initialization method. It is called at the time of contract creation to invoke parent class initializers and initialize the contract's state variables./ deviationThreshold = 0.05e18 = 5e16
function initialize( address owner_, IUFragments uFrags_ ) public initializer { Ownable.initialize(owner_); deviationThreshold = 5 * 10**(DECIMALS - 2); rebaseLag = 3; minRebaseTimeIntervalSec = 1 days; rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; epoch = 0; uFrags = uFrags_; }
10,522,622
./partial_match/42220/0xCdE5039e3AcB3483aEebEBd59Cf6936056c455D4/sources/Users/pahor/repo/4/celo-monorepo/packages/protocol/contracts/governance/Election.sol
Returns the total votes made for `group`. group The address of the validator group. return The total votes made for `group`./
function getTotalVotesForGroup(address group) public view returns (uint256) { return votes.pending.forGroup[group].total.add(votes.active.forGroup[group].total); }
3,496,800
/** *Submitted for verification at Etherscan.io on 2021-05-26 */ // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: openzeppelin-solidity/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: multi-token-standard/contracts/interfaces/IERC165.sol pragma solidity ^0.5.16; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: multi-token-standard/contracts/utils/SafeMath.sol pragma solidity ^0.5.16; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath#mul: OVERFLOW"); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath#div: DIVISION_BY_ZERO"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath#sub: UNDERFLOW"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath#add: OVERFLOW"); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO"); return a % b; } } // File: multi-token-standard/contracts/interfaces/IERC1155TokenReceiver.sol pragma solidity ^0.5.16; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Whether ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } // File: multi-token-standard/contracts/interfaces/IERC1155.sol pragma solidity ^0.5.16; interface IERC1155 { /****************************************| | Events | |_______________________________________*/ /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount); /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts); /** * @dev MUST emit when an approval is updated */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @dev MUST emit when the URI is updated for a token ID * URIs are defined in RFC 3986 * The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema" */ event URI(string _amount, uint256 indexed _id); /****************************************| | Functions | |_______________________________________*/ /** * @notice Transfers amount of an _id from the _from address to the _to address specified * @dev MUST emit TransferSingle event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if balance of sender for token `_id` is lower than the `_amount` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external; /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev MUST emit TransferBatch event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if length of `_ids` is not the same as length of `_amounts` * MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external; /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @dev MUST emit the ApprovalForAll event on success * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } // File: multi-token-standard/contracts/utils/Address.sol pragma solidity ^0.5.16; /** * Utility library of inline functions on addresses */ library Address { // Default hash for EOA accounts returned by extcodehash bytes32 constant internal ACCOUNT_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract. * @param _address address of the account to check * @return Whether the target address is a contract */ function isContract(address _address) internal view returns (bool) { bytes32 codehash; // 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 or if it has a non-zero code hash or account hash assembly { codehash := extcodehash(_address) } return (codehash != 0x0 && codehash != ACCOUNT_HASH); } } // File: multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol pragma solidity ^0.5.16; /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC165, IERC1155 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping (address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping (address => mapping(address => bool)) internal operators; /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public { require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount <= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, gasleft(), _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR"); require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasleft(), _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount) internal { // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, uint256 _gasLimit, bytes memory _data) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received.gas(_gasLimit)(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, uint256 _gasLimit, bytes memory _data) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived.gas(_gasLimit)(msg.sender, _from, _ids, _amounts, _data); require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public view returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public view returns (uint256[] memory) { require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH"); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /** * INTERFACE_SIGNATURE_ERC1155 = * bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ * bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ * bytes4(keccak256("balanceOf(address,uint256)")) ^ * bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ * bytes4(keccak256("setApprovalForAll(address,bool)")) ^ * bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } } // File: multi-token-standard/contracts/tokens/ERC1155/ERC1155MintBurn.sol pragma solidity ^0.5.16; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, gasleft(), _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, gasleft(), _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn(address _from, uint256 _id, uint256 _amount) internal { //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts) internal { // Number of mints to execute uint256 nBurn = _ids.length; require(nBurn == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH"); // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // File: contracts/ERC1155Tradable.sol pragma solidity ^0.5.2; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC1155Tradable * ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin, like exists(), name(), symbol(), and totalSupply() */ contract ERC1155Tradable is ERC1155MintBurn, Ownable { // Proxy registry address address public proxyRegistryAddress; // Contract name string public name; // Contract symbol string public symbol; mapping(uint256 => uint256) private _supply; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) public { name = _name; symbol = _symbol; proxyRegistryAddress = _proxyRegistryAddress; } /** * @dev Throws if called by any account other than the owner or their proxy */ modifier onlyOwner() { require( _isOwner(_msgSender()), "ERC1155Tradable#onlyOwner: CALLER_IS_NOT_OWNER" ); _; } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return _supply[_id]; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { // Whitelist OpenSea proxy contracts for easy trading. if (_isProxyForUser(_owner, _operator)) { return true; } return super.isApprovedForAll(_owner, _operator); } /** * @dev Mints some amount of tokens to an address * @param _to Address of the future owner of the token * @param _id Token ID to mint * @param _quantity Amount of tokens to mint * @param _data Data to pass if receiver is contract */ function mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) public onlyOwner { _mint(_to, _id, _quantity, _data); } /** * @dev Mint tokens for each id in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _quantities Array of amounts of tokens to mint per id * @param _data Data to pass if receiver is contract */ function batchMint( address _to, uint256[] memory _ids, uint256[] memory _quantities, bytes memory _data ) public onlyOwner { _batchMint(_to, _ids, _quantities, _data); } /** * @dev Burns amount of a given token id * @param _from The address to burn tokens from * @param _id Token ID to burn * @param _quantity Amount to burn */ function burn( address _from, uint256 _id, uint256 _quantity ) public { _supply[_id] = _supply[_id].sub(_quantity); _burn(_from, _id, _quantity); } /** * @dev Burns tokens for each id in _ids * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _quantities Array of the amount to be burned */ function batchBurn( address _from, uint256[] memory _ids, uint256[] memory _quantities ) public { for (uint256 i = 0; i < _ids.length; i++) { uint256 id = _ids[i]; _supply[id] = _supply[id].sub(_quantities[i]); } _batchBurn(_from, _ids, _quantities); } /** * @dev Returns whether the specified token is minted * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function exists(uint256 _id) public view returns (bool) { return _supply[_id] > 0; } function _isOwner(address _address) internal view returns (bool) { return owner() == _address || _isProxyForUser(owner(), _address); } // Overrides ERC1155MintBurn to allow changing birth events to creator transfers, // and to set _supply function _mint( address _to, uint256 _id, uint256 _amount, bytes memory _data ) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); _supply[_id] = _supply[_id].add(_amount); // Origin of token will be the _from parameter address origin = _origin(_id); // Emit event emit TransferSingle(msg.sender, origin, _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(origin, _to, _id, _amount, gasleft(), _data); } // Overrides ERC1155MintBurn to change the batch birth events to creator transfers, and to set _supply function _batchMint( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal { require( _ids.length == _amounts.length, "ERC1155Tradable#batchMint: INVALID_ARRAYS_LENGTH" ); // Number of mints to execute uint256 nMint = _ids.length; // Origin of tokens will be the _from parameter address origin = _origin(_ids[0]); // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance uint256 id = _ids[i]; require( _origin(id) == origin, "ERC1155Tradable#batchMint: MULTIPLE_ORIGINS_NOT_ALLOWED" ); balances[_to][id] = balances[_to][id].add(_amounts[i]); _supply[id] = _supply[id].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, origin, _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived( origin, _to, _ids, _amounts, gasleft(), _data ); } // Override this to change birth events' _from address function _origin( uint256 /* _id */ ) internal view returns (address) { return address(0); } // PROXY HELPER METHODS function _isProxyForUser(address _user, address _address) internal view returns (bool) { return _proxy(_user) == _address; } function _proxy(address _address) internal view returns (address) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); return address(proxyRegistry.proxies(_address)); } } // File: contracts/AssetContract.sol pragma solidity ^0.5.2; /** * @title AssetContract * AssetContract - A contract for easily creating non-fungible assets on OpenSea. */ contract AssetContract is ERC1155Tradable { event URI(string _value, uint256 indexed _id); event PermanentURI(string _value, uint256 indexed _id); uint256 constant TOKEN_SUPPLY_CAP = 1; string public templateURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURI; // Mapping for whether a token URI is set permanently mapping(uint256 => bool) private _isPermanentURI; modifier onlyTokenAmountOwned(address _from, uint256 _id, uint256 _quantity) { require( _ownsTokenAmount(_from, _id, _quantity), "AssetContract#onlyTokenAmountOwned: ONLY_TOKEN_AMOUNT_OWNED_ALLOWED" ); _; } /** * @dev Require the URI to be impermanent */ modifier onlyImpermanentURI(uint256 id) { require(!_isPermanentURI[id], "AssetContract#onlyImpermanentURI: URI_CANNOT_BE_CHANGED"); _; } constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress, string memory _templateURI ) public ERC1155Tradable(_name, _symbol, _proxyRegistryAddress) { if (bytes(_templateURI).length > 0) { setTemplateURI(_templateURI); } } function openSeaVersion() public pure returns (string memory) { return "2.0.3"; } /** * @dev Require _from to own a specified quantity of the token */ function _ownsTokenAmount(address _from, uint256 _id, uint256 _quantity) internal view returns (bool) { return balanceOf(_from, _id) >= _quantity; } /** * Compat for factory interfaces on OpenSea * Indicates that this contract can return balances for * tokens that haven't been minted yet */ function supportsFactoryInterface() public pure returns (bool) { return true; } function setTemplateURI(string memory uri) public onlyOwner { templateURI = uri; } function setURI(uint256 _id, string memory _uri) public onlyOwner onlyImpermanentURI(_id) { _setURI(_id, _uri); } function setPermanentURI(uint256 _id, string memory _uri) public onlyOwner onlyImpermanentURI(_id) { _setPermanentURI(_id, _uri); } function uri(uint256 _id) public view returns (string memory) { string memory tokenUri = _tokenURI[_id]; if (bytes(tokenUri).length != 0) { return tokenUri; } return templateURI; } function balanceOf(address _owner, uint256 _id) public view returns (uint256) { uint256 balance = super.balanceOf(_owner, _id); return _isCreatorOrProxy(_id, _owner) ? balance.add(_remainingSupply(_id)) : balance; } function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) public { uint256 mintedBalance = super.balanceOf(_from, _id); if (mintedBalance < _amount) { // Only mint what _from doesn't already have mint(_to, _id, _amount.sub(mintedBalance), _data); if (mintedBalance > 0) { super.safeTransferFrom(_from, _to, _id, mintedBalance, _data); } } else { super.safeTransferFrom(_from, _to, _id, _amount, _data); } } function safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) public { require( _ids.length == _amounts.length, "AssetContractShared#safeBatchTransferFrom: INVALID_ARRAYS_LENGTH" ); for (uint256 i = 0; i < _ids.length; i++) { safeTransferFrom(_from, _to, _ids[i], _amounts[i], _data); } } function mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) public onlyOwner { require( _quantity <= _remainingSupply(_id), "AssetContract#mint: QUANTITY_EXCEEDS_TOKEN_SUPPLY_CAP" ); _mint(_to, _id, _quantity, _data); } function batchMint( address _to, uint256[] memory _ids, uint256[] memory _quantities, bytes memory _data ) public onlyOwner { for (uint256 i = 0; i < _ids.length; i++) { require( _quantities[i] <= _remainingSupply(_ids[i]), "AssetContract#batchMint: QUANTITY_EXCEEDS_TOKEN_SUPPLY_CAP" ); } _batchMint(_to, _ids, _quantities, _data); } // Overrides ERC1155Tradable burn to check for quantity owned function burn( address _from, uint256 _id, uint256 _quantity ) public onlyTokenAmountOwned(_from, _id, _quantity) { super.burn(_from, _id, _quantity); } // Overrides ERC1155Tradable batchBurn to check for quantity owned function batchBurn( address _from, uint256[] memory _ids, uint256[] memory _quantities ) public { for (uint256 i = 0; i < _ids.length; i++) { require( _ownsTokenAmount(_from, _ids[i], _quantities[i]), "AssetContract#batchBurn: ONLY_TOKEN_AMOUNT_OWNED_ALLOWED" ); } super.batchBurn(_from, _ids, _quantities); } function _mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) internal { super._mint(_to, _id, _quantity, _data); if (_data.length > 1) { _setURI(_id, string(_data)); } } function _isCreatorOrProxy(uint256, address _address) internal view returns (bool) { return _isOwner(_address); } function _remainingSupply(uint256 _id) internal view returns (uint256) { return TOKEN_SUPPLY_CAP.sub(totalSupply(_id)); } // Override ERC1155Tradable for birth events function _origin( uint256 /* _id */ ) internal view returns (address) { return owner(); } function _batchMint( address _to, uint256[] memory _ids, uint256[] memory _quantities, bytes memory _data ) internal { super._batchMint(_to, _ids, _quantities, _data); if (_data.length > 1) { for (uint256 i = 0; i < _ids.length; i++) { _setURI(_ids[i], string(_data)); } } } function _setURI(uint256 _id, string memory _uri) internal { _tokenURI[_id] = _uri; emit URI(_uri, _id); } function _setPermanentURI(uint256 _id, string memory _uri) internal { _isPermanentURI[_id] = true; _setURI(_id, _uri); emit PermanentURI(_uri, _id); } } // File: contracts/TokenIdentifiers.sol pragma solidity ^0.5.2; /* DESIGN NOTES: Token ids are a concatenation of: * creator: hex address of the creator of the token. 160 bits * index: Index for this token (the regular ID), up to 2^56 - 1. 56 bits * supply: Supply cap for this token, up to 2^40 - 1 (1 trillion). 40 bits */ /** * @title TokenIdentifiers * support for authentication and metadata for token ids */ library TokenIdentifiers { using SafeMath for uint256; uint8 constant ADDRESS_BITS = 160; uint8 constant INDEX_BITS = 56; uint8 constant SUPPLY_BITS = 40; uint256 constant SUPPLY_MASK = (uint256(1) << SUPPLY_BITS) - 1; uint256 constant INDEX_MASK = ((uint256(1) << INDEX_BITS) - 1) ^ SUPPLY_MASK; function tokenMaxSupply(uint256 _id) internal pure returns (uint256) { return _id & SUPPLY_MASK; } function tokenIndex(uint256 _id) internal pure returns (uint256) { return _id & INDEX_MASK; } function tokenCreator(uint256 _id) internal pure returns (address) { return address(_id >> (INDEX_BITS + SUPPLY_BITS)); } } // File: contracts/AssetContractShared.sol pragma solidity ^0.5.2; /** * @title NiftyPlanet * NiftyPlanet shared asset contract */ contract NiftyPlanet is AssetContract, ReentrancyGuard { mapping(address => bool) public sharedProxyAddresses; using SafeMath for uint256; using TokenIdentifiers for uint256; event CreatorChanged(uint256 indexed _id, address indexed _creator); mapping(uint256 => address) internal _creatorOverride; /** * @dev Require msg.sender to be the creator of the token id */ modifier creatorOnly(uint256 _id) { require( _isCreatorOrProxy(_id, _msgSender()), "AssetContractShared#creatorOnly: ONLY_CREATOR_ALLOWED" ); _; } /** * @dev Require the caller to own the full supply of the token */ modifier onlyFullTokenOwner(uint256 _id) { require( _ownsTokenAmount(_msgSender(), _id, _id.tokenMaxSupply()), "AssetContractShared#onlyFullTokenOwner: ONLY_FULL_TOKEN_OWNER_ALLOWED" ); _; } constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress, string memory _templateURI ) public AssetContract(_name, _symbol, _proxyRegistryAddress, _templateURI) {} /** * @dev Allows owner to change the proxy registry */ function setProxyRegistryAddress(address _address) public onlyOwner { proxyRegistryAddress = _address; } /** * @dev Allows owner to add a shared proxy address */ function addSharedProxyAddress(address _address) public onlyOwner { sharedProxyAddresses[_address] = true; } /** * @dev Allows owner to remove a shared proxy address */ function removeSharedProxyAddress(address _address) public onlyOwner { delete sharedProxyAddresses[_address]; } function mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) public nonReentrant() { _requireMintable(_msgSender(), _id, _quantity); _mint(_to, _id, _quantity, _data); } function batchMint( address _to, uint256[] memory _ids, uint256[] memory _quantities, bytes memory _data ) public nonReentrant() { for (uint256 i = 0; i < _ids.length; i++) { _requireMintable(_msgSender(), _ids[i], _quantities[i]); } _batchMint(_to, _ids, _quantities, _data); } ///////////////////////////////// // CONVENIENCE CREATOR METHODS // ///////////////////////////////// /** * @dev Will update the URI for the token * @param _id The token ID to update. msg.sender must be its creator, the uri must be impermanent, * and the creator must own all of the token supply * @param _uri New URI for the token. */ function setURI(uint256 _id, string memory _uri) public creatorOnly(_id) onlyImpermanentURI(_id) onlyFullTokenOwner(_id) { _setURI(_id, _uri); } /** * @dev setURI, but permanent */ function setPermanentURI(uint256 _id, string memory _uri) public creatorOnly(_id) onlyImpermanentURI(_id) onlyFullTokenOwner(_id) { _setPermanentURI(_id, _uri); } /** * @dev Change the creator address for given token * @param _to Address of the new creator * @param _id Token IDs to change creator of */ function setCreator(uint256 _id, address _to) public creatorOnly(_id) { require( _to != address(0), "AssetContractShared#setCreator: INVALID_ADDRESS." ); _creatorOverride[_id] = _to; emit CreatorChanged(_id, _to); } /** * @dev Get the creator for a token * @param _id The token id to look up */ function creator(uint256 _id) public view returns (address) { if (_creatorOverride[_id] != address(0)) { return _creatorOverride[_id]; } else { return _id.tokenCreator(); } } /** * @dev Get the maximum supply for a token * @param _id The token id to look up */ function maxSupply(uint256 _id) public pure returns (uint256) { return _id.tokenMaxSupply(); } // Override ERC1155Tradable for birth events function _origin(uint256 _id) internal view returns (address) { return _id.tokenCreator(); } function _requireMintable( address _address, uint256 _id, uint256 _amount ) internal view { require( _isCreatorOrProxy(_id, _address), "AssetContractShared#_requireMintable: ONLY_CREATOR_ALLOWED" ); require( _remainingSupply(_id) >= _amount, "AssetContractShared#_requireMintable: SUPPLY_EXCEEDED" ); } function _remainingSupply(uint256 _id) internal view returns (uint256) { return maxSupply(_id).sub(totalSupply(_id)); } function _isCreatorOrProxy(uint256 _id, address _address) internal view returns (bool) { address creator_ = creator(_id); return creator_ == _address || _isProxyForUser(creator_, _address); } // Overrides ERC1155Tradable to allow a shared proxy address function _isProxyForUser(address _user, address _address) internal view returns (bool) { if (sharedProxyAddresses[_address]) { return true; } return super._isProxyForUser(_user, _address); } }
Burns amount of a given token id _from The address to burn tokens from _id Token ID to burn _quantity Amount to burn/
function burn( address _from, uint256 _id, uint256 _quantity ) public { _supply[_id] = _supply[_id].sub(_quantity); _burn(_from, _id, _quantity); }
6,668,219
./full_match/84531/0x1FE6cAf7C5A873F74B5693a32C1C95B52F287993/sources/src/token/ERC721/base/ERC721ABase.sol
@inheritdoc IERC721ABase/
function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transferFrom(from, to, tokenId); }
11,529,798
./full_match/43113/0x79e6aaCD8986c9797B3f8AfbeAE04130Da184Cd4/sources/contracts/Oracle.sol
this is used so users do not have to delegate someone else to monitor the contract 24/7 86400 is seconds in a day, and 3600 is seconds in an hour restricts contract submission to between 5am-8pm in summer, 6am-9pm in winter
function hourOfDay() public view returns (uint hour1) { hour1 = (block.timestamp - 7600) % 86400 / 3600; }
7,168,395
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol"; import "./GoodAaveStakingV2.sol"; import "../../Interfaces.sol"; /** * @title Staking contract that donates earned interest to the DAO * allowing stakers to deposit Token * or withdraw their stake in Token * the contracts buy cToken and can transfer the daily interest to the DAO */ contract AaveStakingFactory { using ClonesUpgradeable for address; address public impl = address(new GoodAaveStakingV2()); event Deployed(address proxy, address token, address impl); function clone( address _impl, ERC20 token, bytes32 paramsHash ) internal returns (GoodAaveStakingV2) { address deployed = address(_impl).cloneDeterministic( keccak256(abi.encodePacked(address(token), paramsHash)) ); emit Deployed(deployed, address(token), _impl); return GoodAaveStakingV2(deployed); } function cloneAndInit( ERC20 token, address _lendingPool, INameService _ns, uint64 _maxRewardThreshold, address _tokenUsdOracle, IAaveIncentivesController _incentiveController, address _aaveUSDOracle, address[] memory _tokenToDaiSwapPath ) public { cloneAndInit( impl, token, _lendingPool, _ns, _maxRewardThreshold, _tokenUsdOracle, _incentiveController, _aaveUSDOracle, _tokenToDaiSwapPath ); } /** @dev Function to clone Staking contract and initialize new one with new token @param token Staking token to use in staking contract @param _lendingPool address of the lending Pool of AAVE Protocol @param _ns NameService that holds whole necessary addresses @param _maxRewardThreshold Block numbers that need to pass in order to user would get their rewards with 1x multiplier instead of 0.5x @param _tokenUsdOracle address of the TOKEN/USD oracle @param _incentiveController Incentive Controller of AAVE protocol in order to claim rewards from AAVE @param _aaveUSDOracle address of the AAVE/USD oracle */ function cloneAndInit( address _impl, ERC20 token, address _lendingPool, INameService _ns, uint64 _maxRewardThreshold, address _tokenUsdOracle, IAaveIncentivesController _incentiveController, address _aaveUSDOracle, address[] memory _tokenToDaiSwapPath ) public { GoodAaveStakingV2 deployed = clone( _impl, token, keccak256( abi.encodePacked( address(_lendingPool), address(_ns), _maxRewardThreshold, _tokenUsdOracle, address(_incentiveController), _aaveUSDOracle ) ) ); deployed.init( address(token), address(_lendingPool), _ns, string(abi.encodePacked("GoodAaveStakingV2 ", token.name())), string(abi.encodePacked("ga", token.symbol())), _maxRewardThreshold, _tokenUsdOracle, _incentiveController, _aaveUSDOracle, _tokenToDaiSwapPath ); } function predictAddress( address _impl, ERC20 token, bytes32 paramsHash ) public view returns (address) { return address(_impl).predictDeterministicAddress( keccak256(abi.encodePacked(address(token), paramsHash)) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library ClonesUpgradeable { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../SimpleStakingV2.sol"; import "../../Interfaces.sol"; import "../../utils/DataTypes.sol"; import "../UniswapV2SwapHelper.sol"; /** * @title Staking contract that donates earned interest to the DAO * allowing stakers to deposit Token * or withdraw their stake in Token * the contracts buy cToken and can transfer the daily interest to the DAO */ contract GoodAaveStakingV2 is SimpleStakingV2 { using UniswapV2SwapHelper for IHasRouter; // Address of the TOKEN/USD oracle from chainlink address public tokenUsdOracle; //LendingPool of aave ILendingPool public lendingPool; //Address of the AaveIncentivesController IAaveIncentivesController public incentiveController; //address of the AAVE/USD oracle address public aaveUSDOracle; // Gas cost to collect interest from this staking contract uint32 public collectInterestGasCost; // Gas cost to claim stkAave rewards uint32 public stkAaveClaimGasCost; address[] public tokenToDaiSwapPath; /** * @param _token Token to swap DEFI token * @param _lendingPool LendingPool address * @param _ns Address of the NameService * @param _tokenName Name of the staking token which will be provided to staker for their staking share * @param _tokenSymbol Symbol of the staking token which will be provided to staker for their staking share * @param _tokenSymbol Determines blocks to pass for 1x Multiplier * @param _tokenUsdOracle address of the TOKEN/USD oracle * @param _incentiveController Aave incentive controller which provides AAVE rewards * @param _aaveUSDOracle address of the AAVE/USD oracle */ function init( address _token, address _lendingPool, INameService _ns, string memory _tokenName, string memory _tokenSymbol, uint64 _maxRewardThreshold, address _tokenUsdOracle, IAaveIncentivesController _incentiveController, address _aaveUSDOracle, address[] memory _tokenToDaiSwapPath ) public { lendingPool = ILendingPool(_lendingPool); DataTypes.ReserveData memory reserve = lendingPool.getReserveData(_token); initialize( _token, reserve.aTokenAddress, _ns, _tokenName, _tokenSymbol, _maxRewardThreshold ); require( _tokenToDaiSwapPath[0] == _token && _tokenToDaiSwapPath[_tokenToDaiSwapPath.length - 1] == nameService.getAddress("DAI"), "invalid _tokenToDaiSwapPath" ); tokenToDaiSwapPath = _tokenToDaiSwapPath; //above initialize going to revert on second call, so this is safe tokenUsdOracle = _tokenUsdOracle; incentiveController = _incentiveController; aaveUSDOracle = _aaveUSDOracle; collectInterestGasCost = 250000; stkAaveClaimGasCost = 50000; _approveTokens(); } /** * @dev stake some Token * @param _amount of Token to stake */ function mintInterestToken(uint256 _amount) internal override { lendingPool.deposit(address(token), _amount, address(this), 0); } /** * @dev redeem Token from aave * @param _amount of token to redeem in Token */ function redeem(uint256 _amount) internal override { uint256 withdrawnAmount = lendingPool.withdraw( address(token), _amount, address(this) ); require(withdrawnAmount > 0, "Withdrawn amount should be bigger than zero"); } /** * @dev Function to redeem aToken for DAI, so reserve knows how to handle it. (reserve can handle dai or cdai) * also transfers stkaave to reserve * @dev _amount of token in iToken * @dev _recipient recipient of the DAI * @return actualTokenGains amount of token redeemed for dai, actualRewardTokenGains amount of reward token earned, daiAmount total dai received */ function redeemUnderlyingToDAI(uint256 _amount, address _recipient) internal override returns ( uint256 actualTokenGains, uint256 actualRewardTokenGains, uint256 daiAmount ) { //out of requested interests to withdraw how much is it safe to swap actualTokenGains = IHasRouter(this).maxSafeTokenAmount( address(token), tokenToDaiSwapPath[1], _amount, maxLiquidityPercentageSwap ); lendingPool.withdraw(address(token), actualTokenGains, address(this)); actualTokenGains = token.balanceOf(address(this)); address[] memory tokenAddress = new address[](1); tokenAddress[0] = address(iToken); actualRewardTokenGains = incentiveController.claimRewards( tokenAddress, type(uint256).max, avatar ); if (actualTokenGains > 0) { daiAmount = IHasRouter(this).swap( tokenToDaiSwapPath, actualTokenGains, 0, _recipient ); } } /** * @dev returns decimals of token. */ function tokenDecimal() internal view override returns (uint256) { ERC20 token = ERC20(address(token)); return uint256(token.decimals()); } /** * @dev returns decimals of interest token. */ function iTokenDecimal() internal view override returns (uint256) { ERC20 aToken = ERC20(address(iToken)); return uint256(aToken.decimals()); } /** * @dev Function that calculates current interest gains of this staking contract * @param _returnTokenBalanceInUSD determine return token balance of staking contract in USD * @param _returnTokenGainsInUSD determine return token gains of staking contract in USD * @return iTokenGains gains in iToken, tokenGains gains in token, tokenBalance current balance , balanceInUSD, tokenGainsInUSD */ function currentGains( bool _returnTokenBalanceInUSD, bool _returnTokenGainsInUSD ) public view override returns ( uint256 iTokenGains, uint256 tokenGains, uint256 tokenBalance, uint256 balanceInUSD, uint256 tokenGainsInUSD ) { ERC20 aToken = ERC20(address(iToken)); tokenBalance = aToken.balanceOf(address(this)); balanceInUSD = _returnTokenBalanceInUSD ? getTokenValueInUSD(tokenUsdOracle, tokenBalance, token.decimals()) : 0; address[] memory tokenAddress = new address[](1); tokenAddress[0] = address(token); if (tokenBalance <= totalProductivity) { return (0, 0, tokenBalance, balanceInUSD, 0); } iTokenGains = tokenGains = tokenBalance - totalProductivity; tokenGainsInUSD = _returnTokenGainsInUSD ? getTokenValueInUSD(tokenUsdOracle, tokenGains, token.decimals()) : 0; } /** * @dev Function to get interest transfer cost for this particular staking contract */ function getGasCostForInterestTransfer() external view override returns (uint32) { address[] memory tokenAddress = new address[](1); tokenAddress[0] = address(iToken); uint256 stkAaaveBalance = incentiveController.getRewardsBalance( tokenAddress, address(this) ); if (stkAaaveBalance > 0) return collectInterestGasCost + stkAaveClaimGasCost; return collectInterestGasCost; } /** * @dev Set Gas cost to interest collection for this contract * @param _collectInterestGasCost Gas cost to collect interest * @param _rewardTokenCollectCost gas cost to collect reward tokens */ function setcollectInterestGasCostParams( uint32 _collectInterestGasCost, uint32 _rewardTokenCollectCost ) external { _onlyAvatar(); collectInterestGasCost = _collectInterestGasCost; stkAaveClaimGasCost = _rewardTokenCollectCost; } /** * @dev Calculates worth of given amount of iToken in Token * @param _amount Amount of token to calculate worth in Token * @return Worth of given amount of token in Token */ function iTokenWorthInToken(uint256 _amount) internal view override returns (uint256) { return _amount; // since aToken is peg to Token 1:1 return exact amount } function _approveTokens() internal { address uniswapRouter = nameService.getAddress("UNISWAP_ROUTER"); token.approve(uniswapRouter, type(uint256).max); token.approve(address(lendingPool), type(uint256).max); // approve the transfers to defi protocol as much as possible in order to save gas } } // SPDX-License-Identifier: MIT import { DataTypes } from "./utils/DataTypes.sol"; pragma solidity >=0.8.0; pragma experimental ABIEncoderV2; interface ERC20 { function balanceOf(address addr) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function decimals() external view returns (uint8); function mint(address to, uint256 mintAmount) external returns (uint256); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); event Transfer(address indexed from, address indexed to, uint256 amount); event Transfer( address indexed from, address indexed to, uint256 amount, bytes data ); } interface cERC20 is ERC20 { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 mintAmount) external returns (uint256); function redeem(uint256 mintAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } interface IGoodDollar is ERC20 { function getFees(uint256 value) external view returns (uint256, bool); function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function renounceMinter() external; function addMinter(address minter) external; function isMinter(address minter) external view returns (bool); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool); function formula() external view returns (address); } interface IERC2917 is ERC20 { /// @dev This emit when interests amount per block is changed by the owner of the contract. /// It emits with the old interests amount and the new interests amount. event InterestRatePerBlockChanged(uint256 oldValue, uint256 newValue); /// @dev This emit when a users' productivity has changed /// It emits with the user's address and the the value after the change. event ProductivityIncreased(address indexed user, uint256 value); /// @dev This emit when a users' productivity has changed /// It emits with the user's address and the the value after the change. event ProductivityDecreased(address indexed user, uint256 value); /// @dev Return the current contract's interests rate per block. /// @return The amount of interests currently producing per each block. function interestsPerBlock() external view returns (uint256); /// @notice Change the current contract's interests rate. /// @dev Note the best practice will be restrict the gross product provider's contract address to call this. /// @return The true/fase to notice that the value has successfully changed or not, when it succeed, it will emite the InterestRatePerBlockChanged event. function changeInterestRatePerBlock(uint256 value) external returns (bool); /// @notice It will get the productivity of given user. /// @dev it will return 0 if user has no productivity proved in the contract. /// @return user's productivity and overall productivity. function getProductivity(address user) external view returns (uint256, uint256); /// @notice increase a user's productivity. /// @dev Note the best practice will be restrict the callee to prove of productivity's contract address. /// @return true to confirm that the productivity added success. function increaseProductivity(address user, uint256 value) external returns (bool); /// @notice decrease a user's productivity. /// @dev Note the best practice will be restrict the callee to prove of productivity's contract address. /// @return true to confirm that the productivity removed success. function decreaseProductivity(address user, uint256 value) external returns (bool); /// @notice take() will return the interests that callee will get at current block height. /// @dev it will always calculated by block.number, so it will change when block height changes. /// @return amount of the interests that user are able to mint() at current block height. function take() external view returns (uint256); /// @notice similar to take(), but with the block height joined to calculate return. /// @dev for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interests. /// @return amount of interests and the block height. function takeWithBlock() external view returns (uint256, uint256); /// @notice mint the avaiable interests to callee. /// @dev once it mint, the amount of interests will transfer to callee's address. /// @return the amount of interests minted. function mint() external returns (uint256); } interface Staking { struct Staker { // The staked DAI amount uint256 stakedDAI; // The latest block number which the // staker has staked tokens uint256 lastStake; } function stakeDAI(uint256 amount) external; function withdrawStake() external; function stakers(address staker) external view returns (Staker memory); } interface Uniswap { function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function WETH() external pure returns (address); function factory() external pure returns (address); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountOut( uint256 amountI, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountsOut(uint256 amountIn, address[] memory path) external pure returns (uint256[] memory amounts); } interface UniswapFactory { function getPair(address tokenA, address tokenB) external view returns (address); } interface UniswapPair { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); } interface Reserve { function buy( address _buyWith, uint256 _tokenAmount, uint256 _minReturn ) external returns (uint256); } interface IIdentity { function isWhitelisted(address user) external view returns (bool); function addWhitelistedWithDID(address account, string memory did) external; function removeWhitelisted(address account) external; function addIdentityAdmin(address account) external returns (bool); function setAvatar(address _avatar) external; function isIdentityAdmin(address account) external view returns (bool); function owner() external view returns (address); event WhitelistedAdded(address user); } interface IUBIScheme { function currentDay() external view returns (uint256); function periodStart() external view returns (uint256); function hasClaimed(address claimer) external view returns (bool); } interface IFirstClaimPool { function awardUser(address user) external returns (uint256); function claimAmount() external view returns (uint256); } interface ProxyAdmin { function getProxyImplementation(address proxy) external view returns (address); function getProxyAdmin(address proxy) external view returns (address); function upgrade(address proxy, address implementation) external; function owner() external view returns (address); function transferOwnership(address newOwner) external; } /** * @dev Interface for chainlink oracles to obtain price datas */ 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 latestAnswer() external view returns (int256); } /** @dev interface for AAVE lending Pool */ interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev 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); } interface IDonationStaking { function stakeDonations() external payable; } interface INameService { function getAddress(string memory _name) external view returns (address); } interface IAaveIncentivesController { /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); } interface IGoodStaking { function collectUBIInterest(address recipient) external returns ( uint256, uint256, uint256 ); function iToken() external view returns (address); function currentGains( bool _returnTokenBalanceInUSD, bool _returnTokenGainsInUSD ) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function getRewardEarned(address user) external view returns (uint256); function getGasCostForInterestTransfer() external view returns (uint256); function rewardsMinted( address user, uint256 rewardsPerBlock, uint256 blockStart, uint256 blockEnd ) external returns (uint256); } interface IHasRouter { function getRouter() external view returns (Uniswap); } interface IAdminWallet { function addAdmins(address payable[] memory _admins) external; function removeAdmins(address[] memory _admins) external; function owner() external view returns (address); function transferOwnership(address _owner) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../Interfaces.sol"; import "../DAOStackInterfaces.sol"; import "../utils/NameService.sol"; import "../utils/DAOContract.sol"; import "./GoodFundManager.sol"; import "./BaseShareFieldV2.sol"; import "../governance/StakersDistribution.sol"; import "./UniswapV2SwapHelper.sol"; /** * @title Staking contract that donates earned interest to the DAO * allowing stakers to deposit Tokens * or withdraw their stake in Tokens * the FundManager can request to receive the interest */ abstract contract SimpleStakingV2 is ERC20Upgradeable, DAOContract, BaseShareFieldV2, ReentrancyGuardUpgradeable, IHasRouter { // Token address ERC20 public token; // Interest Token address ERC20 public iToken; // emergency pause bool public isPaused; //max percentage of token/dai pool liquidity to swap to DAI when collecting interest out of 100000 uint24 public maxLiquidityPercentageSwap = 300; //0.3% uint256 public lockedUSDValue; /** * @dev Emitted when `staker` stake `value` tokens of `token` */ event Staked(address indexed staker, address token, uint256 value); /** * @dev Emitted when `staker` withdraws their stake `value` tokens and contracts balance will * be reduced to`remainingBalance`. */ event StakeWithdraw(address indexed staker, address token, uint256 value); /** * @dev Emitted when fundmanager transfers intrest collected from defi protrocol. * `recipient` will receive `intrestTokenValue` as intrest. */ event InterestCollected( address recipient, uint256 iTokenGains, // interest accrued uint256 tokenGains, // interest worth in underlying token value uint256 actualTokenRedeemed, //actual token redeemed in uniswap (max 0.3% of liquidity) to DAI uint256 actualRewardTokenEarned, //actual reward token earned uint256 interestCollectedInDAI //actual dai sent to the reserve as interest from converting token and optionally reward token in uniswap ); /** * @dev Constructor * @param _token The address of Token * @param _iToken The address of Interest Token * @param _ns The address of the INameService contract * @param _tokenName The name of the staking token * @param _tokenSymbol The symbol of the staking token * @param _maxRewardThreshold the blocks that should pass to get 1x reward multiplier */ function initialize( address _token, address _iToken, INameService _ns, string memory _tokenName, string memory _tokenSymbol, uint64 _maxRewardThreshold ) public virtual initializer { setDAO(_ns); token = ERC20(_token); iToken = ERC20(_iToken); __ERC20_init(_tokenName, _tokenSymbol); require(token.decimals() <= 18, "decimals"); tokenDecimalDifference = 18 - token.decimals(); maxMultiplierThreshold = _maxRewardThreshold; } function setMaxLiquidityPercentageSwap(uint24 _maxPercentage) public virtual { _onlyAvatar(); maxLiquidityPercentageSwap = _maxPercentage; } /** * @dev Calculates worth of given amount of iToken in Token * @param _amount Amount of iToken to calculate worth in Token * @return Worth of given amount of iToken in Token */ function iTokenWorthInToken(uint256 _amount) internal view virtual returns (uint256); /** * @dev Get gas cost for interest transfer so can be used in the calculation of collectable interest for particular gas amount * @return returns hardcoded gas cost */ function getGasCostForInterestTransfer() external view virtual returns (uint32); /** * @dev Returns decimal value for token. */ function tokenDecimal() internal view virtual returns (uint256); /** * @dev Returns decimal value for intrest token. */ function iTokenDecimal() internal view virtual returns (uint256); /** * @dev Redeem invested tokens from defi protocol. * @param _amount tokens to be redeemed. */ function redeem(uint256 _amount) internal virtual; /** * @dev Redeem invested underlying tokens from defi protocol and exchange into DAI * @param _amount tokens to be redeemed * @return amount of token swapped to dai, amount of reward token swapped to dai, total dai */ function redeemUnderlyingToDAI(uint256 _amount, address _recipient) internal virtual returns ( uint256, uint256, uint256 ); /** * @dev Invests staked tokens to defi protocol. * @param _amount tokens staked. */ function mintInterestToken(uint256 _amount) internal virtual; /** * @dev Function that calculates current interest gains of this staking contract * @param _returnTokenBalanceInUSD determine return token balance of staking contract in USD * @param _returnTokenGainsInUSD determine return token gains of staking contract in USD * @return return gains in itoken,Token and worth of total locked Tokens,token balance in USD (8 decimals),token Gains in USD (8 decimals) */ function currentGains( bool _returnTokenBalanceInUSD, bool _returnTokenGainsInUSD ) public view virtual returns ( uint256, uint256, uint256, uint256, uint256 ); /** * @dev Allows a staker to deposit Tokens. Notice that `approve` is * needed to be executed before the execution of this method. * Can be executed only when the contract is not paused. * @param _amount The amount of Token or iToken to stake (it depends on _inInterestToken parameter) * @param _donationPer The % of interest staker want to donate. * @param _inInterestToken specificy if stake in iToken or Token */ function stake( uint256 _amount, uint256 _donationPer, bool _inInterestToken ) external virtual nonReentrant { require(isPaused == false, "Staking is paused"); require(_donationPer == 0 || _donationPer == 100, "donationPer"); require(_amount > 0, "amount"); require( (_inInterestToken ? iToken : token).transferFrom( _msgSender(), address(this), _amount ), "approve" ); _amount = _inInterestToken ? iTokenWorthInToken(_amount) : _amount; if (_inInterestToken == false) { mintInterestToken(_amount); //mint iToken } _mint(_msgSender(), _amount); // mint Staking token for staker ( uint32 rewardsPerBlock, uint64 blockStart, uint64 blockEnd, ) = GoodFundManager(nameService.getAddress("FUND_MANAGER")) .rewardsForStakingContract(address(this)); _increaseProductivity( _msgSender(), _amount, rewardsPerBlock, blockStart, blockEnd, _donationPer ); (, , , uint256 lockedValueInUSD, ) = currentGains(true, false); lockedUSDValue = lockedValueInUSD; //notify GDAO distrbution for stakers StakersDistribution sd = StakersDistribution( nameService.getAddress("GDAO_STAKERS") ); if (address(sd) != address(0)) { sd.userStaked(_msgSender(), _convertValueTo18Decimals(_amount)); } emit Staked(_msgSender(), address(token), _amount); } /** * @dev Withdraws the sender staked Token. * @param _amount Amount to withdraw in Token or iToken * @param _inInterestToken if true _amount is in iToken and also returned in iToken other wise use Token */ function withdrawStake(uint256 _amount, bool _inInterestToken) external virtual nonReentrant { uint256 tokenWithdraw; if (_inInterestToken) { uint256 tokenWorth = iTokenWorthInToken(_amount); require(iToken.transfer(_msgSender(), _amount), "iWithdraw"); tokenWithdraw = _amount = tokenWorth; } else { tokenWithdraw = _amount; redeem(tokenWithdraw); //this is required for redeem precision loss uint256 tokenActual = token.balanceOf(address(this)); if (tokenActual < tokenWithdraw) { tokenWithdraw = tokenActual; } require(token.transfer(_msgSender(), tokenWithdraw), "withdraw"); } GoodFundManager fm = GoodFundManager( nameService.getAddress("FUND_MANAGER") ); (, , , uint256 lockedValueInUSD, ) = currentGains(true, false); lockedUSDValue = lockedValueInUSD; //this will revert in case user doesnt have enough productivity to withdraw _amount, as productivity=staking tokens amount _burn(msg.sender, _amount); // burn their staking tokens (uint32 rewardsPerBlock, uint64 blockStart, uint64 blockEnd, ) = fm .rewardsForStakingContract(address(this)); _decreaseProductivity( _msgSender(), _amount, rewardsPerBlock, blockStart, blockEnd ); fm.mintReward(nameService.getAddress("CDAI"), _msgSender()); // send rewards to user and use cDAI address since reserve in cDAI //notify GDAO distrbution for stakers StakersDistribution sd = StakersDistribution( nameService.getAddress("GDAO_STAKERS") ); if (address(sd) != address(0)) { sd.userWithdraw(_msgSender(), _convertValueTo18Decimals(_amount)); } emit StakeWithdraw(msg.sender, address(token), tokenWithdraw); } /** * @dev withdraw staker G$ rewards + GDAO rewards * withdrawing rewards resets the multiplier! so if user just want GDAO he should use claimReputation() */ function withdrawRewards() external nonReentrant { GoodFundManager(nameService.getAddress("FUND_MANAGER")).mintReward( nameService.getAddress("CDAI"), _msgSender() ); // send rewards to user and use cDAI address since reserve in cDAI claimReputation(); } /** * @dev withdraw staker GDAO rewards */ function claimReputation() public { //claim reputation rewards StakersDistribution sd = StakersDistribution( nameService.getAddress("GDAO_STAKERS") ); if (address(sd) != address(0)) { address[] memory contracts = new address[](1); contracts[0] = (address(this)); sd.claimReputation(_msgSender(), contracts); } } /** * @dev notify stakersdistribution when user performs transfer operation */ function _transfer( address _from, address _to, uint256 _value ) internal override { super._transfer(_from, _to, _value); StakersDistribution sd = StakersDistribution( nameService.getAddress("GDAO_STAKERS") ); ( uint32 rewardsPerBlock, uint64 blockStart, uint64 blockEnd, ) = GoodFundManager(nameService.getAddress("FUND_MANAGER")) .rewardsForStakingContract(address(this)); _decreaseProductivity(_from, _value, rewardsPerBlock, blockStart, blockEnd); _increaseProductivity( _to, _value, rewardsPerBlock, blockStart, blockEnd, 0 ); if (address(sd) != address(0)) { uint256 _convertedValue = _convertValueTo18Decimals(_value); sd.userWithdraw(_from, _convertedValue); sd.userStaked(_to, _convertedValue); } } function _convertValueTo18Decimals(uint256 _amount) internal view returns (uint256 amountInEighteenDecimals) { amountInEighteenDecimals = token.decimals() == 18 ? _amount : _amount * 10**(18 - token.decimals()); } // @dev To find difference in token's decimal and iToken's decimal // @return difference in decimals. // @return true if token's decimal is more than iToken's function tokenDecimalPrecision() internal view returns (uint256, bool) { uint256 _tokenDecimal = tokenDecimal(); uint256 _iTokenDecimal = iTokenDecimal(); uint256 decimalDifference = _tokenDecimal > _iTokenDecimal ? _tokenDecimal - _iTokenDecimal : _iTokenDecimal - _tokenDecimal; return (decimalDifference, _tokenDecimal > _iTokenDecimal); } /** * @dev Collects gained interest by fundmanager. * @param _recipient The recipient of cDAI gains * @return actualTokenRedeemed actualRewardTokenRedeemed actualDai collected interest from token, * collected interest from reward token, total DAI received from swapping token+reward token */ function collectUBIInterest(address _recipient) public virtual returns ( uint256 actualTokenRedeemed, uint256 actualRewardTokenRedeemed, uint256 actualDai ) { _canMintRewards(); (uint256 iTokenGains, uint256 tokenGains, , , ) = currentGains( false, false ); ( actualTokenRedeemed, actualRewardTokenRedeemed, actualDai ) = redeemUnderlyingToDAI(iTokenGains, _recipient); emit InterestCollected( _recipient, iTokenGains, tokenGains, actualTokenRedeemed, actualRewardTokenRedeemed, actualDai ); } /** * @dev making the contract inactive * NOTICE: this could theoretically result in future interest earned in cdai to remain locked */ function pause(bool _isPaused) public { _onlyAvatar(); isPaused = _isPaused; } /** * @dev method to recover any stuck ERC20 tokens (ie compound COMP) * @param _token the ERC20 token to recover */ function recover(ERC20 _token) public { _onlyAvatar(); uint256 toWithdraw = _token.balanceOf(address(this)); // recover left iToken(stakers token) only when all stakes have been withdrawn if (address(_token) == address(iToken)) { require(totalProductivity == 0 && isPaused, "recover"); } require(_token.transfer(address(avatar), toWithdraw), "transfer"); } /** @dev function calculate Token price in USD @param _oracle chainlink oracle usd/token oralce @param _amount Amount of Token to calculate worth of it @param _decimals decimals of Token @return Returns worth of Tokens in USD */ function getTokenValueInUSD( address _oracle, uint256 _amount, uint256 _decimals ) public view returns (uint256) { AggregatorV3Interface tokenPriceOracle = AggregatorV3Interface(_oracle); int256 tokenPriceinUSD = tokenPriceOracle.latestAnswer(); return (uint256(tokenPriceinUSD) * _amount) / (10**_decimals); // tokenPriceinUSD in 8 decimals and _amount is in Token's decimals so we divide it to Token's decimal at the end to reduce 8 decimals back } function _canMintRewards() internal view override { require(_msgSender() == nameService.getAddress("FUND_MANAGER"), "fund"); } function decimals() public view virtual override returns (uint8) { return token.decimals(); } /** * @param _staker account to get rewards status for * @return (minted, pending) in G$ 2 decimals */ function getUserMintedAndPending(address _staker) external view returns (uint256, uint256) { ( uint32 rewardsPerBlock, uint64 blockStart, uint64 blockEnd, ) = GoodFundManager(nameService.getAddress("FUND_MANAGER")) .rewardsForStakingContract(address(this)); uint256 pending = getUserPendingReward( _staker, rewardsPerBlock, blockStart, blockEnd ); //divide by 1e16 to return in 2 decimals return (users[_staker].rewardMinted / 1e16, pending / 1e16); } function getRouter() public view override returns (Uniswap) { return Uniswap(nameService.getAddress("UNISWAP_ROUTER")); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } enum InterestRateMode { NONE, STABLE, VARIABLE } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../utils/DAOContract.sol"; import "../Interfaces.sol"; library UniswapV2SwapHelper { /** *@dev Helper to calculate percentage out of token liquidity in pool that is safe to exchange against sandwich attack. * also checks if token->eth has better safe limit, so perhaps doing tokenA->eth->tokenB is better than tokenA->tokenB * in that case it could be that eth->tokenB can be attacked because we dont know if eth received for tokenA->eth is less than _maxPercentage of the liquidity in * eth->tokenB. In our use case it is always eth->dai so either it will be safe or very minimal *@param _inToken address of token we are swapping *@param _outToken address of swap result token *@param _inTokenAmount amount of in token required to swap *@param _maxLiquidityPercentageSwap max percentage of liquidity to swap to token * when swapping tokens and this value is out of 100000 so for example if you want to set it to 0.3 you need set it to 300 */ function maxSafeTokenAmount( IHasRouter _iHasRouter, address _inToken, address _outToken, uint256 _inTokenAmount, uint256 _maxLiquidityPercentageSwap ) public view returns (uint256 safeAmount) { Uniswap uniswap = _iHasRouter.getRouter(); address wETH = uniswap.WETH(); _inToken = _inToken == address(0x0) ? wETH : _inToken; _outToken = _outToken == address(0x0) ? wETH : _outToken; UniswapPair pair = UniswapPair( UniswapFactory(uniswap.factory()).getPair(_inToken, _outToken) ); (uint112 reserve0, uint112 reserve1, ) = pair.getReserves(); uint112 reserve = reserve0; if (_inToken == pair.token1()) { reserve = reserve1; } safeAmount = (reserve * _maxLiquidityPercentageSwap) / 100000; return safeAmount < _inTokenAmount ? safeAmount : _inTokenAmount; } /** @dev Helper to swap tokens in the Uniswap *@param _path the buy path *@param _tokenAmount token amount to swap *@param _minTokenReturn minimum token amount to get in swap transaction *@param _receiver receiver of tokens after swap transaction * */ function swap( IHasRouter _iHasRouter, address[] memory _path, uint256 _tokenAmount, uint256 _minTokenReturn, address _receiver ) internal returns (uint256 swapResult) { Uniswap uniswapContract = _iHasRouter.getRouter(); uint256[] memory result; if (_path[0] == address(0x0)) { _path[0] = uniswapContract.WETH(); result = uniswapContract.swapExactETHForTokens{ value: _tokenAmount }( _minTokenReturn, _path, _receiver, block.timestamp ); } else if (_path[_path.length - 1] == address(0x0)) { _path[_path.length - 1] = uniswapContract.WETH(); result = uniswapContract.swapExactTokensForETH( _tokenAmount, _minTokenReturn, _path, _receiver, block.timestamp ); } else { result = uniswapContract.swapExactTokensForTokens( _tokenAmount, _minTokenReturn, _path, _receiver, block.timestamp ); } return result[result.length - 1]; } } // SPDX-License-Identifier: MIT 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 initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @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 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; interface Avatar { function nativeToken() external view returns (address); function nativeReputation() external view returns (address); function owner() external view returns (address); } interface Controller { event RegisterScheme(address indexed _sender, address indexed _scheme); event UnregisterScheme(address indexed _sender, address indexed _scheme); function genericCall( address _contract, bytes calldata _data, address _avatar, uint256 _value ) external returns (bool, bytes memory); function avatar() external view returns (address); function unregisterScheme(address _scheme, address _avatar) external returns (bool); function unregisterSelf(address _avatar) external returns (bool); function registerScheme( address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar ) external returns (bool); function isSchemeRegistered(address _scheme, address _avatar) external view returns (bool); function getSchemePermissions(address _scheme, address _avatar) external view returns (bytes4); function addGlobalConstraint( address _constraint, bytes32 _paramHash, address _avatar ) external returns (bool); function mintTokens( uint256 _amount, address _beneficiary, address _avatar ) external returns (bool); function externalTokenTransfer( address _token, address _recipient, uint256 _amount, address _avatar ) external returns (bool); function sendEther( uint256 _amountInWei, address payable _to, address _avatar ) external returns (bool); } interface GlobalConstraintInterface { enum CallPhase { Pre, Post, PreAndPost } function pre( address _scheme, bytes32 _params, bytes32 _method ) external returns (bool); /** * @dev when return if this globalConstraints is pre, post or both. * @return CallPhase enum indication Pre, Post or PreAndPost. */ function when() external returns (CallPhase); } interface ReputationInterface { function balanceOf(address _user) external view returns (uint256); function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); function getVotes(address _user) external view returns (uint256); function getVotesAt( address _user, bool _global, uint256 _blockNumber ) external view returns (uint256); function totalSupply() external view returns (uint256); function totalSupplyAt(uint256 _blockNumber) external view returns (uint256); function delegateOf(address _user) external returns (address); } interface SchemeRegistrar { function proposeScheme( Avatar _avatar, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string memory _descriptionHash ) external returns (bytes32); event NewSchemeProposal( address indexed _avatar, bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string _descriptionHash ); } interface IntVoteInterface { event NewProposal( bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event ExecuteProposal( bytes32 indexed _proposalId, address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VoteProposal( bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CancelProposal( bytes32 indexed _proposalId, address indexed _organization ); event CancelVoting( bytes32 indexed _proposalId, address indexed _organization, address indexed _voter ); /** * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being * generated by calculating keccak256 of a incremented counter. * @param _numOfChoices number of voting choices * @param _proposalParameters defines the parameters of the voting machine used for this proposal * @param _proposer address * @param _organization address - if this address is zero the msg.sender will be used as the organization address. * @return proposal's id. */ function propose( uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns (bytes32); function vote( bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns (bool); function cancelVote(bytes32 _proposalId) external; function getNumberOfChoices(bytes32 _proposalId) external view returns (uint256); function isVotable(bytes32 _proposalId) external view returns (bool); /** * @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. * @param _proposalId the ID of the proposal * @param _choice the index in the * @return voted reputation for the given choice */ function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns (uint256); /** * @dev isAbstainAllow returns if the voting machine allow abstain (0) * @return bool true or false */ function isAbstainAllow() external pure returns (bool); /** * @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. * @return min - minimum number of choices max - maximum number of choices */ function getAllowedRangeOfChoices() external pure returns (uint256 min, uint256 max); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "../DAOStackInterfaces.sol"; /** @title Simple name to address resolver */ contract NameService is Initializable, UUPSUpgradeable { mapping(bytes32 => address) public addresses; Controller public dao; event AddressChanged(string name ,address addr); function initialize( Controller _dao, bytes32[] memory _nameHashes, address[] memory _addresses ) public virtual initializer { dao = _dao; for (uint256 i = 0; i < _nameHashes.length; i++) { addresses[_nameHashes[i]] = _addresses[i]; } addresses[keccak256(bytes("CONTROLLER"))] = address(_dao); addresses[keccak256(bytes("AVATAR"))] = address(_dao.avatar()); } function _authorizeUpgrade(address) internal override { _onlyAvatar(); } function _onlyAvatar() internal view { require( address(dao.avatar()) == msg.sender, "only avatar can call this method" ); } function setAddress(string memory name, address addr) external { _onlyAvatar(); addresses[keccak256(bytes(name))] = addr; emit AddressChanged(name, addr); } function setAddresses(bytes32[] calldata hash, address[] calldata addrs) external { _onlyAvatar(); for (uint256 i = 0; i < hash.length; i++) { addresses[hash[i]] = addrs[i]; } } function getAddress(string memory name) external view returns (address) { return addresses[keccak256(bytes(name))]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../DAOStackInterfaces.sol"; import "../Interfaces.sol"; /** @title Simple contract that keeps DAO contracts registery */ contract DAOContract { Controller public dao; address public avatar; INameService public nameService; function _onlyAvatar() internal view { require( address(dao.avatar()) == msg.sender, "only avatar can call this method" ); } function setDAO(INameService _ns) internal { nameService = _ns; updateAvatar(); } function updateAvatar() public { dao = Controller(nameService.getAddress("CONTROLLER")); avatar = dao.avatar(); } function nativeToken() public view returns (IGoodDollar) { return IGoodDollar(nameService.getAddress("GOODDOLLAR")); } uint256[50] private gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../reserve/GoodReserveCDai.sol"; import "../Interfaces.sol"; import "../utils/DSMath.sol"; import "../utils/DAOUpgradeableContract.sol"; /** * @title GoodFundManager contract that transfer interest from the staking contract * to the reserve contract and transfer the return mintable tokens to the staking * contract * cDAI support only */ contract GoodFundManager is DAOUpgradeableContract, DSMath { // timestamp that indicates last time that interests collected uint256 public lastCollectedInterest; //just for UI to easily find last event uint256 public lastCollectedInterestBlock; // Gas cost for mint ubi+bridge ubi+mint rewards uint256 public gasCostExceptInterestCollect; // Gas cost for minting GD for keeper uint256 public gdMintGasCost; // how much time since last collectInterest should pass in order to cancel gas cost multiplier requirement for next collectInterest uint256 public collectInterestTimeThreshold; // to allow keeper to collect interest, total interest collected should be interestMultiplier*gas costs uint8 public interestMultiplier; //min amount of days between interest collection uint8 public minCollectInterestIntervalDays; //address of the active staking contracts address[] public activeContracts; event GasCostSet(uint256 newGasCost); event CollectInterestTimeThresholdSet( uint256 newCollectInterestTimeThreshold ); event InterestMultiplierSet(uint8 newInterestMultiplier); event GasCostExceptInterestCollectSet( uint256 newGasCostExceptInterestCollect ); event StakingRewardSet( uint32 _rewardsPerBlock, address _stakingAddress, uint32 _blockStart, uint32 _blockEnd, bool _isBlackListed ); //Structure that hold reward information and if its blacklicksted or not for particular staking Contract struct Reward { uint32 blockReward; //in G$ uint64 blockStart; // # of the start block to distribute rewards uint64 blockEnd; // # of the end block to distribute rewards bool isBlackListed; // If staking contract is blacklisted or not } struct InterestInfo { address contractAddress; // staking contract address which interest will be collected uint256 interestBalance; // Interest amount that staking contract has uint256 collectedInterestSoFar; // Collected interest amount so far including this contract uint256 gasCostSoFar; // Spent gas amount so far including this contract uint256 maxGasAmountSoFar; // Max gas amount that can spend to collect this interest according to interest amount bool maxGasLargerOrEqualRequired; // Bool that indicates if max gas amount larger or equal to actual gas needed } // Rewards per block for particular Staking contract mapping(address => Reward) public rewardsForStakingContract; // Emits when `transferInterest` transfers // funds to the staking contract and to // the bridge event FundsTransferred( // The caller address address indexed caller, // The staking contract address //address indexed staking, // The reserve contract address address reserve, //addresses of the staking contracts address[] stakings, // Amount of cDai that was transferred // from the staking contract to the // reserve contract uint256 cDAIinterestEarned, // The number of tokens that have been minted // by the reserve to the staking contract //uint256 gdInterest, // The number of tokens that have been minted // by the reserve to the bridge which in his // turn should transfer those funds to the // sidechain uint256 gdUBI, // Amount of GD to be minted as reward //to the keeper which collect interests uint256 gdReward ); event StakingRewardMinted( address stakingContract, address staker, uint256 gdReward ); /** * @dev Constructor * @param _ns The address of the name Service */ function initialize(INameService _ns) public virtual initializer { setDAO(_ns); gdMintGasCost = 250000; // While testing highest amount was 240k so put 250k to be safe collectInterestTimeThreshold = 60 days; interestMultiplier = 4; gasCostExceptInterestCollect = 850000; //while testing highest amount was 800k so put 850k to be safe minCollectInterestIntervalDays = 7; } /** * @dev Set gas cost to mint GD rewards for keeper * @param _gasAmount amount of gas it costs for minting gd reward */ function setGasCost(uint256 _gasAmount) public { _onlyAvatar(); gdMintGasCost = _gasAmount; emit GasCostSet(_gasAmount); } /** * @dev Set collectInterestTimeThreshold to determine how much time should pass after collectInterest called * after which we ignore the interest>=multiplier*gas costs limit * @param _timeThreshold new threshold in seconds */ function setCollectInterestTimeThreshold(uint256 _timeThreshold) public { _onlyAvatar(); collectInterestTimeThreshold = _timeThreshold; emit CollectInterestTimeThresholdSet(_timeThreshold); } /** * @dev Set multiplier to determine how much times larger should be collected interest than spent gas when collectInterestTimeThreshold did not pass */ function setInterestMultiplier(uint8 _newMultiplier) public { _onlyAvatar(); interestMultiplier = _newMultiplier; emit InterestMultiplierSet(_newMultiplier); } /** * @dev Set Gas cost for required transactions after collecting interest in collectInterest function * we need this to know if caller has enough gas left to keep collecting interest * @dev _gasAmount The gas amount that needed for transactions */ function setGasCostExceptInterestCollect(uint256 _gasAmount) public { _onlyAvatar(); gasCostExceptInterestCollect = _gasAmount; emit GasCostExceptInterestCollectSet(_gasAmount); } /** * @dev Sets the Reward for particular Staking contract * @param _rewardsPerBlock reward for per block * @param _stakingAddress address of the staking contract * @param _blockStart block number for start reward distrubution * @param _blockEnd block number for end reward distrubition * @param _isBlackListed set staking contract blacklisted or not to prevent minting */ function setStakingReward( uint32 _rewardsPerBlock, address _stakingAddress, uint32 _blockStart, uint32 _blockEnd, bool _isBlackListed ) public { _onlyAvatar(); //we dont allow to undo blacklisting as it will mess up rewards accounting. //staking contracts are assumed immutable and thus non fixable require( (_isBlackListed || !rewardsForStakingContract[_stakingAddress].isBlackListed), "can't undo blacklisting" ); Reward memory reward = Reward( _rewardsPerBlock, _blockStart > 0 ? _blockStart : uint32(block.number), _blockEnd > 0 ? _blockEnd : 0xFFFFFFFF, _isBlackListed ); rewardsForStakingContract[_stakingAddress] = reward; bool exist; uint8 i; for (i = 0; i < activeContracts.length; i++) { if (activeContracts[i] == _stakingAddress) { exist = true; break; } } if (exist && (_isBlackListed || _rewardsPerBlock == 0)) { activeContracts[i] = activeContracts[activeContracts.length - 1]; activeContracts.pop(); } else if (!exist && !(_isBlackListed || _rewardsPerBlock == 0)) { activeContracts.push(_stakingAddress); } emit StakingRewardSet( _rewardsPerBlock, _stakingAddress, _blockStart, _blockEnd, _isBlackListed ); } /** * @dev Collects UBI interest in iToken from a given staking contract and transfers * that interest to the reserve contract. Then transfers the given gd which * received from the reserve contract back to the staking contract and to the * bridge, which locks the funds and then the GD tokens are been minted to the * given address on the sidechain * @param _stakingContracts from which contracts to collect interest * @param _forceAndWaiverRewards if set to true, it will collect interest even if not passed thershold, but will not reward caller with gas refund + reward */ function collectInterest( address[] calldata _stakingContracts, bool _forceAndWaiverRewards ) external { uint256 initialGas = gasleft(); uint256 gdUBI; uint256 interestInCdai; address reserveAddress; { // require( // block.timestamp >= lastCollectedInterest + minCollectedInterestIntervalDays * days, // "collectInterest: collect interval not passed" // ); //prevent stack too deep cERC20 iToken = cERC20(nameService.getAddress("CDAI")); ERC20 daiToken = ERC20(nameService.getAddress("DAI")); reserveAddress = nameService.getAddress("RESERVE"); // DAI balance of the reserve contract uint256 currentBalance = daiToken.balanceOf(reserveAddress); uint256 startingCDAIBalance = iToken.balanceOf(reserveAddress); for (uint256 i = _stakingContracts.length - 1; i >= 0; i--) { // elements are sorted by balances from lowest to highest if (_stakingContracts[i] != address(0x0)) { IGoodStaking(_stakingContracts[i]).collectUBIInterest(reserveAddress); } if (i == 0) break; // when active contracts length is 1 then gives error } // Finds the actual transferred DAI uint256 daiToConvert = daiToken.balanceOf(reserveAddress) - currentBalance; // Mints gd while the interest amount is equal to the transferred amount (gdUBI, interestInCdai) = GoodReserveCDai(reserveAddress).mintUBI( daiToConvert, startingCDAIBalance, iToken ); IGoodDollar token = IGoodDollar(nameService.getAddress("GOODDOLLAR")); if (gdUBI > 0) { //transfer ubi to avatar on sidechain via bridge require( token.transferAndCall( nameService.getAddress("BRIDGE_CONTRACT"), gdUBI, abi.encodePacked(nameService.getAddress("UBI_RECIPIENT")) ), "ubi bridge transfer failed" ); } } uint256 gdRewardToMint; if (_forceAndWaiverRewards == false) { uint256 totalUsedGas = ((initialGas - gasleft() + gdMintGasCost) * 110) / 100; // We will return as reward 1.1x of used gas in GD gdRewardToMint = getGasPriceInGD(totalUsedGas); GoodReserveCDai(reserveAddress).mintRewardFromRR( nameService.getAddress("CDAI"), msg.sender, gdRewardToMint ); uint256 gasPriceIncDAI = getGasPriceIncDAIorDAI( initialGas - gasleft(), false ); if ( block.timestamp >= lastCollectedInterest + collectInterestTimeThreshold ) { require( interestInCdai >= gasPriceIncDAI, "Collected interest value should be larger than spent gas costs" ); // This require is necessary to keeper can not abuse this function } else { require( interestInCdai >= interestMultiplier * gasPriceIncDAI, "Collected interest value should be interestMultiplier x gas costs" ); } } emit FundsTransferred( msg.sender, reserveAddress, _stakingContracts, interestInCdai, gdUBI, gdRewardToMint ); lastCollectedInterest = block.timestamp; lastCollectedInterestBlock = block.number; } /** * @dev Function that get interest informations of staking contracts in the sorted array by highest interest to lowest interest amount * @return array of interestInfo struct */ function calcSortedContracts() public view returns (InterestInfo[] memory) { address[] memory addresses = new address[](activeContracts.length); uint256[] memory balances = new uint256[](activeContracts.length); InterestInfo[] memory interestInfos = new InterestInfo[]( activeContracts.length ); uint256 tempInterest; int256 i; for (i = 0; i < int256(activeContracts.length); i++) { (, , , , tempInterest) = IGoodStaking(activeContracts[uint256(i)]) .currentGains(false, true); if (tempInterest != 0) { addresses[uint256(i)] = activeContracts[uint256(i)]; balances[uint256(i)] = tempInterest; } } uint256 usedGasAmount = gasCostExceptInterestCollect; quick(balances, addresses); // sort the values according to interest balance uint256 gasCost; uint256 possibleCollected; uint256 maxGasAmount; for (i = int256(activeContracts.length) - 1; i >= 0; i--) { // elements are sorted by balances from lowest to highest if (addresses[uint256(i)] != address(0x0)) { gasCost = IGoodStaking(addresses[uint256(i)]) .getGasCostForInterestTransfer(); // collects the interest from the staking contract and transfer it directly to the reserve contract //`collectUBIInterest` returns (iTokengains, tokengains, precission loss, donation ratio) possibleCollected += balances[uint256(i)]; usedGasAmount += gasCost; maxGasAmount = block.timestamp >= lastCollectedInterest + collectInterestTimeThreshold ? (possibleCollected * 1e10) / getGasPriceIncDAIorDAI(1, true) : (possibleCollected * 1e10) / (interestMultiplier * getGasPriceIncDAIorDAI(1, true)); interestInfos[uint256(i)] = InterestInfo({ contractAddress: addresses[uint256(i)], interestBalance: balances[uint256(i)], collectedInterestSoFar: possibleCollected, gasCostSoFar: usedGasAmount, maxGasAmountSoFar: maxGasAmount, maxGasLargerOrEqualRequired: maxGasAmount >= usedGasAmount }); } else { break; // if addresses are null after this element then break because we initialize array in size activecontracts but if their interest balance is zero then we dont put it in this array } } return interestInfos; } /** * @dev Mint to users reward tokens which they earned by staking contract * @param _token reserve token (currently can be just cDAI) * @param _user user to get rewards */ function mintReward(address _token, address _user) public { Reward memory staking = rewardsForStakingContract[address(msg.sender)]; require(staking.blockStart > 0, "Staking contract not registered"); uint256 amount = IGoodStaking(address(msg.sender)).rewardsMinted( _user, staking.blockReward, staking.blockStart, staking.blockEnd ); if (amount > 0 && staking.isBlackListed == false) { GoodReserveCDai(nameService.getAddress("RESERVE")).mintRewardFromRR( _token, _user, amount ); emit StakingRewardMinted(msg.sender, _user, amount); } } /// quick sort function quick(uint256[] memory data, address[] memory addresses) internal pure { if (data.length > 1) { quickPart(data, addresses, 0, data.length - 1); } } /** @dev quicksort algorithm to sort array */ function quickPart( uint256[] memory data, address[] memory addresses, uint256 low, uint256 high ) internal pure { if (low < high) { uint256 pivotVal = data[(low + high) / 2]; uint256 low1 = low; uint256 high1 = high; for (;;) { while (data[low1] < pivotVal) low1++; while (data[high1] > pivotVal) high1--; if (low1 >= high1) break; (data[low1], data[high1]) = (data[high1], data[low1]); (addresses[low1], addresses[high1]) = ( addresses[high1], addresses[low1] ); low1++; high1--; } if (low < high1) quickPart(data, addresses, low, high1); high1++; if (high1 < high) quickPart(data, addresses, high1, high); } } /** @dev Helper function to get gasPrice in GWEI then change it to cDAI/DAI @param _gasAmount gas amount to get its value @param _inDAI indicates if result should return in DAI @return Price of the gas in DAI/cDAI */ function getGasPriceIncDAIorDAI(uint256 _gasAmount, bool _inDAI) public view returns (uint256) { AggregatorV3Interface gasPriceOracle = AggregatorV3Interface( nameService.getAddress("GAS_PRICE_ORACLE") ); int256 gasPrice = gasPriceOracle.latestAnswer(); // returns gas price in 0 decimal as GWEI so 1eth / 1e9 eth AggregatorV3Interface daiETHOracle = AggregatorV3Interface( nameService.getAddress("DAI_ETH_ORACLE") ); int256 daiInETH = daiETHOracle.latestAnswer(); // returns DAI price in ETH uint256 result = ((uint256(gasPrice) * 1e18) / uint256(daiInETH)); // Gasprice in GWEI and daiInETH is 18 decimals so we multiply gasprice with 1e18 in order to get result in 18 decimals if (_inDAI) return result * _gasAmount; result = (((result / 1e10) * 1e28) / cERC20(nameService.getAddress("CDAI")).exchangeRateStored()) * _gasAmount; // based on https://compound.finance/docs#protocol-math return result; } /** @dev Helper function to get gasPrice in G$, used to calculate the rewards for collectInterest KEEPER @param _gasAmount gas amount to get its value @return Price of the gas in G$ */ function getGasPriceInGD(uint256 _gasAmount) public view returns (uint256) { uint256 priceInCdai = getGasPriceIncDAIorDAI(_gasAmount, false); uint256 gdPriceIncDAI = GoodReserveCDai(nameService.getAddress("RESERVE")) .currentPrice(); return ((priceInCdai * 1e27) / gdPriceIncDAI) / 1e25; // rdiv returns result in 27 decimals since GD$ in 2 decimals then divide 1e25 } function getActiveContractsCount() public view returns (uint256) { return activeContracts.length; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../Interfaces.sol"; contract BaseShareFieldV2 { // rewards claimed by users uint128 mintedRewards; // total staked for shares calculation uint128 totalProductivity; // total staked that earns rewards (some stakers can donate their rewards) uint128 totalEffectiveStakes; // rewards accumulated for distribution uint128 accumulatedRewards; // block of last rewards accumulation uint128 lastRewardBlock; // number of blocks before reaching the max rewards multiplier (starting at 0.5 reaching 1 after maxMultiplierThreshold) uint64 maxMultiplierThreshold; // Staking contracts accepts Tokens with max 18 decimals so this variable holds decimal difference between 18 and Token's decimal in order to make calculations uint8 tokenDecimalDifference; // accumulated rewards per share in 27 decimals precision uint256 accAmountPerShare; //status of user rewards. everything is in 18 decimals struct UserInfo { uint128 amount; // How many tokens the user has provided. uint128 effectiveStakes; // stakes not including stakes that donate their rewards uint128 rewardDebt; // Reward debt. uint128 rewardEarn; // Reward earn and not minted uint128 rewardMinted; //Rewards minted to user so far uint64 lastRewardTime; // Last time that user got rewards uint64 multiplierResetTime; // Reset time of multiplier } mapping(address => UserInfo) public users; function getStats() external view returns ( uint256 _accAmountPerShare, uint128 _mintedRewards, uint128 _totalProductivity, uint128 _totalEffectiveStakes, uint128 _accumulatedRewards, uint128 _lastRewardBlock, uint64 _maxMultiplierThreshold, uint8 _tokenDecimalDifference ) { return ( accAmountPerShare, mintedRewards, totalProductivity, totalEffectiveStakes, accumulatedRewards, lastRewardBlock, maxMultiplierThreshold, tokenDecimalDifference ); } /** * @dev Helper function to check if caller is fund manager */ function _canMintRewards() internal view virtual {} /** * @dev Update reward variables of the given pool to be up-to-date. * Calculates passed blocks and adding to the reward pool * @param rewardsPerBlock how much rewards does this contract earns per block * @param blockStart block from which contract starts earning rewards * @param blockEnd block from which contract stops earning rewards */ function _update( uint256 rewardsPerBlock, uint256 blockStart, uint256 blockEnd ) internal virtual { if (totalEffectiveStakes == 0) { lastRewardBlock = uint128(block.number); return; } if (block.number >= blockStart && lastRewardBlock < blockStart) { lastRewardBlock = uint128(blockStart); } uint256 _lastRewardBlock = lastRewardBlock < blockStart && block.number >= blockStart ? blockStart : lastRewardBlock; uint256 curRewardBlock = block.number > blockEnd ? blockEnd : block.number; if (curRewardBlock < blockStart || _lastRewardBlock >= blockEnd) return; uint256 multiplier = curRewardBlock - _lastRewardBlock; // Blocks passed since last reward block uint256 reward = multiplier * (rewardsPerBlock * 1e16); // rewardsPerBlock is in G$ which is only 2 decimals, we turn it into 18 decimals by multiplying 1e16 accAmountPerShare = accAmountPerShare + (reward * 1e27) / (totalEffectiveStakes * (10**tokenDecimalDifference)); // Increase totalEffectiveStakes decimals if it is less than 18 decimals then accAmountPerShare in 27 decimals lastRewardBlock = uint128(curRewardBlock); } /** * @dev Audit user's rewards and calculate their earned rewards * For the first month rewards calculated with 0.5x * multiplier therefore they just gets half of the rewards which they earned in the first month * after first month they get full amount of rewards for the part that they earned after one month * @param user the user to audit * @param updatedAmount the new stake of the user after deposit/withdraw * @param donationPer percentage user is donating from his rewards. (currently just 0 or 100 in SimpleStaking) */ function _audit( address user, uint256 updatedAmount, uint256 donationPer ) internal virtual { UserInfo storage userInfo = users[user]; uint256 _amount = userInfo.amount; uint256 userEffectiveStake = userInfo.effectiveStakes; if (userEffectiveStake > 0) { ( uint256 blocksToPay, uint256 firstMonthBlocksToPay, uint256 fullBlocksToPay ) = _auditCalcs(userInfo); if (blocksToPay != 0) { uint256 pending = (userEffectiveStake * (10**tokenDecimalDifference) * accAmountPerShare) / 1e27 - userInfo.rewardDebt; // Turn userInfo.amount to 18 decimals by multiplying tokenDecimalDifference if it's not and multiply with accAmountPerShare which is 27 decimals then divide it 1e27 bring it down to 18 decimals uint256 rewardPerBlock = (pending * 1e9) / blocksToPay; // bring pending to 1e27 pending = ((((firstMonthBlocksToPay * 1e2 * 5) / 10) + fullBlocksToPay * 1e2) * // multiply first month by 0.5x (5/10) since rewards in first month with multiplier 0.5 and multiply it with 1e2 to get it 2decimals so we could get more precision rewardPerBlock) / // Multiply fullBlocksToPay with 1e2 to bring it to 2 decimals // rewardPerBlock is in 27decimals 1e11; // Pending in 18 decimals so we divide 1e11 to bring it down to 18 decimals userInfo.rewardEarn = uint128(userInfo.rewardEarn + pending); // Add user's earned rewards to user's account so it can be minted later accumulatedRewards = uint128(accumulatedRewards + pending); } } else { userInfo.multiplierResetTime = uint64(block.number); // Should set user's multiplierResetTime when they stake for the first time } //if withdrawing rewards/stake we reset multiplier, only in case of increasinig productivity we dont reset multiplier if (updatedAmount <= _amount) { userInfo.multiplierResetTime = uint64(block.number); if (_amount > 0) { //calculate relative part of user effective stakes uint256 withdrawFromEffectiveStake = ((_amount - updatedAmount) * userInfo.effectiveStakes) / _amount; userInfo.effectiveStakes -= uint128(withdrawFromEffectiveStake); totalEffectiveStakes -= uint128(withdrawFromEffectiveStake); } } else if (donationPer == 0) { userInfo.effectiveStakes += uint128(updatedAmount - _amount); totalEffectiveStakes += uint128(updatedAmount - _amount); } userInfo.lastRewardTime = uint64(block.number); userInfo.amount = uint128(updatedAmount); userInfo.rewardDebt = uint128( (userInfo.effectiveStakes * (10**tokenDecimalDifference) * accAmountPerShare) / 1e27 ); // Divide to 1e27 to keep rewardDebt in 18 decimals since accAmountPerShare is 27 decimals } /** * @dev Helper function to make calculations in audit and getUserPendingReward methods */ function _auditCalcs(UserInfo memory _userInfo) internal view returns ( uint256, uint256, uint256 ) { uint256 blocksPaid = _userInfo.lastRewardTime - _userInfo.multiplierResetTime; // lastRewardTime is always >= multiplierResetTime uint256 blocksPassedFirstMonth = maxMultiplierThreshold < block.number - _userInfo.multiplierResetTime ? maxMultiplierThreshold : block.number - _userInfo.multiplierResetTime; // blocks which is after first month uint256 blocksToPay = block.number - _userInfo.lastRewardTime; // blocks passed since last payment uint256 firstMonthBlocksToPay = blocksPaid >= maxMultiplierThreshold ? 0 : blocksPassedFirstMonth - blocksPaid; // block which is in the first month so pays with 0.5x multiplier uint256 fullBlocksToPay = blocksToPay - firstMonthBlocksToPay; // blocks to pay in full amount which means with 1x multiplier return (blocksToPay, firstMonthBlocksToPay, fullBlocksToPay); } /** * @dev This function increase user's productivity and updates the global productivity. * This function increase user's productivity and updates the global productivity. * the users' actual share percentage will calculated by: * Formula: user_productivity / global_productivity * @param user the user to update * @param value the increase in user stake * @param rewardsPerBlock how much rewards does this contract earns per block * @param blockStart block from which contract starts earning rewards * @param blockEnd block from which contract stops earning rewards * @param donationPer percentage user is donating from his rewards. (currently just 0 or 100 in SimpleStaking) */ function _increaseProductivity( address user, uint256 value, uint256 rewardsPerBlock, uint256 blockStart, uint256 blockEnd, uint256 donationPer ) internal virtual returns (bool) { _update(rewardsPerBlock, blockStart, blockEnd); _audit(user, users[user].amount + value, donationPer); totalProductivity = uint128(totalProductivity + value); return true; } /** * @dev This function will decreases user's productivity by value, and updates the global productivity * it will record which block this is happenning and accumulates the area of (productivity * time) * @param user the user to update * @param value the increase in user stake * @param rewardsPerBlock how much rewards does this contract earns per block * @param blockStart block from which contract starts earning rewards * @param blockEnd block from which contract stops earning rewards */ function _decreaseProductivity( address user, uint256 value, uint256 rewardsPerBlock, uint256 blockStart, uint256 blockEnd ) internal virtual returns (bool) { _update(rewardsPerBlock, blockStart, blockEnd); _audit(user, users[user].amount - value, 1); // donationPer variable should be something different than zero so called with 1 totalProductivity = uint128(totalProductivity - value); return true; } /** * @dev Query user's pending reward with updated variables * @param user the user to update * @param rewardsPerBlock how much rewards does this contract earns per block * @param blockStart block from which contract starts earning rewards * @param blockEnd block from which contract stops earning rewards * @return returns amount of user's earned but not minted rewards */ function getUserPendingReward( address user, uint256 rewardsPerBlock, uint256 blockStart, uint256 blockEnd ) public view returns (uint256) { UserInfo memory userInfo = users[user]; uint256 _accAmountPerShare = accAmountPerShare; uint256 pending = 0; if ( totalEffectiveStakes != 0 && block.number >= blockStart && blockEnd >= block.number ) { uint256 multiplier = block.number - lastRewardBlock; uint256 reward = multiplier * (rewardsPerBlock * 1e16); // turn it to 18 decimals since rewardsPerBlock in 2 decimals ( uint256 blocksToPay, uint256 firstMonthBlocksToPay, uint256 fullBlocksToPay ) = _auditCalcs(userInfo); _accAmountPerShare = _accAmountPerShare + (reward * 1e27) / (totalEffectiveStakes * 10**tokenDecimalDifference); // Increase totalEffectiveStakes decimals if it is less than 18 decimals then accAmountPerShare in 27 decimals UserInfo memory tempUserInfo = userInfo; // to prevent stack too deep error any other recommendation? if (blocksToPay != 0) { pending = (tempUserInfo.effectiveStakes * (10**tokenDecimalDifference) * _accAmountPerShare) / 1e27 - tempUserInfo.rewardDebt; // Turn userInfo.amount to 18 decimals by multiplying tokenDecimalDifference if it's not and multiply with accAmountPerShare which is 27 decimals then divide it 1e27 bring it down to 18 decimals uint256 rewardPerBlock = (pending * 1e27) / (blocksToPay * 1e18); // bring both variable to 18 decimals and multiply pending by 1e27 so when we divide them to each other result would be in 1e27 pending = ((((firstMonthBlocksToPay * 1e2 * 5) / 10) + fullBlocksToPay * 1e2) * // multiply first month by 0.5x (5/10) since rewards in first month with multiplier 0.5 and multiply it with 1e2 to get it 2decimals so we could get more precision rewardPerBlock) / // Multiply fullBlocksToPay with 1e2 to bring it to 2decimals // rewardPerBlock is in 27decimals 1e11; // Pending in 18 decimals so we divide 1e11 to bring it down to 18 decimals } } return userInfo.rewardEarn + pending; // rewardEarn is in 18 decimals } /** * @dev When the fundmanager calls this function it will updates the user records * get the user rewards which they earned but not minted and mark it as minted * @param user the user to update * @param rewardsPerBlock how much rewards does this contract earns per block * @param blockStart block from which contract starts earning rewards * @param blockEnd block from which contract stops earning rewards * @return returns amount to mint as reward to the user */ function rewardsMinted( address user, uint256 rewardsPerBlock, uint256 blockStart, uint256 blockEnd ) public returns (uint256) { _canMintRewards(); _update(rewardsPerBlock, blockStart, blockEnd); _audit(user, users[user].amount, 1); // donationPer variable should be something different than zero so called with 1 uint128 amount = users[user].rewardEarn; users[user].rewardEarn = 0; users[user].rewardMinted += amount; mintedRewards = mintedRewards + amount; amount = amount / 1e16; // change decimal of mint amount to GD decimals return amount; } /** * @return Returns how many productivity a user has and global has. */ function getProductivity(address user) public view virtual returns (uint256, uint256) { return (users[user].amount, totalProductivity); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../utils/DAOContract.sol"; import "../utils/NameService.sol"; import "../Interfaces.sol"; import "../governance/GReputation.sol"; import "../governance/MultiBaseGovernanceShareField.sol"; import "../staking/GoodFundManager.sol"; import "../staking/SimpleStakingV2.sol"; /** * Staking contracts will update this contract with staker token stake amount * This contract will be able to mint GDAO. 2M GDAO that will be allocated between staking contracts each month pro-rate based on $ value staked. * Each staker will receive his share pro rata per staking contract he participates in * NOTICE: a contract will start earning GDAO rewards only after first month */ contract StakersDistribution is DAOUpgradeableContract, MultiBaseGovernanceShareField { ///@notice reputation to distribute each month, will effect next month when set uint256 public monthlyReputationDistribution; ///@notice month number since epoch uint256 public currentMonth; event ReputationEarned( address staker, address[] stakingContracts, uint256 reputation ); function initialize(INameService _ns) public initializer { monthlyReputationDistribution = 2000000 ether; //2M as specified in specs setDAO(_ns); } /** * @dev this contract runs on ethereum */ function getChainBlocksPerMonth() public pure override returns (uint256) { return 172800; //4 * 60 * 24 * 30 } /** * @dev update the monthly reputation distribution. only avatar can do that. * @param newMonthlyReputationDistribution the new reputation amount to distribute */ function setMonthlyReputationDistribution( uint256 newMonthlyReputationDistribution ) external { _onlyAvatar(); monthlyReputationDistribution = newMonthlyReputationDistribution; } /** * @dev internal function to switch to new month. records for new month the current monthlyReputationDistribution */ function _updateRewards() internal { if (nameService.getAddress("FUND_MANAGER") != address(0)) { //read active staking contracts set pro rate monthly share GoodFundManager gfm = GoodFundManager( nameService.getAddress("FUND_MANAGER") ); uint256 activeContractsCount = gfm.getActiveContractsCount(); address payable[] memory activeStakingList = new address payable[]( activeContractsCount ); uint256[] memory contractLockedValue = new uint256[]( activeContractsCount ); uint256 totalLockedValue; for (uint256 i = 0; i < activeContractsCount; i++) { activeStakingList[i] = payable(gfm.activeContracts(i)); (, uint64 blockStart, uint64 blockEnd, ) = gfm .rewardsForStakingContract(activeStakingList[i]); if (blockStart <= block.number && blockEnd > block.number) { uint256 lockedValueInUSD = SimpleStakingV2(activeStakingList[i]) .lockedUSDValue(); contractLockedValue[i] = lockedValueInUSD; totalLockedValue += contractLockedValue[i]; } } //set each contract relative monthly rewards for (uint256 i = 0; i < activeContractsCount; i++) { uint256 contractShare = totalLockedValue > 0 ? (monthlyReputationDistribution * contractLockedValue[i]) / totalLockedValue : monthlyReputationDistribution / activeContractsCount; if (contractLockedValue[i] > 0) { _setMonthlyRewards(activeStakingList[i], contractShare); } } } } /** * @dev staking contract can call this to increase user current contribution * @param _staker the user to update * @param _value the value to increase by */ function userStaked(address _staker, uint256 _value) external { address stakingContract = msg.sender; ( , uint64 blockStart, uint64 blockEnd, bool isBlackListed ) = GoodFundManager(nameService.getAddress("FUND_MANAGER")) .rewardsForStakingContract(stakingContract); if (isBlackListed) return; //dont do anything if staking contract has been blacklisted; _increaseProductivity( stakingContract, _staker, _value, blockStart, blockEnd ); address[] memory contracts = new address[](1); contracts[0] = stakingContract; _claimReputation(_staker, contracts); _updateRewards(); } /** * @dev staking contract can call this to decrease user current contribution * @param _staker the user to update * @param _value the value to decrease by */ function userWithdraw(address _staker, uint256 _value) external { address stakingContract = msg.sender; ( , uint64 blockStart, uint64 blockEnd, bool isBlackListed ) = GoodFundManager(nameService.getAddress("FUND_MANAGER")) .rewardsForStakingContract(stakingContract); if (isBlackListed) return; //dont do anything if staking contract has been blacklisted; _decreaseProductivity( stakingContract, _staker, _value, blockStart, blockEnd ); address[] memory contracts = new address[](1); contracts[0] = stakingContract; _claimReputation(_staker, contracts); _updateRewards(); } /** * @dev mints reputation to user according to his share in the different staking contracts * @param _staker the user to distribute reputation to * @param _stakingContracts the user to distribute reputation to */ function claimReputation( address _staker, address[] calldata _stakingContracts ) external { _claimReputation(_staker, _stakingContracts); } function _claimReputation(address _staker, address[] memory _stakingContracts) internal { uint256 totalRep; GoodFundManager gfm = GoodFundManager( nameService.getAddress("FUND_MANAGER") ); for (uint256 i = 0; i < _stakingContracts.length; i++) { (, uint64 blockStart, uint64 blockEnd, bool isBlackListed) = gfm .rewardsForStakingContract(_stakingContracts[i]); if (isBlackListed == false) totalRep += _issueEarnedRewards( _stakingContracts[i], _staker, blockStart, blockEnd ); } if (totalRep > 0) { GReputation(nameService.getAddress("REPUTATION")).mint(_staker, totalRep); emit ReputationEarned(_staker, _stakingContracts, totalRep); } } /** * @dev get user reputation rewards accrued in goodstaking contracts * @param _contracts list of contracts to check for rewards * @param _user the user to check rewards for * @return reputation rewards pending for user */ function getUserPendingRewards(address[] memory _contracts, address _user) public view returns (uint256) { uint256 pending; for (uint256 i = 0; i < _contracts.length; i++) { ( , uint64 blockStart, uint64 blockEnd, bool isBlackListed ) = GoodFundManager(nameService.getAddress("FUND_MANAGER")) .rewardsForStakingContract(_contracts[i]); if (isBlackListed == false) { pending += getUserPendingReward( _contracts[i], blockStart, blockEnd, _user ); } } return pending; } /** * @param _contracts staking contracts to sum _user minted and pending * @param _user account to get rewards status for * @return (minted, pending) in GDAO 18 decimals */ function getUserMintedAndPending(address[] memory _contracts, address _user) public view returns (uint256, uint256) { uint256 pending = getUserPendingRewards(_contracts, _user); uint256 minted; for (uint256 i = 0; i < _contracts.length; i++) { minted += contractToUsers[_contracts[i]][_user].rewardMinted; } return (minted, pending); } } // 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.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 "../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; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/presets/ERC20PresetMinterPauserUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../utils/DAOUpgradeableContract.sol"; import "../utils/NameService.sol"; import "../DAOStackInterfaces.sol"; import "../Interfaces.sol"; import "./GoodMarketMaker.sol"; interface ContributionCalc { function calculateContribution( GoodMarketMaker _marketMaker, GoodReserveCDai _reserve, address _contributer, ERC20 _token, uint256 _gdAmount ) external view returns (uint256); function setContributionRatio(uint256 _nom, uint256 _denom) external; } /** @title Reserve based on cDAI and dynamic reserve ratio market maker */ contract GoodReserveCDai is DAOUpgradeableContract, ERC20PresetMinterPauserUpgradeable, GlobalConstraintInterface { bytes32 public constant RESERVE_MINTER_ROLE = keccak256("RESERVE_MINTER_ROLE"); /// @dev G$ minting cap; uint256 public cap; // The last block number which // `mintUBI` has been executed in uint256 public lastMinted; address public daiAddress; address public cDaiAddress; /// @dev merkleroot for GDX airdrop bytes32 public gdxAirdrop; /// @dev mark if user claimed his GDX mapping(address => bool) public isClaimedGDX; // Emits when new GD tokens minted event UBIMinted( //epoch of UBI uint256 indexed day, //the token paid as interest address indexed interestToken, //wei amount of interest paid in interestToken uint256 interestReceived, // Amount of GD tokens that was // added to the supply as a result // of `mintInterest` uint256 gdInterestMinted, // Amount of GD tokens that was // added to the supply as a result // of `mintExpansion` uint256 gdExpansionMinted, // Amount of GD tokens that was // minted to the `ubiCollector` uint256 gdUbiTransferred ); // Emits when GD tokens are purchased event TokenPurchased( // The initiate of the action address indexed caller, // The convertible token address // which the GD tokens were // purchased with address indexed inputToken, // Reserve tokens amount uint256 inputAmount, // Actual return after the // conversion uint256 actualReturn, // Address of the receiver of tokens address indexed receiverAddress ); // Emits when GD tokens are sold event TokenSold( // The initiate of the action address indexed caller, // The convertible token address // which the GD tokens were // sold to address indexed outputToken, // GD tokens amount uint256 gdAmount, // The amount of GD tokens that // was contributed during the // conversion uint256 contributionAmount, // Actual return after the // conversion uint256 actualReturn, // Address of the receiver of tokens address indexed receiverAddress ); function initialize(INameService _ns, bytes32 _gdxAirdrop) public virtual initializer { __ERC20PresetMinterPauser_init("GDX", "G$X"); setDAO(_ns); //fixed cdai/dai setAddresses(); //gdx roles renounceRole(MINTER_ROLE, _msgSender()); renounceRole(PAUSER_ROLE, _msgSender()); renounceRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(DEFAULT_ADMIN_ROLE, address(avatar)); //mint access through reserve _setupRole(RESERVE_MINTER_ROLE, address(avatar)); //only Avatar can manage minters cap = 22 * 1e14; //22 trillion G$ cents gdxAirdrop = _gdxAirdrop; } function setGDXAirdrop(bytes32 _airdrop) external { _onlyAvatar(); gdxAirdrop = _airdrop; } /// @dev GDX decimals function decimals() public pure override returns (uint8) { return 2; } function setAddresses() public { daiAddress = nameService.getAddress("DAI"); cDaiAddress = nameService.getAddress("CDAI"); // Approve transfer to cDAI contract ERC20(daiAddress).approve(cDaiAddress, type(uint256).max); } /** * @dev get current MarketMaker from name service * The address of the market maker contract * which makes the calculations and holds * the token and accounts info (should be owned by the reserve) */ function getMarketMaker() public view returns (GoodMarketMaker) { return GoodMarketMaker(nameService.getAddress("MARKET_MAKER")); } /** * @dev Converts cDai tokens to GD tokens and updates the bonding curve params. * `buy` occurs only if the GD return is above the given minimum. It is possible * to buy only with cDAI and when the contract is set to active. MUST call to * cDAI `approve` prior this action to allow this contract to accomplish the * conversion. * @param _tokenAmount The amount of cDAI tokens that should be converted to GD tokens * @param _minReturn The minimum allowed return in GD tokens * @param _targetAddress address of g$ and gdx recipient if different than msg.sender * @return (gdReturn) How much GD tokens were transferred */ function buy( uint256 _tokenAmount, uint256 _minReturn, address _targetAddress ) external returns (uint256) { ERC20 buyWith = ERC20(cDaiAddress); uint256 gdReturn = getMarketMaker().buy(buyWith, _tokenAmount); _targetAddress = _targetAddress == address(0x0) ? msg.sender : _targetAddress; address exchangeHelper = nameService.getAddress("EXCHANGE_HELPER"); if (msg.sender != exchangeHelper) require( buyWith.transferFrom(msg.sender, address(this), _tokenAmount) == true, "transferFrom failed, make sure you approved input token transfer" ); require(gdReturn >= _minReturn, "GD return must be above the minReturn"); _mintGoodDollars(_targetAddress, gdReturn, true); //mint GDX _mintGDX(_targetAddress, gdReturn); emit TokenPurchased( msg.sender != exchangeHelper ? msg.sender : tx.origin, cDaiAddress, _tokenAmount, gdReturn, _targetAddress ); return gdReturn; } /** * @dev Mint rewards for staking contracts in G$ and update RR * requires minting permissions which is enforced by _mintGoodDollars * @param _to Receipent address for rewards * @param _amount G$ amount to mint for rewards */ function mintRewardFromRR( address _token, address _to, uint256 _amount ) public { getMarketMaker().mintFromReserveRatio(ERC20(_token), _amount); _mintGoodDollars(_to, _amount, false); //mint GDX _mintGDX(_to, _amount); } /** * @dev sell helper function burns GD tokens and update the bonding curve params. * `sell` occurs only if the token return is above the given minimum. Notice that * there is a contribution amount from the given GD that remains in the reserve. * @param _gdAmount The amount of GD tokens that should be converted to cDAI tokens * @param _minReturn The minimum allowed `sellTo` tokens return * @param _target address of the receiver of cDAI when sell G$ * @param _seller address of the seller when using helper contract * @return (tokenReturn, contribution) (cDAI received, G$ exit contribution) */ function sell( uint256 _gdAmount, uint256 _minReturn, address _target, address _seller ) external returns (uint256, uint256) { GoodMarketMaker mm = getMarketMaker(); if (msg.sender != nameService.getAddress("EXCHANGE_HELPER")) { IGoodDollar(nameService.getAddress("GOODDOLLAR")).burnFrom( msg.sender, _gdAmount ); _seller = msg.sender; } _target = _target == address(0x0) ? msg.sender : _target; //discount on exit contribution based on gdx uint256 gdx = balanceOf(_seller); uint256 discount = gdx <= _gdAmount ? gdx : _gdAmount; //burn gdx used for discount if (discount > 0) _burn(_seller, discount); uint256 contributionAmount = 0; uint256 gdAmountTemp = _gdAmount; // to prevent stack too deep errors if (discount < gdAmountTemp) contributionAmount = ContributionCalc( nameService.getAddress("CONTRIBUTION_CALCULATION") ).calculateContribution( mm, this, _seller, ERC20(cDaiAddress), gdAmountTemp - discount ); uint256 tokenReturn = mm.sellWithContribution( ERC20(cDaiAddress), gdAmountTemp, contributionAmount ); require( tokenReturn >= _minReturn, "Token return must be above the minReturn" ); cERC20(cDaiAddress).transfer(_target, tokenReturn); emit TokenSold( _seller, cDaiAddress, _gdAmount, contributionAmount, tokenReturn, _target ); return (tokenReturn, contributionAmount); } function currentPrice() public view returns (uint256) { return getMarketMaker().currentPrice(ERC20(cDaiAddress)); } function currentPriceDAI() public view returns (uint256) { cERC20 cDai = cERC20(cDaiAddress); return (((currentPrice() * 1e10) * cDai.exchangeRateStored()) / 1e28); // based on https://compound.finance/docs#protocol-math } /** * @dev helper to mint G$s * @param _to the recipient of newly minted G$s * @param _gdToMint how much G$ to mint * @param _internalCall skip minting role validation for internal calls, used when "buying G$" to "allow" buyer to mint G$ in exchange for his cDAI */ function _mintGoodDollars( address _to, uint256 _gdToMint, bool _internalCall ) internal { //enforce minting rules require( _internalCall || _msgSender() == nameService.getAddress("FUND_MANAGER") || hasRole(RESERVE_MINTER_ROLE, _msgSender()), "GoodReserve: not a minter" ); require( IGoodDollar(nameService.getAddress("GOODDOLLAR")).totalSupply() + _gdToMint <= cap, "GoodReserve: cap enforced" ); IGoodDollar(nameService.getAddress("GOODDOLLAR")).mint(_to, _gdToMint); } /// @dev helper to mint GDX to make _mint more verbose function _mintGDX(address _to, uint256 _gdx) internal { _mint(_to, _gdx); } /** * @dev only FundManager or other with mint G$ permission can call this to trigger minting. * Reserve sends UBI + interest to FundManager. * @param _daiToConvert DAI amount to convert cDAI * @param _startingCDAIBalance Initial cDAI balance before staking collect process start * @param _interestToken The token that was transfered to the reserve * @return gdUBI,interestInCdai how much GD UBI was minted and how much cDAI collected from staking contracts */ function mintUBI( uint256 _daiToConvert, uint256 _startingCDAIBalance, ERC20 _interestToken ) public returns (uint256, uint256) { cERC20(cDaiAddress).mint(_daiToConvert); uint256 interestInCdai = _interestToken.balanceOf(address(this)) - _startingCDAIBalance; uint256 gdInterestToMint = getMarketMaker().mintInterest( _interestToken, interestInCdai ); uint256 gdExpansionToMint = getMarketMaker().mintExpansion(_interestToken); uint256 gdUBI = gdInterestToMint + gdExpansionToMint; //this enforces who can call the public mintUBI method. only an address with permissions at reserve of RESERVE_MINTER_ROLE _mintGoodDollars(nameService.getAddress("FUND_MANAGER"), gdUBI, false); lastMinted = block.number; emit UBIMinted( lastMinted, address(_interestToken), interestInCdai, gdInterestToMint, gdExpansionToMint, gdUBI ); return (gdUBI, interestInCdai); } /** * @dev Allows the DAO to change the daily expansion rate * it is calculated by _nom/_denom with e27 precision. Emits * `ReserveRatioUpdated` event after the ratio has changed. * Only Avatar can call this method. * @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from * @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from */ function setReserveRatioDailyExpansion(uint256 _nom, uint256 _denom) public { _onlyAvatar(); getMarketMaker().setReserveRatioDailyExpansion(_nom, _denom); } /** * @dev Remove minting rights after it has transferred the cDAI funds to `_avatar` * Only the Avatar can execute this method */ function end() public { _onlyAvatar(); // remaining cDAI tokens in the current reserve contract if (ERC20(cDaiAddress).balanceOf(address(this)) > 0) { require( ERC20(cDaiAddress).transfer( address(avatar), ERC20(cDaiAddress).balanceOf(address(this)) ), "recover transfer failed" ); } //restore minting to avatar, so he can re-delegate it IGoodDollar gd = IGoodDollar(nameService.getAddress("GOODDOLLAR")); if (gd.isMinter(address(avatar)) == false) gd.addMinter(address(avatar)); IGoodDollar(nameService.getAddress("GOODDOLLAR")).renounceMinter(); } /** * @dev method to recover any stuck erc20 tokens (ie compound COMP) * @param _token the ERC20 token to recover */ function recover(ERC20 _token) public { _onlyAvatar(); require( _token.transfer(address(avatar), _token.balanceOf(address(this))), "recover transfer failed" ); } /** * @notice prove user balance in a specific blockchain state hash * @dev "rootState" is a special state that can be supplied once, and actually mints reputation on the current blockchain * @param _user the user to prove his balance * @param _gdx the balance we are prooving * @param _proof array of byte32 with proof data (currently merkle tree path) * @return true if proof is valid */ function claimGDX( address _user, uint256 _gdx, bytes32[] memory _proof ) public returns (bool) { require(isClaimedGDX[_user] == false, "already claimed gdx"); bytes32 leafHash = keccak256(abi.encode(_user, _gdx)); bool isProofValid = MerkleProofUpgradeable.verify( _proof, gdxAirdrop, leafHash ); require(isProofValid, "invalid merkle proof"); _mintGDX(_user, _gdx); isClaimedGDX[_user] = true; return true; } // implement minting constraints through the GlobalConstraintInterface interface. prevent any minting not through reserve function pre( address _scheme, bytes32 _hash, bytes32 _method ) public pure override returns (bool) { _scheme; _hash; _method; if (_method == "mintTokens") return false; return true; } function when() public pure override returns (CallPhase) { return CallPhase.Pre; } } // SPDX-License-Identifier: MIT /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >=0.8.0; contract DSMath { function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = (x * y) / 10**27; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = (x * (10**27)) / y; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./DAOContract.sol"; /** @title Simple contract that adds upgradability to DAOContract */ contract DAOUpgradeableContract is Initializable, UUPSUpgradeable, DAOContract { function _authorizeUpgrade(address) internal virtual override { _onlyAvatar(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../extensions/ERC20BurnableUpgradeable.sol"; import "../extensions/ERC20PausableUpgradeable.sol"; import "../../../access/AccessControlEnumerableUpgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC20PresetMinterPauserUpgradeable is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable { function initialize(string memory name, string memory symbol) public virtual initializer { __ERC20PresetMinterPauser_init(name, symbol); } 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}. */ function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC20_init_unchained(name, symbol); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); __ERC20PresetMinterPauser_init_unchained(name, symbol); } function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer { _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(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT 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 MerkleProofUpgradeable { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../utils/DSMath.sol"; import "../utils/BancorFormula.sol"; import "../DAOStackInterfaces.sol"; import "../Interfaces.sol"; import "../utils/DAOUpgradeableContract.sol"; /** @title Dynamic reserve ratio market maker */ contract GoodMarketMaker is DAOUpgradeableContract, DSMath { // Entity that holds a reserve token struct ReserveToken { // Determines the reserve token balance // that the reserve contract holds uint256 reserveSupply; // Determines the current ratio between // the reserve token and the GD token uint32 reserveRatio; // How many GD tokens have been minted // against that reserve token uint256 gdSupply; // Last time reserve ratio was expanded uint256 lastExpansion; } // The map which holds the reserve token entities mapping(address => ReserveToken) public reserveTokens; // Emits when a change has occurred in a // reserve balance, i.e. buy / sell will // change the balance event BalancesUpdated( // The account who initiated the action address indexed caller, // The address of the reserve token address indexed reserveToken, // The incoming amount uint256 amount, // The return value uint256 returnAmount, // The updated total supply uint256 totalSupply, // The updated reserve balance uint256 reserveBalance ); // Emits when the ratio changed. The caller should be the Avatar by definition event ReserveRatioUpdated(address indexed caller, uint256 nom, uint256 denom); // Defines the daily change in the reserve ratio in RAY precision. // In the current release, only global ratio expansion is supported. // That will be a part of each reserve token entity in the future. uint256 public reserveRatioDailyExpansion; //goodDollar token decimals uint256 decimals; /** * @dev Constructor * @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from * @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from */ function initialize( INameService _ns, uint256 _nom, uint256 _denom ) public virtual initializer { reserveRatioDailyExpansion = (_nom * 1e27) / _denom; decimals = 2; setDAO(_ns); } function _onlyActiveToken(ERC20 _token) internal view { ReserveToken storage rtoken = reserveTokens[address(_token)]; require(rtoken.gdSupply > 0, "Reserve token not initialized"); } function _onlyReserveOrAvatar() internal view { require( nameService.getAddress("RESERVE") == msg.sender || nameService.getAddress("AVATAR") == msg.sender, "GoodMarketMaker: not Reserve or Avatar" ); } function getBancor() public view returns (BancorFormula) { return BancorFormula(nameService.getAddress("BANCOR_FORMULA")); } /** * @dev Allows the DAO to change the daily expansion rate * it is calculated by _nom/_denom with e27 precision. Emits * `ReserveRatioUpdated` event after the ratio has changed. * Only Avatar can call this method. * @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from * @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from */ function setReserveRatioDailyExpansion(uint256 _nom, uint256 _denom) public { _onlyReserveOrAvatar(); require(_denom > 0, "denominator must be above 0"); reserveRatioDailyExpansion = (_nom * 1e27) / _denom; require(reserveRatioDailyExpansion < 1e27, "Invalid nom or denom value"); emit ReserveRatioUpdated(msg.sender, _nom, _denom); } // NOTICE: In the current release, if there is a wish to add another reserve token, // `end` method in the reserve contract should be called first. Then, the DAO have // to deploy a new reserve contract that will own the market maker. A scheme for // updating the new reserve must be deployed too. /** * @dev Initialize a reserve token entity with the given parameters * @param _token The reserve token * @param _gdSupply Initial supply of GD to set the price * @param _tokenSupply Initial supply of reserve token to set the price * @param _reserveRatio The starting reserve ratio * @param _lastExpansion Last time reserve ratio was expanded */ function initializeToken( ERC20 _token, uint256 _gdSupply, uint256 _tokenSupply, uint32 _reserveRatio, uint256 _lastExpansion ) public { _onlyReserveOrAvatar(); reserveTokens[address(_token)] = ReserveToken({ gdSupply: _gdSupply, reserveSupply: _tokenSupply, reserveRatio: _reserveRatio, lastExpansion: _lastExpansion == 0 ? block.timestamp : _lastExpansion }); } /** * @dev Calculates how much to decrease the reserve ratio for _token by * the `reserveRatioDailyExpansion` * @param _token The reserve token to calculate the reserve ratio for * @return The new reserve ratio */ function calculateNewReserveRatio(ERC20 _token) public view returns (uint32) { ReserveToken memory reserveToken = reserveTokens[address(_token)]; uint256 ratio = uint256(reserveToken.reserveRatio); if (ratio == 0) { ratio = 1e6; } ratio *= 1e21; //expand to e27 precision uint256 daysPassed = (block.timestamp - reserveToken.lastExpansion) / 1 days; for (uint256 i = 0; i < daysPassed; i++) { ratio = (ratio * reserveRatioDailyExpansion) / 1e27; } return uint32(ratio / 1e21); // return to e6 precision } /** * @dev Decreases the reserve ratio for _token by the `reserveRatioDailyExpansion` * @param _token The token to change the reserve ratio for * @return The new reserve ratio */ function expandReserveRatio(ERC20 _token) public returns (uint32) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); ReserveToken storage reserveToken = reserveTokens[address(_token)]; uint32 ratio = reserveToken.reserveRatio; if (ratio == 0) { ratio = 1e6; } reserveToken.reserveRatio = calculateNewReserveRatio(_token); //set last expansion to begining of expansion day reserveToken.lastExpansion = block.timestamp - ((block.timestamp - reserveToken.lastExpansion) % 1 days); return reserveToken.reserveRatio; } /** * @dev Calculates the buy return in GD according to the given _tokenAmount * @param _token The reserve token buying with * @param _tokenAmount The amount of reserve token buying with * @return Number of GD that should be given in exchange as calculated by the bonding curve */ function buyReturn(ERC20 _token, uint256 _tokenAmount) public view returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return getBancor().calculatePurchaseReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, _tokenAmount ); } /** * @dev Calculates the sell return in _token according to the given _gdAmount * @param _token The desired reserve token to have * @param _gdAmount The amount of GD that are sold * @return Number of tokens that should be given in exchange as calculated by the bonding curve */ function sellReturn(ERC20 _token, uint256 _gdAmount) public view returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return getBancor().calculateSaleReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, _gdAmount ); } /** * @dev Updates the _token bonding curve params. Emits `BalancesUpdated` with the * new reserve token information. * @param _token The reserve token buying with * @param _tokenAmount The amount of reserve token buying with * @return (gdReturn) Number of GD that will be given in exchange as calculated by the bonding curve */ function buy(ERC20 _token, uint256 _tokenAmount) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); uint256 gdReturn = buyReturn(_token, _tokenAmount); ReserveToken storage rtoken = reserveTokens[address(_token)]; rtoken.gdSupply += gdReturn; rtoken.reserveSupply += _tokenAmount; emit BalancesUpdated( msg.sender, address(_token), _tokenAmount, gdReturn, rtoken.gdSupply, rtoken.reserveSupply ); return gdReturn; } /** * @dev Updates the bonding curve params. Decrease RR to in order to mint gd in the amount of provided * new RR = Reserve supply / ((gd supply + gd mint amount) * price) * @param _gdAmount Amount of gd to add reserveParams * @param _token The reserve token which is currently active */ function mintFromReserveRatio(ERC20 _token, uint256 _gdAmount) public { _onlyReserveOrAvatar(); _onlyActiveToken(_token); uint256 reserveDecimalsDiff = uint256(27) - _token.decimals(); // //result is in RAY precision ReserveToken storage rtoken = reserveTokens[address(_token)]; uint256 priceBeforeGdSupplyChange = currentPrice(_token); rtoken.gdSupply += _gdAmount; rtoken.reserveRatio = uint32( ((rtoken.reserveSupply * 1e27) / (rtoken.gdSupply * priceBeforeGdSupplyChange)) / 10**reserveDecimalsDiff ); // Divide it decimal diff to bring it proper decimal } /** * @dev Calculates the sell return with contribution in _token and update the bonding curve params. * Emits `BalancesUpdated` with the new reserve token information. * @param _token The desired reserve token to have * @param _gdAmount The amount of GD that are sold * @param _contributionGdAmount The number of GD tokens that will not be traded for the reserve token * @return Number of tokens that will be given in exchange as calculated by the bonding curve */ function sellWithContribution( ERC20 _token, uint256 _gdAmount, uint256 _contributionGdAmount ) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); require( _gdAmount >= _contributionGdAmount, "GD amount is lower than the contribution amount" ); ReserveToken storage rtoken = reserveTokens[address(_token)]; require( rtoken.gdSupply >= _gdAmount, "GD amount is higher than the total supply" ); // Deduces the convertible amount of GD tokens by the given contribution amount uint256 amountAfterContribution = _gdAmount - _contributionGdAmount; // The return value after the deduction uint256 tokenReturn = sellReturn(_token, amountAfterContribution); rtoken.gdSupply -= _gdAmount; rtoken.reserveSupply -= tokenReturn; emit BalancesUpdated( msg.sender, address(_token), _contributionGdAmount, tokenReturn, rtoken.gdSupply, rtoken.reserveSupply ); return tokenReturn; } /** * @dev Current price of GD in `token`. currently only cDAI is supported. * @param _token The desired reserve token to have * @return price of GD */ function currentPrice(ERC20 _token) public view returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return getBancor().calculateSaleReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, (10**decimals) ); } //TODO: need real calculation and tests /** * @dev Calculates how much G$ to mint based on added token supply (from interest) * and on current reserve ratio, in order to keep G$ price the same at the bonding curve * formula to calculate the gd to mint: gd to mint = * addreservebalance * (gdsupply / (reservebalance * reserveratio)) * @param _token the reserve token * @param _addTokenSupply amount of token added to supply * @return how much to mint in order to keep price in bonding curve the same */ function calculateMintInterest(ERC20 _token, uint256 _addTokenSupply) public view returns (uint256) { uint256 decimalsDiff = uint256(27) - decimals; //resulting amount is in RAY precision //we divide by decimalsdiff to get precision in GD (2 decimals) return ((_addTokenSupply * 1e27) / currentPrice(_token)) / (10**decimalsDiff); } /** * @dev Updates bonding curve based on _addTokenSupply and new minted amount * @param _token The reserve token * @param _addTokenSupply Amount of token added to supply * @return How much to mint in order to keep price in bonding curve the same */ function mintInterest(ERC20 _token, uint256 _addTokenSupply) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); if (_addTokenSupply == 0) { return 0; } uint256 toMint = calculateMintInterest(_token, _addTokenSupply); ReserveToken storage reserveToken = reserveTokens[address(_token)]; reserveToken.gdSupply += toMint; reserveToken.reserveSupply += _addTokenSupply; return toMint; } /** * @dev Calculate how much G$ to mint based on expansion change (new reserve * ratio), in order to keep G$ price the same at the bonding curve. the * formula to calculate the gd to mint: gd to mint = * (reservebalance / (newreserveratio * currentprice)) - gdsupply * @param _token The reserve token * @return How much to mint in order to keep price in bonding curve the same */ function calculateMintExpansion(ERC20 _token) public view returns (uint256) { ReserveToken memory reserveToken = reserveTokens[address(_token)]; uint32 newReserveRatio = calculateNewReserveRatio(_token); // new reserve ratio uint256 reserveDecimalsDiff = uint256(27) - _token.decimals(); // //result is in RAY precision uint256 denom = (uint256(newReserveRatio) * 1e21 * currentPrice(_token) * (10**reserveDecimalsDiff)) / 1e27; // (newreserveratio * currentprice) in RAY precision uint256 gdDecimalsDiff = uint256(27) - decimals; uint256 toMint = ((reserveToken.reserveSupply * (10**reserveDecimalsDiff) * 1e27) / denom) / (10**gdDecimalsDiff); // reservebalance in RAY precision // return to gd precision return toMint - reserveToken.gdSupply; } /** * @dev Updates bonding curve based on expansion change and new minted amount * @param _token The reserve token * @return How much to mint in order to keep price in bonding curve the same */ function mintExpansion(ERC20 _token) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); uint256 toMint = calculateMintExpansion(_token); reserveTokens[address(_token)].gdSupply += toMint; expandReserveRatio(_token); return toMint; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer { } /** * @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"); } uint256[50] private __gap; } // 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 "./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 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; /** * @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 "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; contract BancorFormula { using SafeMathUpgradeable for uint256; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; // Auto-generated via 'PrintIntScalingFactors.py' uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; // Auto-generated via 'PrintLn2ScalingFactors.py' uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; // Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; // Auto-generated via 'PrintLambertFactors.py' uint256 private constant LAMBERT_CONV_RADIUS = 0x002f16ac6c59de6f8d5d6f63c1482a7c86; uint256 private constant LAMBERT_POS2_SAMPLE = 0x0003060c183060c183060c183060c18306; uint256 private constant LAMBERT_POS2_MAXVAL = 0x01af16ac6c59de6f8d5d6f63c1482a7c80; uint256 private constant LAMBERT_POS3_MAXVAL = 0x6b22d43e72c326539cceeef8bb48f255ff; // Auto-generated via 'PrintWeightFactors.py' uint256 private constant MAX_UNF_WEIGHT = 0x10c6f7a0b5ed8d36b4c7f34938583621fafc8b0079a2834d26fa3fcc9ea9; // Auto-generated via 'PrintMaxExpArray.py' uint256[128] private maxExpArray; function initMaxExpArray() private { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } // Auto-generated via 'PrintLambertArray.py' uint256[128] private lambertArray; function initLambertArray() private { lambertArray[0] = 0x60e393c68d20b1bd09deaabc0373b9c5; lambertArray[1] = 0x5f8f46e4854120989ed94719fb4c2011; lambertArray[2] = 0x5e479ebb9129fb1b7e72a648f992b606; lambertArray[3] = 0x5d0bd23fe42dfedde2e9586be12b85fe; lambertArray[4] = 0x5bdb29ddee979308ddfca81aeeb8095a; lambertArray[5] = 0x5ab4fd8a260d2c7e2c0d2afcf0009dad; lambertArray[6] = 0x5998b31359a55d48724c65cf09001221; lambertArray[7] = 0x5885bcad2b322dfc43e8860f9c018cf5; lambertArray[8] = 0x577b97aa1fe222bb452fdf111b1f0be2; lambertArray[9] = 0x5679cb5e3575632e5baa27e2b949f704; lambertArray[10] = 0x557fe8241b3a31c83c732f1cdff4a1c5; lambertArray[11] = 0x548d868026504875d6e59bbe95fc2a6b; lambertArray[12] = 0x53a2465ce347cf34d05a867c17dd3088; lambertArray[13] = 0x52bdce5dcd4faed59c7f5511cf8f8acc; lambertArray[14] = 0x51dfcb453c07f8da817606e7885f7c3e; lambertArray[15] = 0x5107ef6b0a5a2be8f8ff15590daa3cce; lambertArray[16] = 0x5035f241d6eae0cd7bacba119993de7b; lambertArray[17] = 0x4f698fe90d5b53d532171e1210164c66; lambertArray[18] = 0x4ea288ca297a0e6a09a0eee240e16c85; lambertArray[19] = 0x4de0a13fdcf5d4213fc398ba6e3becde; lambertArray[20] = 0x4d23a145eef91fec06b06140804c4808; lambertArray[21] = 0x4c6b5430d4c1ee5526473db4ae0f11de; lambertArray[22] = 0x4bb7886c240562eba11f4963a53b4240; lambertArray[23] = 0x4b080f3f1cb491d2d521e0ea4583521e; lambertArray[24] = 0x4a5cbc96a05589cb4d86be1db3168364; lambertArray[25] = 0x49b566d40243517658d78c33162d6ece; lambertArray[26] = 0x4911e6a02e5507a30f947383fd9a3276; lambertArray[27] = 0x487216c2b31be4adc41db8a8d5cc0c88; lambertArray[28] = 0x47d5d3fc4a7a1b188cd3d788b5c5e9fc; lambertArray[29] = 0x473cfce4871a2c40bc4f9e1c32b955d0; lambertArray[30] = 0x46a771ca578ab878485810e285e31c67; lambertArray[31] = 0x4615149718aed4c258c373dc676aa72d; lambertArray[32] = 0x4585c8b3f8fe489c6e1833ca47871384; lambertArray[33] = 0x44f972f174e41e5efb7e9d63c29ce735; lambertArray[34] = 0x446ff970ba86d8b00beb05ecebf3c4dc; lambertArray[35] = 0x43e9438ec88971812d6f198b5ccaad96; lambertArray[36] = 0x436539d11ff7bea657aeddb394e809ef; lambertArray[37] = 0x42e3c5d3e5a913401d86f66db5d81c2c; lambertArray[38] = 0x4264d2395303070ea726cbe98df62174; lambertArray[39] = 0x41e84a9a593bb7194c3a6349ecae4eea; lambertArray[40] = 0x416e1b785d13eba07a08f3f18876a5ab; lambertArray[41] = 0x40f6322ff389d423ba9dd7e7e7b7e809; lambertArray[42] = 0x40807cec8a466880ecf4184545d240a4; lambertArray[43] = 0x400cea9ce88a8d3ae668e8ea0d9bf07f; lambertArray[44] = 0x3f9b6ae8772d4c55091e0ed7dfea0ac1; lambertArray[45] = 0x3f2bee253fd84594f54bcaafac383a13; lambertArray[46] = 0x3ebe654e95208bb9210c575c081c5958; lambertArray[47] = 0x3e52c1fc5665635b78ce1f05ad53c086; lambertArray[48] = 0x3de8f65ac388101ddf718a6f5c1eff65; lambertArray[49] = 0x3d80f522d59bd0b328ca012df4cd2d49; lambertArray[50] = 0x3d1ab193129ea72b23648a161163a85a; lambertArray[51] = 0x3cb61f68d32576c135b95cfb53f76d75; lambertArray[52] = 0x3c5332d9f1aae851a3619e77e4cc8473; lambertArray[53] = 0x3bf1e08edbe2aa109e1525f65759ef73; lambertArray[54] = 0x3b921d9cff13fa2c197746a3dfc4918f; lambertArray[55] = 0x3b33df818910bfc1a5aefb8f63ae2ac4; lambertArray[56] = 0x3ad71c1c77e34fa32a9f184967eccbf6; lambertArray[57] = 0x3a7bc9abf2c5bb53e2f7384a8a16521a; lambertArray[58] = 0x3a21dec7e76369783a68a0c6385a1c57; lambertArray[59] = 0x39c9525de6c9cdf7c1c157ca4a7a6ee3; lambertArray[60] = 0x39721bad3dc85d1240ff0190e0adaac3; lambertArray[61] = 0x391c324344d3248f0469eb28dd3d77e0; lambertArray[62] = 0x38c78df7e3c796279fb4ff84394ab3da; lambertArray[63] = 0x387426ea4638ae9aae08049d3554c20a; lambertArray[64] = 0x3821f57dbd2763256c1a99bbd2051378; lambertArray[65] = 0x37d0f256cb46a8c92ff62fbbef289698; lambertArray[66] = 0x37811658591ffc7abdd1feaf3cef9b73; lambertArray[67] = 0x37325aa10e9e82f7df0f380f7997154b; lambertArray[68] = 0x36e4b888cfb408d873b9a80d439311c6; lambertArray[69] = 0x3698299e59f4bb9de645fc9b08c64cca; lambertArray[70] = 0x364ca7a5012cb603023b57dd3ebfd50d; lambertArray[71] = 0x36022c928915b778ab1b06aaee7e61d4; lambertArray[72] = 0x35b8b28d1a73dc27500ffe35559cc028; lambertArray[73] = 0x357033e951fe250ec5eb4e60955132d7; lambertArray[74] = 0x3528ab2867934e3a21b5412e4c4f8881; lambertArray[75] = 0x34e212f66c55057f9676c80094a61d59; lambertArray[76] = 0x349c66289e5b3c4b540c24f42fa4b9bb; lambertArray[77] = 0x34579fbbd0c733a9c8d6af6b0f7d00f7; lambertArray[78] = 0x3413bad2e712288b924b5882b5b369bf; lambertArray[79] = 0x33d0b2b56286510ef730e213f71f12e9; lambertArray[80] = 0x338e82ce00e2496262c64457535ba1a1; lambertArray[81] = 0x334d26a96b373bb7c2f8ea1827f27a92; lambertArray[82] = 0x330c99f4f4211469e00b3e18c31475ea; lambertArray[83] = 0x32ccd87d6486094999c7d5e6f33237d8; lambertArray[84] = 0x328dde2dd617b6665a2e8556f250c1af; lambertArray[85] = 0x324fa70e9adc270f8262755af5a99af9; lambertArray[86] = 0x32122f443110611ca51040f41fa6e1e3; lambertArray[87] = 0x31d5730e42c0831482f0f1485c4263d8; lambertArray[88] = 0x31996ec6b07b4a83421b5ebc4ab4e1f1; lambertArray[89] = 0x315e1ee0a68ff46bb43ec2b85032e876; lambertArray[90] = 0x31237fe7bc4deacf6775b9efa1a145f8; lambertArray[91] = 0x30e98e7f1cc5a356e44627a6972ea2ff; lambertArray[92] = 0x30b04760b8917ec74205a3002650ec05; lambertArray[93] = 0x3077a75c803468e9132ce0cf3224241d; lambertArray[94] = 0x303fab57a6a275c36f19cda9bace667a; lambertArray[95] = 0x3008504beb8dcbd2cf3bc1f6d5a064f0; lambertArray[96] = 0x2fd19346ed17dac61219ce0c2c5ac4b0; lambertArray[97] = 0x2f9b7169808c324b5852fd3d54ba9714; lambertArray[98] = 0x2f65e7e711cf4b064eea9c08cbdad574; lambertArray[99] = 0x2f30f405093042ddff8a251b6bf6d103; lambertArray[100] = 0x2efc931a3750f2e8bfe323edfe037574; lambertArray[101] = 0x2ec8c28e46dbe56d98685278339400cb; lambertArray[102] = 0x2e957fd933c3926d8a599b602379b851; lambertArray[103] = 0x2e62c882c7c9ed4473412702f08ba0e5; lambertArray[104] = 0x2e309a221c12ba361e3ed695167feee2; lambertArray[105] = 0x2dfef25d1f865ae18dd07cfea4bcea10; lambertArray[106] = 0x2dcdcee821cdc80decc02c44344aeb31; lambertArray[107] = 0x2d9d2d8562b34944d0b201bb87260c83; lambertArray[108] = 0x2d6d0c04a5b62a2c42636308669b729a; lambertArray[109] = 0x2d3d6842c9a235517fc5a0332691528f; lambertArray[110] = 0x2d0e402963fe1ea2834abc408c437c10; lambertArray[111] = 0x2cdf91ae602647908aff975e4d6a2a8c; lambertArray[112] = 0x2cb15ad3a1eb65f6d74a75da09a1b6c5; lambertArray[113] = 0x2c8399a6ab8e9774d6fcff373d210727; lambertArray[114] = 0x2c564c4046f64edba6883ca06bbc4535; lambertArray[115] = 0x2c2970c431f952641e05cb493e23eed3; lambertArray[116] = 0x2bfd0560cd9eb14563bc7c0732856c18; lambertArray[117] = 0x2bd1084ed0332f7ff4150f9d0ef41a2c; lambertArray[118] = 0x2ba577d0fa1628b76d040b12a82492fb; lambertArray[119] = 0x2b7a5233cd21581e855e89dc2f1e8a92; lambertArray[120] = 0x2b4f95cd46904d05d72bdcde337d9cc7; lambertArray[121] = 0x2b2540fc9b4d9abba3faca6691914675; lambertArray[122] = 0x2afb5229f68d0830d8be8adb0a0db70f; lambertArray[123] = 0x2ad1c7c63a9b294c5bc73a3ba3ab7a2b; lambertArray[124] = 0x2aa8a04ac3cbe1ee1c9c86361465dbb8; lambertArray[125] = 0x2a7fda392d725a44a2c8aeb9ab35430d; lambertArray[126] = 0x2a57741b18cde618717792b4faa216db; lambertArray[127] = 0x2a2f6c81f5d84dd950a35626d6d5503a; } /** * @dev should be executed after construction (too large for the constructor) */ function init() public { initMaxExpArray(); initLambertArray(); } /** * @dev given a token supply, reserve balance, weight and a deposit amount (in the reserve token), * calculates the target amount for a given conversion (in the main token) * * Formula: * return = _supply * ((1 + _amount / _reserveBalance) ^ (_reserveWeight / 1000000) - 1) * * @param _supply liquid token supply * @param _reserveBalance reserve balance * @param _reserveWeight reserve weight, represented in ppm (1-1000000) * @param _amount amount of reserve tokens to get the target amount for * * @return target */ function purchaseTargetAmount( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT" ); // special case for 0 deposit amount if (_amount == 0) return 0; // special case if the weight = 100% if (_reserveWeight == MAX_WEIGHT) return _supply.mul(_amount) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _amount.add(_reserveBalance); (result, precision) = power( baseN, _reserveBalance, _reserveWeight, MAX_WEIGHT ); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** * @dev given a token supply, reserve balance, weight and a sell amount (in the main token), * calculates the target amount for a given conversion (in the reserve token) * * Formula: * return = _reserveBalance * (1 - (1 - _amount / _supply) ^ (1000000 / _reserveWeight)) * * @param _supply liquid token supply * @param _reserveBalance reserve balance * @param _reserveWeight reserve weight, represented in ppm (1-1000000) * @param _amount amount of liquid tokens to get the target amount for * * @return reserve token amount */ function saleTargetAmount( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT" ); require(_amount <= _supply, "ERR_INVALID_AMOUNT"); // special case for 0 sell amount if (_amount == 0) return 0; // special case for selling the entire supply if (_amount == _supply) return _reserveBalance; // special case if the weight = 100% if (_reserveWeight == MAX_WEIGHT) return _reserveBalance.mul(_amount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _amount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveWeight); uint256 temp1 = _reserveBalance.mul(result); uint256 temp2 = _reserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev given two reserve balances/weights and a sell amount (in the first reserve token), * calculates the target amount for a conversion from the source reserve token to the target reserve token * * Formula: * return = _targetReserveBalance * (1 - (_sourceReserveBalance / (_sourceReserveBalance + _amount)) ^ (_sourceReserveWeight / _targetReserveWeight)) * * @param _sourceReserveBalance source reserve balance * @param _sourceReserveWeight source reserve weight, represented in ppm (1-1000000) * @param _targetReserveBalance target reserve balance * @param _targetReserveWeight target reserve weight, represented in ppm (1-1000000) * @param _amount source reserve amount * * @return target reserve amount */ function crossReserveTargetAmount( uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount ) public view returns (uint256) { // validate input require( _sourceReserveBalance > 0 && _targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE" ); require( _sourceReserveWeight > 0 && _sourceReserveWeight <= MAX_WEIGHT && _targetReserveWeight > 0 && _targetReserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT" ); // special case for equal weights if (_sourceReserveWeight == _targetReserveWeight) return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _sourceReserveBalance.add(_amount); (result, precision) = power( baseN, _sourceReserveBalance, _sourceReserveWeight, _targetReserveWeight ); uint256 temp1 = _targetReserveBalance.mul(result); uint256 temp2 = _targetReserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev given a pool token supply, reserve balance, reserve ratio and an amount of requested pool tokens, * calculates the amount of reserve tokens required for purchasing the given amount of pool tokens * * Formula: * return = _reserveBalance * (((_supply + _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio) - 1) * * @param _supply pool token supply * @param _reserveBalance reserve balance * @param _reserveRatio reserve ratio, represented in ppm (2-2000000) * @param _amount requested amount of pool tokens * * @return reserve token amount */ function fundCost( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO" ); // special case for 0 amount if (_amount == 0) return 0; // special case if the reserve ratio = 100% if (_reserveRatio == MAX_WEIGHT) return (_amount.mul(_reserveBalance) - 1) / _supply + 1; uint256 result; uint8 precision; uint256 baseN = _supply.add(_amount); (result, precision) = power(baseN, _supply, MAX_WEIGHT, _reserveRatio); uint256 temp = ((_reserveBalance.mul(result) - 1) >> precision) + 1; return temp - _reserveBalance; } /** * @dev given a pool token supply, reserve balance, reserve ratio and an amount of reserve tokens to fund with, * calculates the amount of pool tokens received for purchasing with the given amount of reserve tokens * * Formula: * return = _supply * ((_amount / _reserveBalance + 1) ^ (_reserveRatio / MAX_WEIGHT) - 1) * * @param _supply pool token supply * @param _reserveBalance reserve balance * @param _reserveRatio reserve ratio, represented in ppm (2-2000000) * @param _amount amount of reserve tokens to fund with * * @return pool token amount */ function fundSupplyAmount( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO" ); // special case for 0 amount if (_amount == 0) return 0; // special case if the reserve ratio = 100% if (_reserveRatio == MAX_WEIGHT) return _amount.mul(_supply) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _reserveBalance.add(_amount); (result, precision) = power( baseN, _reserveBalance, _reserveRatio, MAX_WEIGHT ); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** * @dev given a pool token supply, reserve balance, reserve ratio and an amount of pool tokens to liquidate, * calculates the amount of reserve tokens received for selling the given amount of pool tokens * * Formula: * return = _reserveBalance * (1 - ((_supply - _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio)) * * @param _supply pool token supply * @param _reserveBalance reserve balance * @param _reserveRatio reserve ratio, represented in ppm (2-2000000) * @param _amount amount of pool tokens to liquidate * * @return reserve token amount */ function liquidateReserveAmount( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO" ); require(_amount <= _supply, "ERR_INVALID_AMOUNT"); // special case for 0 amount if (_amount == 0) return 0; // special case for liquidating the entire supply if (_amount == _supply) return _reserveBalance; // special case if the reserve ratio = 100% if (_reserveRatio == MAX_WEIGHT) return _amount.mul(_reserveBalance) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _amount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveRatio); uint256 temp1 = _reserveBalance.mul(result); uint256 temp2 = _reserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev The arbitrage incentive is to convert to the point where the on-chain price is equal to the off-chain price. * We want this operation to also impact the primary reserve balance becoming equal to the primary reserve staked balance. * In other words, we want the arbitrager to convert the difference between the reserve balance and the reserve staked balance. * * Formula input: * - let t denote the primary reserve token staked balance * - let s denote the primary reserve token balance * - let r denote the secondary reserve token balance * - let q denote the numerator of the rate between the tokens * - let p denote the denominator of the rate between the tokens * Where p primary tokens are equal to q secondary tokens * * Formula output: * - compute x = W(t / r * q / p * log(s / t)) / log(s / t) * - return x / (1 + x) as the weight of the primary reserve token * - return 1 / (1 + x) as the weight of the secondary reserve token * Where W is the Lambert W Function * * If the rate-provider provides the rates for a common unit, for example: * - P = 2 ==> 2 primary reserve tokens = 1 ether * - Q = 3 ==> 3 secondary reserve tokens = 1 ether * Then you can simply use p = P and q = Q * * If the rate-provider provides the rates for a single unit, for example: * - P = 2 ==> 1 primary reserve token = 2 ethers * - Q = 3 ==> 1 secondary reserve token = 3 ethers * Then you can simply use p = Q and q = P * * @param _primaryReserveStakedBalance the primary reserve token staked balance * @param _primaryReserveBalance the primary reserve token balance * @param _secondaryReserveBalance the secondary reserve token balance * @param _reserveRateNumerator the numerator of the rate between the tokens * @param _reserveRateDenominator the denominator of the rate between the tokens * * Note that `numerator / denominator` should represent the amount of secondary tokens equal to one primary token * * @return the weight of the primary reserve token and the weight of the secondary reserve token, both in ppm (0-1000000) */ function balancedWeights( uint256 _primaryReserveStakedBalance, uint256 _primaryReserveBalance, uint256 _secondaryReserveBalance, uint256 _reserveRateNumerator, uint256 _reserveRateDenominator ) public view returns (uint32, uint32) { if (_primaryReserveStakedBalance == _primaryReserveBalance) require( _primaryReserveStakedBalance > 0 || _secondaryReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE" ); else require( _primaryReserveStakedBalance > 0 && _primaryReserveBalance > 0 && _secondaryReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE" ); require( _reserveRateNumerator > 0 && _reserveRateDenominator > 0, "ERR_INVALID_RESERVE_RATE" ); uint256 tq = _primaryReserveStakedBalance.mul(_reserveRateNumerator); uint256 rp = _secondaryReserveBalance.mul(_reserveRateDenominator); if (_primaryReserveStakedBalance < _primaryReserveBalance) return balancedWeightsByStake( _primaryReserveBalance, _primaryReserveStakedBalance, tq, rp, true ); if (_primaryReserveStakedBalance > _primaryReserveBalance) return balancedWeightsByStake( _primaryReserveStakedBalance, _primaryReserveBalance, tq, rp, false ); return normalizedWeights(tq, rp); } /** * @dev General Description: * Determine a value of precision. * Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. * Return the result along with the precision used. * * Detailed Description: * Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". * The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". * The larger "precision" is, the more accurately this value represents the real value. * However, the larger "precision" is, the more bits are required in order to store this value. * And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). * This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". * Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. * This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. * This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". * Since we rely on unsigned-integer arithmetic and "base < 1" ==> "log(base) < 0", this function does not support "_baseN < _baseD". */ function power( uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD ) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = (_baseN * FIXED_1) / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = (baseLog * _expN) / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return ( generalExp( baseLogTimesExp >> (MAX_PRECISION - precision), precision ), precision ); } } /** * @dev computes log(x / FIXED_1) * FIXED_1. * This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return (res * LN2_NUMERATOR) / LN2_DENOMINATOR; } /** * @dev computes the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** * @dev the global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: * - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] * - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); } /** * @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. * it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". * it returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. * the global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". * the maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** * @dev computes log(x / FIXED_1) * FIXED_1 * Input range: FIXED_1 <= x <= OPT_LOG_MAX_VAL - 1 * Auto-generated via 'PrintFunctionOptimalLog.py' * Detailed description: * - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 * - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent * - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 * - The natural logarithm of the input is calculated by summing up the intermediate results above * - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) { res += 0x40000000000000000000000000000000; x = (x * FIXED_1) / 0xd3094c70f034de4b96ff7d5b6f99fcd8; } // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) { res += 0x20000000000000000000000000000000; x = (x * FIXED_1) / 0xa45af1e1f40c333b3de1db4dd55f29a7; } // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) { res += 0x10000000000000000000000000000000; x = (x * FIXED_1) / 0x910b022db7ae67ce76b441c27035c6a1; } // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) { res += 0x08000000000000000000000000000000; x = (x * FIXED_1) / 0x88415abbe9a76bead8d00cf112e4d4a8; } // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) { res += 0x04000000000000000000000000000000; x = (x * FIXED_1) / 0x84102b00893f64c705e841d5d4064bd3; } // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) { res += 0x02000000000000000000000000000000; x = (x * FIXED_1) / 0x8204055aaef1c8bd5c3259f4822735a2; } // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) { res += 0x01000000000000000000000000000000; x = (x * FIXED_1) / 0x810100ab00222d861931c15e39b44e99; } // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) { res += 0x00800000000000000000000000000000; x = (x * FIXED_1) / 0x808040155aabbbe9451521693554f733; } // add 1 / 2^8 z = y = x - FIXED_1; w = (y * y) / FIXED_1; res += (z * (0x100000000000000000000000000000000 - y)) / 0x100000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02 res += (z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) / 0x200000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04 res += (z * (0x099999999999999999999999999999999 - y)) / 0x300000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06 res += (z * (0x092492492492492492492492492492492 - y)) / 0x400000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08 res += (z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) / 0x500000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10 res += (z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) / 0x600000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12 res += (z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) / 0x700000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14 res += (z * (0x088888888888888888888888888888888 - y)) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = (z * y) / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 */ function lowerStake(uint256 _x) internal view returns (uint256) { if (_x <= LAMBERT_CONV_RADIUS) return lambertPos1(_x); if (_x <= LAMBERT_POS2_MAXVAL) return lambertPos2(_x); if (_x <= LAMBERT_POS3_MAXVAL) return lambertPos3(_x); require(false); } /** * @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1 */ function higherStake(uint256 _x) internal pure returns (uint256) { if (_x <= LAMBERT_CONV_RADIUS) return lambertNeg1(_x); return (FIXED_1 * FIXED_1) / _x; } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 * input range: 1 <= x <= 1 / e * FIXED_1 * auto-generated via 'PrintFunctionLambertPos1.py' */ function lambertPos1(uint256 _x) internal pure returns (uint256) { uint256 xi = _x; uint256 res = (FIXED_1 - _x) * 0xde1bc4d19efcac82445da75b00000000; // x^(1-1) * (34! * 1^(1-1) / 1!) - x^(2-1) * (34! * 2^(2-1) / 2!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // sub x^(04-1) * (34! * 04^(04-1) / 04!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // sub x^(06-1) * (34! * 06^(06-1) / 06!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!) xi = (xi * _x) / FIXED_1; res -= xi * 0x000000002d207601f46a99b4112418400000000000; // sub x^(08-1) * (34! * 08^(08-1) / 08!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // sub x^(10-1) * (34! * 10^(10-1) / 10!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // sub x^(12-1) * (34! * 12^(12-1) / 12!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // sub x^(14-1) * (34! * 14^(14-1) / 14!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!) xi = (xi * _x) / FIXED_1; res -= xi * 0x000000bac08546b867cdaa20000000000000000000; // sub x^(16-1) * (34! * 16^(16-1) / 16!) xi = (xi * _x) / FIXED_1; res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!) xi = (xi * _x) / FIXED_1; res -= xi * 0x000004851d99f82060df265f3309b26f8200000000; // sub x^(18-1) * (34! * 18^(18-1) / 18!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // sub x^(20-1) * (34! * 20^(20-1) / 20!) xi = (xi * _x) / FIXED_1; res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // sub x^(22-1) * (34! * 22^(22-1) / 22!) xi = (xi * _x) / FIXED_1; res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // sub x^(24-1) * (34! * 24^(24-1) / 24!) xi = (xi * _x) / FIXED_1; res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!) xi = (xi * _x) / FIXED_1; res -= xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // sub x^(26-1) * (34! * 26^(26-1) / 26!) xi = (xi * _x) / FIXED_1; res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // sub x^(28-1) * (34! * 28^(28-1) / 28!) xi = (xi * _x) / FIXED_1; res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!) xi = (xi * _x) / FIXED_1; res -= xi * 0x053a044ebd984351493e1786af38d39a0800000000; // sub x^(30-1) * (34! * 30^(30-1) / 30!) xi = (xi * _x) / FIXED_1; res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!) xi = (xi * _x) / FIXED_1; res -= xi * 0x231000000000000000000000000000000000000000; // sub x^(32-1) * (34! * 32^(32-1) / 32!) xi = (xi * _x) / FIXED_1; res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!) xi = (xi * _x) / FIXED_1; res -= xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // sub x^(34-1) * (34! * 34^(34-1) / 34!) return res / 0xde1bc4d19efcac82445da75b00000000; // divide by 34! } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 * input range: LAMBERT_CONV_RADIUS + 1 <= x <= LAMBERT_POS2_MAXVAL */ function lambertPos2(uint256 _x) internal view returns (uint256) { uint256 x = _x - LAMBERT_CONV_RADIUS - 1; uint256 i = x / LAMBERT_POS2_SAMPLE; uint256 a = LAMBERT_POS2_SAMPLE * i; uint256 b = LAMBERT_POS2_SAMPLE * (i + 1); uint256 c = lambertArray[i]; uint256 d = lambertArray[i + 1]; return (c * (b - x) + d * (x - a)) / LAMBERT_POS2_SAMPLE; } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 * input range: LAMBERT_POS2_MAXVAL + 1 <= x <= LAMBERT_POS3_MAXVAL */ function lambertPos3(uint256 _x) internal pure returns (uint256) { uint256 l1 = _x < OPT_LOG_MAX_VAL ? optimalLog(_x) : generalLog(_x); uint256 l2 = l1 < OPT_LOG_MAX_VAL ? optimalLog(l1) : generalLog(l1); return ((l1 - l2 + (l2 * FIXED_1) / l1) * FIXED_1) / _x; } /** * @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1 * input range: 1 <= x <= 1 / e * FIXED_1 * auto-generated via 'PrintFunctionLambertNeg1.py' */ function lambertNeg1(uint256 _x) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) / FIXED_1; res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // add x^(04-1) * (34! * 04^(04-1) / 04!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // add x^(06-1) * (34! * 06^(06-1) / 06!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000002d207601f46a99b4112418400000000000; // add x^(08-1) * (34! * 08^(08-1) / 08!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // add x^(10-1) * (34! * 10^(10-1) / 10!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // add x^(12-1) * (34! * 12^(12-1) / 12!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // add x^(14-1) * (34! * 14^(14-1) / 14!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000bac08546b867cdaa20000000000000000000; // add x^(16-1) * (34! * 16^(16-1) / 16!) xi = (xi * _x) / FIXED_1; res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!) xi = (xi * _x) / FIXED_1; res += xi * 0x000004851d99f82060df265f3309b26f8200000000; // add x^(18-1) * (34! * 18^(18-1) / 18!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!) xi = (xi * _x) / FIXED_1; res += xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // add x^(20-1) * (34! * 20^(20-1) / 20!) xi = (xi * _x) / FIXED_1; res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // add x^(22-1) * (34! * 22^(22-1) / 22!) xi = (xi * _x) / FIXED_1; res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!) xi = (xi * _x) / FIXED_1; res += xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // add x^(24-1) * (34! * 24^(24-1) / 24!) xi = (xi * _x) / FIXED_1; res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!) xi = (xi * _x) / FIXED_1; res += xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // add x^(26-1) * (34! * 26^(26-1) / 26!) xi = (xi * _x) / FIXED_1; res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!) xi = (xi * _x) / FIXED_1; res += xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // add x^(28-1) * (34! * 28^(28-1) / 28!) xi = (xi * _x) / FIXED_1; res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!) xi = (xi * _x) / FIXED_1; res += xi * 0x053a044ebd984351493e1786af38d39a0800000000; // add x^(30-1) * (34! * 30^(30-1) / 30!) xi = (xi * _x) / FIXED_1; res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!) xi = (xi * _x) / FIXED_1; res += xi * 0x231000000000000000000000000000000000000000; // add x^(32-1) * (34! * 32^(32-1) / 32!) xi = (xi * _x) / FIXED_1; res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!) xi = (xi * _x) / FIXED_1; res += xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // add x^(34-1) * (34! * 34^(34-1) / 34!) return res / 0xde1bc4d19efcac82445da75b00000000 + _x + FIXED_1; // divide by 34! and then add x^(2-1) * (34! * 2^(2-1) / 2!) + x^(1-1) * (34! * 1^(1-1) / 1!) } /** * @dev computes the weights based on "W(log(hi / lo) * tq / rp) * tq / rp", where "W" is a variation of the Lambert W function. */ function balancedWeightsByStake( uint256 _hi, uint256 _lo, uint256 _tq, uint256 _rp, bool _lowerStake ) internal view returns (uint32, uint32) { (_tq, _rp) = safeFactors(_tq, _rp); uint256 f = _hi.mul(FIXED_1) / _lo; uint256 g = f < OPT_LOG_MAX_VAL ? optimalLog(f) : generalLog(f); uint256 x = g.mul(_tq) / _rp; uint256 y = _lowerStake ? lowerStake(x) : higherStake(x); return normalizedWeights(y.mul(_tq), _rp.mul(FIXED_1)); } /** * @dev reduces "a" and "b" while maintaining their ratio. */ function safeFactors(uint256 _a, uint256 _b) internal pure returns (uint256, uint256) { if (_a <= FIXED_2 && _b <= FIXED_2) return (_a, _b); if (_a < FIXED_2) return ((_a * FIXED_2) / _b, FIXED_2); if (_b < FIXED_2) return (FIXED_2, (_b * FIXED_2) / _a); uint256 c = _a > _b ? _a : _b; uint256 n = floorLog2(c / FIXED_1); return (_a >> n, _b >> n); } /** * @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)". */ function normalizedWeights(uint256 _a, uint256 _b) internal pure returns (uint32, uint32) { if (_a <= _b) return accurateWeights(_a, _b); (uint32 y, uint32 x) = accurateWeights(_b, _a); return (x, y); } /** * @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)", assuming that "a <= b". */ function accurateWeights(uint256 _a, uint256 _b) internal pure returns (uint32, uint32) { if (_a > MAX_UNF_WEIGHT) { uint256 c = _a / (MAX_UNF_WEIGHT + 1) + 1; _a /= c; _b /= c; } uint256 x = roundDiv(_a * MAX_WEIGHT, _a.add(_b)); uint256 y = MAX_WEIGHT - x; return (uint32(x), uint32(y)); } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + (_n % _d) / (_d - _d / 2); } /** * @dev deprecated, backward compatibility */ function calculatePurchaseReturn( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { return purchaseTargetAmount( _supply, _reserveBalance, _reserveWeight, _amount ); } /** * @dev deprecated, backward compatibility */ function calculateSaleReturn( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { return saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function calculateCrossReserveReturn( uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount ) public view returns (uint256) { return crossReserveTargetAmount( _sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount ); } /** * @dev deprecated, backward compatibility */ function calculateCrossConnectorReturn( uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount ) public view returns (uint256) { return crossReserveTargetAmount( _sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount ); } /** * @dev deprecated, backward compatibility */ function calculateFundCost( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { return fundCost(_supply, _reserveBalance, _reserveRatio, _amount); } /** * @dev deprecated, backward compatibility */ function calculateLiquidateReturn( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { return liquidateReserveAmount( _supply, _reserveBalance, _reserveRatio, _amount ); } /** * @dev deprecated, backward compatibility */ function purchaseRate( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { return purchaseTargetAmount( _supply, _reserveBalance, _reserveWeight, _amount ); } /** * @dev deprecated, backward compatibility */ function saleRate( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { return saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function crossReserveRate( uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount ) public view returns (uint256) { return crossReserveTargetAmount( _sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount ); } /** * @dev deprecated, backward compatibility */ function liquidateRate( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { return liquidateReserveAmount( _supply, _reserveBalance, _reserveRatio, _amount ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./Reputation.sol"; import "../Interfaces.sol"; /** * @title GReputation extends Reputation with delegation and cross blockchain merkle states * @dev NOTICE: this breaks DAOStack nativeReputation usage, since it is not possiible to upgrade * the original nativeReputation token. it means you can no longer rely on avatar.nativeReputation() or controller.nativeReputation() * to return the current reputation token. * The DAO avatar will be the owner of this reputation token and not the Controller. * Minting by the DAO will be done using controller.genericCall and not via controller.mintReputation */ contract GReputation is Reputation { bytes32 public constant ROOT_STATE = keccak256("rootState"); /// @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 delegate,uint256 nonce,uint256 expiry)"); /// @notice describe a single blockchain states /// @param stateHash the hash with the reputation state /// @param hashType the type of hash. currently just 0 = merkle tree root hash /// @param totalSupply the totalSupply at the blockchain /// @param blockNumber the effective blocknumber struct BlockchainState { bytes32 stateHash; uint256 hashType; uint256 totalSupply; uint256 blockNumber; uint256[5] __reserevedSpace; } /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice mapping from blockchain id hash to list of states mapping(bytes32 => BlockchainState[]) public blockchainStates; /// @notice mapping from stateHash to the user balance can be >0 only after supplying state proof mapping(bytes32 => mapping(address => uint256)) public stateHashBalances; /// @notice list of blockchains having a statehash for easy iteration bytes32[] public activeBlockchains; /// @notice keep map of user -> delegate mapping(address => address) public delegates; /// @notice map of user non delegated + delegated votes to user. this is used for actual voting mapping(address => uint256[]) public activeVotes; /// @notice keep map of address -> reputation recipient, an address can set that its earned rep will go to another address mapping(address => address) public reputationRecipients; /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, address indexed delegator, uint256 previousBalance, uint256 newBalance ); event StateHash(string blockchain, bytes32 merkleRoot, uint256 totalSupply); event StateHashProof(string blockchain, address user, uint256 repBalance); /** * @dev initialize */ function initialize( INameService _ns, string calldata _stateId, bytes32 _stateHash, uint256 _totalSupply ) external initializer { __Reputation_init(_ns); if (_totalSupply > 0) _setBlockchainStateHash(_stateId, _stateHash, _totalSupply); } function _canMint() internal view override { require( _msgSender() == nameService.getAddress("GDAO_CLAIMERS") || _msgSender() == nameService.getAddress("GDAO_STAKING") || _msgSender() == nameService.getAddress("GDAO_STAKERS") || hasRole(MINTER_ROLE, _msgSender()), "GReputation: need minter role or be GDAO contract" ); } /// @notice internal function that overrides Reputation.sol with consideration to delegation /// @param _user the address to mint for /// @param _amount the amount of rep to mint /// @return the actual amount minted function _mint(address _user, uint256 _amount) internal override returns (uint256) { address repTarget = reputationRecipients[_user]; repTarget = repTarget != address(0) ? repTarget : _user; super._mint(repTarget, _amount); //set self as initial delegator address delegator = delegates[repTarget]; if (delegator == address(0)) { delegates[repTarget] = repTarget; delegator = repTarget; } uint256 previousVotes = getVotesAt(delegator, false, block.number); _updateDelegateVotes( delegator, repTarget, previousVotes, previousVotes + _amount ); return _amount; } /// @notice internal function that overrides Reputation.sol with consideration to delegation /// @param _user the address to burn from /// @param _amount the amount of rep to mint /// @return the actual amount burned function _burn(address _user, uint256 _amount) internal override returns (uint256) { uint256 amountBurned = super._burn(_user, _amount); address delegator = delegates[_user]; delegator = delegator != address(0) ? delegator : _user; delegates[_user] = delegator; uint256 previousVotes = getVotesAt(delegator, false, block.number); _updateDelegateVotes( delegator, _user, previousVotes, previousVotes - amountBurned ); return amountBurned; } /// @notice sets the state hash of a blockchain, can only be called by owner /// @param _id the string name of the blockchain (will be hashed to produce byte32 id) /// @param _hash the state hash /// @param _totalSupply total supply of reputation on the specific blockchain function setBlockchainStateHash( string memory _id, bytes32 _hash, uint256 _totalSupply ) public { _onlyAvatar(); _setBlockchainStateHash(_id, _hash, _totalSupply); } /// @notice sets the state hash of a blockchain, can only be called by owner /// @param _id the string name of the blockchain (will be hashed to produce byte32 id) /// @param _hash the state hash /// @param _totalSupply total supply of reputation on the specific blockchain function _setBlockchainStateHash( string memory _id, bytes32 _hash, uint256 _totalSupply ) internal { bytes32 idHash = keccak256(bytes(_id)); //dont consider rootState as blockchain, it is a special state hash bool isRootState = idHash == ROOT_STATE; require( !isRootState || totalSupplyLocalAt(block.number) == 0, "rootState already created" ); uint256 i = 0; for (; !isRootState && i < activeBlockchains.length; i++) { if (activeBlockchains[i] == idHash) break; } //if new blockchain if (!isRootState && i == activeBlockchains.length) { activeBlockchains.push(idHash); } BlockchainState memory state; state.stateHash = _hash; state.totalSupply = _totalSupply; state.blockNumber = block.number; blockchainStates[idHash].push(state); emit StateHash(_id, _hash, _totalSupply); } /// @notice get the number of active votes a user holds after delegation (vs the basic balance of reputation he holds) /// @param _user the user to get active votes for /// @param _global wether to include reputation from other blockchains /// @param _blockNumber get votes state at specific block /// @return the number of votes function getVotesAt( address _user, bool _global, uint256 _blockNumber ) public view returns (uint256) { uint256 startingBalance = getValueAt(activeVotes[_user], _blockNumber); if (_global) { for (uint256 i = 0; i < activeBlockchains.length; i++) { startingBalance += getVotesAtBlockchain( activeBlockchains[i], _user, _blockNumber ); } } return startingBalance; } /** * @notice returns aggregated active votes in all blockchains and delegated * @param _user the user to get active votes for * @return the number of votes */ function getVotes(address _user) public view returns (uint256) { return getVotesAt(_user, true, block.number); } /** * @notice same as getVotes, be compatible with metamask */ function balanceOf(address _user) public view returns (uint256 balance) { return getVotesAt(_user, block.number); } /** same as getVotes be compatible with compound */ function getCurrentVotes(address _user) public view returns (uint256) { return getVotesAt(_user, true, block.number); } function getPriorVotes(address _user, uint256 _block) public view returns (uint256) { return getVotesAt(_user, true, _block); } /** * @notice returns aggregated active votes in all blockchains and delegated at specific block * @param _user user to get active votes for * @param _blockNumber get votes state at specific block * @return the number of votes */ function getVotesAt(address _user, uint256 _blockNumber) public view returns (uint256) { return getVotesAt(_user, true, _blockNumber); } /** * @notice returns total supply in current blockchain * @param _blockNumber get total supply at specific block * @return the totaly supply */ function totalSupplyLocal(uint256 _blockNumber) public view returns (uint256) { return totalSupplyLocalAt(_blockNumber); } /** * @notice returns total supply in all blockchain aggregated * @param _blockNumber get total supply at specific block * @return the totaly supply */ function totalSupplyAt(uint256 _blockNumber) public view returns (uint256) { uint256 startingSupply = totalSupplyLocalAt(_blockNumber); for (uint256 i = 0; i < activeBlockchains.length; i++) { startingSupply += totalSupplyAtBlockchain( activeBlockchains[i], _blockNumber ); } return startingSupply; } /// @dev This function makes it easy to get the total number of reputation /// @return The total number of reputation function totalSupply() public view returns (uint256) { return totalSupplyAt(block.number); } /// @notice get the number of active votes a user holds after delegation in specific blockchain /// @param _id the keccak hash of the blockchain string id /// @param _user the user to get active votes for /// @param _blockNumber get votes state at specific block /// @return the number of votes function getVotesAtBlockchain( bytes32 _id, address _user, uint256 _blockNumber ) public view returns (uint256) { BlockchainState[] storage states = blockchainStates[_id]; int256 i = int256(states.length); if (i == 0) return 0; BlockchainState storage state = states[uint256(i - 1)]; for (i = i - 1; i >= 0; i--) { if (state.blockNumber <= _blockNumber) break; state = states[uint256(i - 1)]; } if (i < 0) return 0; return stateHashBalances[state.stateHash][_user]; } /** * @notice returns total supply in a specific blockchain * @param _blockNumber get total supply at specific block * @return the totaly supply */ function totalSupplyAtBlockchain(bytes32 _id, uint256 _blockNumber) public view returns (uint256) { BlockchainState[] storage states = blockchainStates[_id]; int256 i; if (states.length == 0) return 0; for (i = int256(states.length - 1); i >= 0; i--) { if (states[uint256(i)].blockNumber <= _blockNumber) break; } if (i < 0) return 0; BlockchainState storage state = states[uint256(i)]; return state.totalSupply; } /** * @notice prove user balance in a specific blockchain state hash * @dev "rootState" is a special state that can be supplied once, and actually mints reputation on the current blockchain * we use non sorted merkle tree, as sorting while preparing merkle tree is heavy * @param _id the string id of the blockchain we supply proof for * @param _user the user to prove his balance * @param _balance the balance we are prooving * @param _proof array of byte32 with proof data (currently merkle tree path) * @param _nodeIndex index of node in the tree (for unsorted merkle tree proof) * @return true if proof is valid */ function proveBalanceOfAtBlockchain( string memory _id, address _user, uint256 _balance, bytes32[] memory _proof, uint256 _nodeIndex ) public returns (bool) { bytes32 idHash = keccak256(bytes(_id)); require( blockchainStates[idHash].length > 0, "no state found for given _id" ); bytes32 stateHash = blockchainStates[idHash][ blockchainStates[idHash].length - 1 ].stateHash; //this is specifically important for rootState that should update real balance only once require( stateHashBalances[stateHash][_user] == 0, "stateHash already proved" ); bytes32 leafHash = keccak256(abi.encode(_user, _balance)); bool isProofValid = checkProofOrdered( _proof, stateHash, leafHash, _nodeIndex ); require(isProofValid, "invalid merkle proof"); //if initiial state then set real balance if (idHash == ROOT_STATE) { _mint(_user, _balance); } //if proof is valid then set balances stateHashBalances[stateHash][_user] = _balance; emit StateHashProof(_id, _user, _balance); return true; } /// @notice returns current delegate of _user /// @param _user the delegatee /// @return the address of the delegate (can be _user if no delegate or 0x0 if _user doesnt exists) function delegateOf(address _user) public view returns (address) { return delegates[_user]; } /// @notice delegate votes to another user /// @param _delegate the recipient of votes function delegateTo(address _delegate) public { return _delegateTo(_msgSender(), _delegate); } /// @notice cancel user delegation /// @dev makes user his own delegate function undelegate() public { return _delegateTo(_msgSender(), _msgSender()); } /** * @notice Delegates votes from signatory to `delegate` * @param _delegate 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 _delegate, uint256 _nonce, uint256 _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, _delegate, _nonce, _expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, _v, _r, _s); require( signatory != address(0), "GReputation::delegateBySig: invalid signature" ); require( _nonce == nonces[signatory]++, "GReputation::delegateBySig: invalid nonce" ); require( block.timestamp <= _expiry, "GReputation::delegateBySig: signature expired" ); return _delegateTo(signatory, _delegate); } /// @notice internal function to delegate votes to another user /// @param _user the source of votes (delegator) /// @param _delegate the recipient of votes function _delegateTo(address _user, address _delegate) internal { require( _delegate != address(0), "GReputation::delegate can't delegate to null address" ); address curDelegator = delegates[_user]; require(curDelegator != _delegate, "already delegating to delegator"); delegates[_user] = _delegate; // remove votes from current delegator uint256 coreBalance = balanceOfLocalAt(_user, block.number); //redundant check - should not be possible to have address 0 as delegator if (curDelegator != address(0)) { uint256 removeVotes = getVotesAt(curDelegator, false, block.number); _updateDelegateVotes( curDelegator, _user, removeVotes, removeVotes - coreBalance ); } //move votes to new delegator uint256 addVotes = getVotesAt(_delegate, false, block.number); _updateDelegateVotes(_delegate, _user, addVotes, addVotes + coreBalance); } /// @notice internal function to update delegated votes, emits event with changes /// @param _delegate the delegate whose record we are updating /// @param _delegator the delegator /// @param _oldVotes the delegate previous votes /// @param _newVotes the delegate votes after the change function _updateDelegateVotes( address _delegate, address _delegator, uint256 _oldVotes, uint256 _newVotes ) internal { updateValueAtNow(activeVotes[_delegate], _newVotes); emit DelegateVotesChanged(_delegate, _delegator, _oldVotes, _newVotes); } // from StorJ -- https://github.com/nginnever/storj-audit-verifier/blob/master/contracts/MerkleVerifyv3.sol /** * @dev non sorted merkle tree proof check */ function checkProofOrdered( bytes32[] memory _proof, bytes32 _root, bytes32 _hash, uint256 _index ) public pure returns (bool) { // use the index to determine the node ordering // index ranges 1 to n bytes32 proofElement; bytes32 computedHash = _hash; uint256 remaining; for (uint256 j = 0; j < _proof.length; j++) { proofElement = _proof[j]; // calculate remaining elements in proof remaining = _proof.length - j; // we don't assume that the tree is padded to a power of 2 // if the index is odd then the proof will start with a hash at a higher // layer, so we have to adjust the index to be the index at that layer while (remaining > 0 && _index % 2 == 1 && _index > 2**remaining) { _index = _index / 2 + 1; } if (_index % 2 == 0) { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); _index = _index / 2; } else { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); _index = _index / 2 + 1; } } return computedHash == _root; } /// @notice helper function to get current chain id /// @return chain id function getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function setReputationRecipient(address _target) public { reputationRecipients[msg.sender] = _target; } function fix1() public { if ( getVotes(0x7f8c1877Ed0DA352F78be4Fe4CdA58BB804a30dF) == 1008145362854518632309 && getVotes(0xDEb250aDD368b74ebCCd59862D62fa4Fb57E09D4) == 587905678906424942728383 && getVotes(0x1D5096665E79585019c448259D944090F28702E3) == 3421532080040613840050 ) { _updateDelegateVotes( 0x7f8c1877Ed0DA352F78be4Fe4CdA58BB804a30dF, 0x7f8c1877Ed0DA352F78be4Fe4CdA58BB804a30dF, 1008145362854518632309, balanceOfLocal(0x7f8c1877Ed0DA352F78be4Fe4CdA58BB804a30dF) ); _updateDelegateVotes( 0xDEb250aDD368b74ebCCd59862D62fa4Fb57E09D4, 0xDEb250aDD368b74ebCCd59862D62fa4Fb57E09D4, 587905678906424942728383, balanceOfLocal(0xDEb250aDD368b74ebCCd59862D62fa4Fb57E09D4) ); _updateDelegateVotes( 0x1D5096665E79585019c448259D944090F28702E3, 0x1D5096665E79585019c448259D944090F28702E3, 3421532080040613840050, balanceOfLocal(0x1D5096665E79585019c448259D944090F28702E3) ); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../Interfaces.sol"; import "../utils/DSMath.sol"; /*** * supports accounting for multiple staking contracts to calculate GDAO rewards */ abstract contract MultiBaseGovernanceShareField is DSMath { // Total Amount of stakes mapping(address => uint256) totalProductivity; // Reward amount of the each share mapping(address => uint256) accAmountPerShare; // Amount of the rewards which minted so far mapping(address => uint256) public rewardsMintedSoFar; // Amount of the rewards with pending and minted ones together mapping(address => uint256) public totalRewardsAccumulated; // Block number of last reward calculation made mapping(address => uint256) public lastRewardBlock; // Rewards amount that will be provided each block mapping(address => uint256) public rewardsPerBlock; struct UserInfo { uint128 amount; // How many tokens the user has staked. uint128 rewardDebt; // Rewards that accounted already so should be substracted while calculating rewards of staker uint128 rewardEarn; // Reward earn and not minted uint128 rewardMinted; // rewards sent to the user } mapping(address => mapping(address => UserInfo)) public contractToUsers; function getChainBlocksPerMonth() public virtual returns (uint256); /** * @dev Calculate rewards per block from monthly amount of rewards and set it * @param _monthlyAmount total rewards which will distribute monthly */ function _setMonthlyRewards(address _contract, uint256 _monthlyAmount) internal { rewardsPerBlock[_contract] = _monthlyAmount / getChainBlocksPerMonth(); } /** * @dev Update reward variables of the given pool to be up-to-date. * Make reward calculations according to passed blocks and updates rewards by * multiplying passed blocks since last calculation with rewards per block value * and add it to accumalated amount per share by dividing total productivity */ function _update( address _contract, uint256 _blockStart, uint256 _blockEnd ) internal virtual { if (totalProductivity[_contract] == 0) { lastRewardBlock[_contract] = block.number; return; } (uint256 _lastRewardBlock, uint256 _accAmountPerShare) = _calcUpdate( _contract, _blockStart, _blockEnd ); accAmountPerShare[_contract] = _accAmountPerShare; lastRewardBlock[_contract] = _lastRewardBlock; } /** * @dev helper to calculate global rewards accumulated per block so far * @param _contract the contract to calcualte the rewards for * @param _blockStart the block from which the contract is eligble for rewards * @param _blockEnd the block from which the contract is no longer eligble for rewards */ function _calcUpdate( address _contract, uint256 _blockStart, uint256 _blockEnd ) internal view returns (uint256 _lastRewardBlock, uint256 _accAmountPerShare) { _accAmountPerShare = accAmountPerShare[_contract]; _lastRewardBlock = lastRewardBlock[_contract]; _lastRewardBlock = _lastRewardBlock < _blockStart && block.number >= _blockStart ? _blockStart : _lastRewardBlock; uint256 curRewardBlock = block.number > _blockEnd ? _blockEnd : block.number; if (curRewardBlock < _blockStart || _lastRewardBlock >= _blockEnd) return (_lastRewardBlock, _accAmountPerShare); uint256 multiplier = curRewardBlock - _lastRewardBlock; // Blocks passed since last reward block uint256 reward = multiplier * rewardsPerBlock[_contract]; // rewardsPerBlock is in GDAO which is in 18 decimals _accAmountPerShare += (reward * 1e27) / totalProductivity[_contract]; // totalProductivity in 18decimals and reward in 18 decimals so rdiv result in 27decimals _lastRewardBlock = curRewardBlock; } /** * @dev Audit user's rewards and calculate their earned rewards based on stake_amount * accAmountPerShare */ function _audit( address _contract, address _user, uint256 _updatedAmount ) internal virtual { UserInfo storage userInfo = contractToUsers[_contract][_user]; if (userInfo.amount > 0) { uint256 pending = (userInfo.amount * accAmountPerShare[_contract]) / 1e27 - userInfo.rewardDebt; // Divide 1e27(because userinfo.amount in 18 decimals and accAmountPerShare is in 27decimals) since rewardDebt in 18 decimals so we can calculate how much reward earned in that cycle userInfo.rewardEarn = userInfo.rewardEarn + uint128(pending); // Add user's earned rewards to user's account so it can be minted later totalRewardsAccumulated[_contract] = totalRewardsAccumulated[_contract] + pending; } userInfo.amount = uint128(_updatedAmount); userInfo.rewardDebt = uint128( (_updatedAmount * accAmountPerShare[_contract]) / 1e27 ); // Divide to 1e27 to keep rewardDebt in 18 decimals since accAmountPerShare is in 27 decimals and amount is 18 decimals } /** * @dev This function increase user's productivity and updates the global productivity. * This function increase user's productivity and updates the global productivity. * the users' actual share percentage will calculated by: * Formula: user_productivity / global_productivity */ function _increaseProductivity( address _contract, address _user, uint256 _value, uint256 _blockStart, uint256 _blockEnd ) internal virtual returns (bool) { _update(_contract, _blockStart, _blockEnd); _audit(_contract, _user, contractToUsers[_contract][_user].amount + _value); totalProductivity[_contract] = totalProductivity[_contract] + _value; return true; } /** * @dev This function will decreases user's productivity by value, and updates the global productivity * it will record which block this is happenning and accumulates the area of (productivity * time) */ function _decreaseProductivity( address _contract, address _user, uint256 _value, uint256 _blockStart, uint256 _blockEnd ) internal virtual returns (bool) { _update(_contract, _blockStart, _blockEnd); _audit(_contract, _user, contractToUsers[_contract][_user].amount - _value); totalProductivity[_contract] = totalProductivity[_contract] - _value; return true; } /** * @dev Query user's pending reward with updated variables * @param _contract the contract to calcualte the rewards for * @param _blockStart the block from which the contract is eligble for rewards * @param _blockEnd the block from which the contract is no longer eligble for rewards * @param _user the user to calculate rewards for * @return returns amount of user's earned but not minted rewards */ function getUserPendingReward( address _contract, uint256 _blockStart, uint256 _blockEnd, address _user ) public view returns (uint256) { UserInfo memory userInfo = contractToUsers[_contract][_user]; uint256 pending = 0; if (totalProductivity[_contract] != 0) { (, uint256 _accAmountPerShare) = _calcUpdate( _contract, _blockStart, _blockEnd ); pending = userInfo.rewardEarn; pending += (userInfo.amount * _accAmountPerShare) / 1e27 - userInfo.rewardDebt; // Divide 1e27(because userinfo.amount in 18 decimals and accAmountPerShare is in 27decimals) since rewardDebt in 18 decimals so we can calculate how much reward earned in that cycle } return pending; } /** @dev Calculate earned rewards of the user and update their reward info * @param _contract address of the contract for accounting * @param _user address of the user that will be accounted * @param _blockStart the block from which the contract is eligble for rewards * @param _blockEnd the block from which the contract is no longer eligble for rewards * @return returns minted amount */ function _issueEarnedRewards( address _contract, address _user, uint256 _blockStart, uint256 _blockEnd ) internal returns (uint256) { _update(_contract, _blockStart, _blockEnd); _audit(_contract, _user, contractToUsers[_contract][_user].amount); uint128 amount = contractToUsers[_contract][_user].rewardEarn; contractToUsers[_contract][_user].rewardMinted += amount; contractToUsers[_contract][_user].rewardEarn = 0; rewardsMintedSoFar[_contract] = rewardsMintedSoFar[_contract] + amount; return amount; } /** * @return Returns how much productivity a user has and total productivity. */ function getProductivity(address _contract, address _user) public view virtual returns (uint256, uint256) { return ( contractToUsers[_contract][_user].amount, totalProductivity[_contract] ); } /** * @return Returns the current gross product rate. */ function totalRewardsPerShare(address _contract) public view virtual returns (uint256) { return accAmountPerShare[_contract]; } // for upgrades uint256[50] private _gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "../utils/DAOUpgradeableContract.sol"; /** * based on https://github.com/daostack/infra/blob/60a79a1be02942174e21156c3c9655a7f0695dbd/contracts/Reputation.sol * @title Reputation system * @dev A DAO has Reputation System which allows peers to rate other peers in order to build trust . * A reputation is used to assign influence measure to a DAO'S peers. * Reputation is similar to regular tokens but with one crucial difference: It is non-transferable. * The Reputation contract maintain a map of address to reputation value. * It provides an only minter role functions to mint and burn reputation _to (or _from) a specific address. */ contract Reputation is DAOUpgradeableContract, AccessControlUpgradeable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); string public name; string public symbol; uint8 public decimals; //Number of decimals of the smallest unit // Event indicating minting of reputation to an address. event Mint(address indexed _to, uint256 _amount); // Event indicating burning of reputation for an address. event Burn(address indexed _from, uint256 _amount); uint256 private constant ZERO_HALF_256 = 0xffffffffffffffffffffffffffffffff; /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value //Checkpoint is uint256 : // bits 0-127 `fromBlock` is the block number that the value was generated from // bits 128-255 `value` is the amount of reputation at a specific block number // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping(address => uint256[]) public balances; // Tracks the history of the `totalSupply` of the reputation uint256[] public totalSupplyHistory; /** * @dev initialize */ function initialize(INameService _ns) public initializer { __Reputation_init(_ns); } function __Reputation_init(INameService _ns) internal { decimals = 18; name = "GoodDAO"; symbol = "GOOD"; __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); setDAO(_ns); _setupRole(DEFAULT_ADMIN_ROLE, address(avatar)); _setupRole(MINTER_ROLE, address(avatar)); } function _canMint() internal view virtual { require(hasRole(MINTER_ROLE, _msgSender()), "Reputation: need minter role"); } /// @notice Generates `_amount` reputation that are assigned to `_owner` /// @param _user The address that will be assigned the new reputation /// @param _amount The quantity of reputation generated /// @return True if the reputation are generated correctly function mint(address _user, uint256 _amount) public returns (bool) { _canMint(); _mint(_user, _amount); return true; } function _mint(address _user, uint256 _amount) internal virtual returns (uint256) { uint256 curTotalSupply = totalSupplyLocalAt(block.number); uint256 previousBalanceTo = balanceOfLocalAt(_user, block.number); updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_user], previousBalanceTo + _amount); emit Mint(_user, _amount); return _amount; } /// @notice Burns `_amount` reputation from `_owner` /// @param _user The address that will lose the reputation /// @param _amount The quantity of reputation to burn /// @return True if the reputation are burned correctly function burn(address _user, uint256 _amount) public returns (bool) { //user can burn his own rep other wise we check _canMint if (_user != _msgSender()) _canMint(); _burn(_user, _amount); return true; } function _burn(address _user, uint256 _amount) internal virtual returns (uint256) { uint256 curTotalSupply = totalSupplyLocalAt(block.number); uint256 amountBurned = _amount; uint256 previousBalanceFrom = balanceOfLocalAt(_user, block.number); if (previousBalanceFrom < amountBurned) { amountBurned = previousBalanceFrom; } updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned); updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned); emit Burn(_user, amountBurned); return amountBurned; } function balanceOfLocal(address _owner) public view returns (uint256) { return balanceOfLocalAt(_owner, block.number); } /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfLocalAt(address _owner, uint256 _blockNumber) public view virtual returns (uint256) { if ( (balances[_owner].length == 0) || (uint128(balances[_owner][0]) > _blockNumber) ) { return 0; // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } function totalSupplyLocal() public view virtual returns (uint256) { return totalSupplyLocalAt(block.number); } /// @notice Total amount of reputation at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of reputation at `_blockNumber` function totalSupplyLocalAt(uint256 _blockNumber) public view virtual returns (uint256) { if ( (totalSupplyHistory.length == 0) || (uint128(totalSupplyHistory[0]) > _blockNumber) ) { return 0; // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of reputation at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of reputation being queried function getValueAt(uint256[] storage checkpoints, uint256 _block) internal view returns (uint256) { uint256 len = checkpoints.length; if (len == 0) { return 0; } // Shortcut for the actual value uint256 cur = checkpoints[len - 1]; if (_block >= uint128(cur)) { return cur >> 128; } if (_block < uint128(checkpoints[0])) { return 0; } // Binary search of the value in the array uint256 min = 0; uint256 max = len - 1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (uint128(checkpoints[mid]) <= _block) { min = mid; } else { max = mid - 1; } } return checkpoints[min] >> 128; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of reputation function updateValueAtNow(uint256[] storage checkpoints, uint256 _value) internal { require(uint128(_value) == _value, "reputation overflow"); //check value is in the 128 bits bounderies if ( (checkpoints.length == 0) || (uint128(checkpoints[checkpoints.length - 1]) < block.number) ) { checkpoints.push(uint256(uint128(block.number)) | (_value << 128)); } else { checkpoints[checkpoints.length - 1] = uint256( (checkpoints[checkpoints.length - 1] & uint256(ZERO_HALF_256)) | (_value << 128) ); } } }
Calculates worth of given amount of iToken in Token _amount Amount of token to calculate worth in Token return Worth of given amount of token in Token/
function iTokenWorthInToken(uint256 _amount) internal view override returns (uint256) { }
1,307,125
./partial_match/4/0x1F75b29F849185e8B57E24Fe6fAb09c176583942/sources/ChickenChef.sol
Withdraw LP tokens from MasterChef. require(_amount > 0, "amount should be greater than 0");
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.accChickenPerShare).div(1e12).sub(user.rewardDebt); safeChickenTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accChickenPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
8,562,354
// SPDX-License-Identifier: AGPL // File: contracts/interfaces/IITR.sol pragma solidity ^0.8.0; interface IITR { function claim(address to) external; } // File: contracts/interfaces/ISRC20.sol pragma solidity ^0.8.0; interface ISRC20 { event RestrictionsAndRulesUpdated(address restrictions, address rules); function transferToken(address to, uint256 value, uint256 nonce, uint256 expirationTime, bytes32 msgHash, bytes calldata signature) external returns (bool); function transferTokenFrom(address from, address to, uint256 value, uint256 nonce, uint256 expirationTime, bytes32 hash, bytes calldata signature) external returns (bool); function getTransferNonce() external view returns (uint256); function getTransferNonce(address account) external view returns (uint256); function executeTransfer(address from, address to, uint256 value) external returns (bool); function updateRestrictionsAndRules(address restrictions, address rules) external returns (bool); // ERC20 part-like interface event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); 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 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 increaseAllowance(address spender, uint256 value) external returns (bool); function decreaseAllowance(address spender, uint256 value) external returns (bool); } // File: contracts/interfaces/ITransferRules.sol pragma solidity ^0.8.0; interface ITransferRules { function setSRC(address src20) external returns (bool); function doTransfer(address from, address to, uint256 value) external returns (bool); } // File: contracts/interfaces/IChain.sol pragma solidity ^0.8.0; interface IChain { function doValidate(address from, address to, uint256 value) external returns (address, address, uint256, bool, string memory); } // 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: contracts/restrictions/ChainRuleBase.sol pragma solidity ^0.8.0; abstract contract ChainRuleBase is Ownable { address public _chainRuleAddr; function clearChain() public onlyOwner() { _setChain(address(0)); } function setChain(address chainAddr) public onlyOwner() { _setChain(chainAddr); } //--------------------------------------------------------------------------------- // internal section //--------------------------------------------------------------------------------- function _doValidate( address from, address to, uint256 value ) internal returns ( address _from, address _to, uint256 _value, bool _success, string memory _msg ) { (_from, _to, _value, _success, _msg) = _validate(from, to, value); if (isChainExists() && _success) { (_from, _to, _value, _success, _msg) = IChain(_chainRuleAddr).doValidate(msg.sender, to, value); } } function isChainExists() internal view returns(bool) { return (_chainRuleAddr != address(0) ? true : false); } function _setChain(address chainAddr) internal { _chainRuleAddr = chainAddr; } function _validate(address from, address to, uint256 value) internal virtual returns (address, address, uint256, bool, string memory); } // File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/restrictions/TransferRule.sol pragma solidity ^0.8.0; contract TransferRule is Ownable, ITransferRules, ChainRuleBase { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; address public _src20; address public _doTransferCaller; uint256 internal constant MULTIPLIER = 100000; address public _tradedToken; uint256 public _lockupDuration; uint256 public _lockupFraction; struct Item { uint256 untilTime; uint256 lockedAmount; } mapping(address => Item) restrictions; EnumerableSet.AddressSet _exchangeDepositAddresses; modifier onlyDoTransferCaller { require(msg.sender == address(_doTransferCaller)); _; } //--------------------------------------------------------------------------------- // public section //--------------------------------------------------------------------------------- /** * @param tradedToken tradedToken * @param lockupDuration duration in sec * @param lockupFraction fraction in percent to lock. multiplied by MULTIPLIER */ constructor( address tradedToken, uint256 lockupDuration, uint256 lockupFraction ) { _tradedToken = tradedToken; _lockupDuration = lockupDuration; _lockupFraction = lockupFraction; } function cleanSRC() public onlyOwner() { _src20 = address(0); _doTransferCaller = address(0); //_setChain(address(0)); } function addExchangeAddress(address addr) public onlyOwner() { _exchangeDepositAddresses.add(addr); } function removeExchangeAddress(address addr) public onlyOwner() { _exchangeDepositAddresses.remove(addr); } function viewExchangeAddresses() public view returns(address[] memory) { uint256 len = _exchangeDepositAddresses.length(); address[] memory ret = new address[](len); for (uint256 i =0; i < len; i++) { ret[i] = _exchangeDepositAddresses.at(i); } return ret; } function addRestrictions( address[] memory addressArray, uint256[] memory amountArray, uint256[] memory untilArray ) public onlyOwner { uint l=addressArray.length; for (uint i=0; i<l; i++) { restrictions[ addressArray[i] ] = Item({ lockedAmount: amountArray[i], untilTime: untilArray[i] }); } } //--------------------------------------------------------------------------------- // external section //--------------------------------------------------------------------------------- /** * @dev Set for what contract this rules are. * * @param src20 - Address of src20 contract. */ function setSRC(address src20) override external returns (bool) { require(_doTransferCaller == address(0), "external contract already set"); require(address(_src20) == address(0), "external contract already set"); require(src20 != address(0), "src20 can not be zero"); _doTransferCaller = _msgSender(); _src20 = src20; return true; } /** * @dev Do transfer and checks where funds should go. * before executeTransfer contract will call chainValidate on chain if exists * * @param from The address to transfer from. * @param to The address to send tokens to. * @param value The amount of tokens to send. */ function doTransfer(address from, address to, uint256 value) override external onlyDoTransferCaller returns (bool) { bool success; string memory errmsg; (from, to, value, success, errmsg) = _doValidate(from, to, value); require(success, (bytes(errmsg).length == 0) ? "chain validation failed" : errmsg); // todo: need to check params after chains validation?? require(ISRC20(_src20).executeTransfer(from, to, value), "SRC20 transfer failed"); if ( success && (to == _tradedToken) ) { IITR(_tradedToken).claim(from); } return true; } //--------------------------------------------------------------------------------- // internal section //--------------------------------------------------------------------------------- function _validate(address from, address to, uint256 value) internal virtual override returns (address _from, address _to, uint256 _value, bool _success, string memory _errmsg) { (_from, _to, _value, _success, _errmsg) = (from, to, value, true, ""); require( _exchangeDepositAddresses.contains(to) == false, string(abi.encodePacked("Don't deposit directly to this exchange. Send to the address ITR.ETH first, to obtain the correct token in your wallet.")) ); uint256 balanceFrom = ISRC20(_src20).balanceOf(from); if (restrictions[from].untilTime > block.timestamp) { if (to == _tradedToken) { _success = false; _errmsg = "you recently claimed new tokens, please wait until duration has elapsed to claim again"; } else if ((restrictions[from].lockedAmount).add(value) > balanceFrom) { _success = false; _errmsg = "you recently claimed new tokens, please wait until duration has elapsed to transfer this many tokens"; } } if ( _success && (to == _tradedToken) && (restrictions[from].untilTime > block.timestamp) ) { restrictions[from].untilTime = (block.timestamp).add(_lockupDuration); restrictions[from].lockedAmount = (balanceFrom.sub(value)).mul(_lockupFraction).div(MULTIPLIER); } } //--------------------------------------------------------------------------------- // private section //--------------------------------------------------------------------------------- }
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; }
6,152,382
./full_match/5/0xE2074D1cc079223D073303A42eDb1b5b7D865c74/sources/project_/contracts/SettlerNFT.sol
If there is no base URI, return the token URI. If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } }
7,037,329
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../src/active/ERC20Token.sol"; contract ERC20TokenTest { // truffle test ./test/ERC20Token.test.sol function testInitialBalanceUsingDeployedContract() public { ERC20Token meta = ERC20Token(DeployedAddresses.ERC20Token()); uint expected = 777999777000000000000000000; Assert.equal(meta.totalSupply(), expected, "Owner should have 777999777000000000000000000 ERC20Token initially"); } // truffle test ./test/ERC20Token.test.sol --network test function testInitialBalanceWithNewERC20Token() public { ERC20Token meta = new ERC20Token(); meta.__ERC20Token_init("Nhan Cao", "nhancv", 18, 777999777); uint expected = 777999777000000000000000000; Assert.equal( meta.balanceOf(meta.owner()), expected, "Owner should have 777999777000000000000000000 ERC20Token initially" ); } }
truffle test ./test/ERC20Token.test.sol --network test
function testInitialBalanceWithNewERC20Token() public { ERC20Token meta = new ERC20Token(); meta.__ERC20Token_init("Nhan Cao", "nhancv", 18, 777999777); uint expected = 777999777000000000000000000; Assert.equal( meta.balanceOf(meta.owner()), expected, "Owner should have 777999777000000000000000000 ERC20Token initially" ); }
13,065,705
pragma solidity ^0.4.18; // solhint-disable-line /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete) 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); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } contract CryptocarToken is ERC721 { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new car comes into existence. event Birth(uint256 tokenId, string name, address owner); /// @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoCars"; // solhint-disable-line string public constant SYMBOL = "CryptocarToken"; // solhint-disable-line uint256 private startingPrice = 0.01 ether; uint256 private constant PROMO_CREATION_LIMIT = 5000; uint256 private firstStepLimit = 0.9999998 ether; uint256 private secondStepLimit = 0.9999999 ether; /*** STORAGE ***/ /// @dev A mapping from car IDs to the address that owns them. All cars have /// some valid owner address. mapping (uint256 => address) public carIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from CarIDs to an address that has been approved to call /// transferFrom(). Each Car can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public carIndexToApproved; // @dev A mapping from CarIDs to the price of the token. mapping (uint256 => uint256) private carIndexToPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; uint256 public promoCreatedCount; /*** DATATYPES ***/ struct Car { string name; } Car[] private cars; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function CryptocarToken() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); carIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new promo Car with the given name, with given _price and assignes it to an address. function createPromoCar(address _owner, string _name, uint256 _price) public onlyCOO { require(promoCreatedCount < PROMO_CREATION_LIMIT); address carOwner = _owner; if (carOwner == address(0)) { carOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; _createCar(_name, carOwner, _price); } /// @dev Creates a new Car with the given name. function createContractCar(string _name) public onlyCOO { _createCar(_name, address(this), startingPrice); } /// @notice Returns all the relevant information about a specific car. /// @param _tokenId The tokenId of the car of interest. function getCar(uint256 _tokenId) public view returns ( string carName, uint256 sellingPrice, address owner ) { Car storage car = cars[_tokenId]; carName = car.name; sellingPrice = carIndexToPrice[_tokenId]; owner = carIndexToOwner[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = carIndexToOwner[_tokenId]; require(owner != address(0)); return owner; } function payout(address _to) public onlyCLevel { _payout(_to); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = carIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = carIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 93), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); // Update prices if (sellingPrice < firstStepLimit) { // first stage carIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 93); } else if (sellingPrice < secondStepLimit) { // second stage carIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 118), 93); } else { // third stage carIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 118), 93); } _transfer(oldOwner, newOwner, _tokenId); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1-0.07) } TokenSold(_tokenId, sellingPrice, carIndexToPrice[_tokenId], oldOwner, newOwner, cars[_tokenId].name); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return carIndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = carIndexToOwner[_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); } /// @param _owner The owner whose supercar tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Cars array looking for cars belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array 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 (carIndexToOwner[carId] == _owner) { result[resultIndex] = carId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return cars.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return carIndexToApproved[_tokenId] == _to; } /// For creating Car function _createCar(string _name, address _owner, uint256 _price) private { Car memory _car = Car({ name: _name }); uint256 newCarId = cars.push(_car) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newCarId == uint256(uint32(newCarId))); Birth(newCarId, _name, _owner); carIndexToPrice[newCarId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newCarId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == carIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @dev Assigns ownership of a specific Car to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of cars is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership carIndexToOwner[_tokenId] = _to; // When creating new cars _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete carIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } } 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; } }
Creates a new promo Car with the given name, with given _price and assignes it to an address.
function createPromoCar(address _owner, string _name, uint256 _price) public onlyCOO { require(promoCreatedCount < PROMO_CREATION_LIMIT); address carOwner = _owner; if (carOwner == address(0)) { carOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; _createCar(_name, carOwner, _price); }
6,857,264
// 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 execute a call to an integration 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)); }
1,697,454
pragma solidity 0.5.12; /** * (c) 2021 Akiva Capital Holdings, LLC. All Rights Reserved. * * For LICENSE details, please visit: * https://github.com/akiva-capital-holdings/pairwyse-smart-contracts/blob/master/LICENSE * */ import "./McdAddressesR17main.sol"; import "../interfaces/IMcd.sol"; import "../interfaces/IERC20.sol"; import "../helpers/RaySupport.sol"; /** * @title Agreement multicollateral dai wrapper for maker dao system interaction. * @dev delegates calls to proxy. Oriented to exact MCD release. Current version oriented to 17th release mcd cdp. */ // TODO: make abstract? contract McdWrapper is McdAddressesR17, RaySupport { address payable public proxyAddress; /** * ToDo: usless function * @dev Get registered proxy for current caller (msg.sender address) * function proxy() public view returns (DSProxyLike) { * return DSProxyLike(proxyAddress); * } */ /** * @dev transfer exact amount of erc20 tokens, approved beforehand * @param ilk collateral type * @return IERC20 instance */ function erc20TokenContract(bytes32 ilk) public view returns(IERC20) { (, address payable collateralBaseAddress) = _getCollateralAddreses(ilk); return IERC20(collateralBaseAddress); } // /** // * @dev get amount of dai tokens currently locked in dsr(pot) contract. // * @return pie amount of all dai tokens locked in dsr // */ // function getLockedDai() public view returns(uint256 pie, uint256 pieS) { // pie = PotLike(mcdPotAddr).pie(proxyAddress); // pieS = pie.mul(PotLike(mcdPotAddr).chi()); // } /** * @dev get dai savings rate * @return dsr value in multiplier format defined by maker dao system. 100 * 10^25 - means 0% dsr. 103 * 10^25 means * 3% dsr. */ function getDsr() public view returns(uint) { return PotLike(mcdPotAddr).dsr(); } /** * @dev get collateral cost * @return Duty (base rate plus risk premium) in multiplier format, per-second accrual. */ function getIlkDuty(bytes32 _ilkIndex) public view returns (uint) { (uint _duty, ) = JugLike(mcdJugAddr).ilks(_ilkIndex); return _duty; } /** * ToDo: unused function * @dev Get the equivalent of exact dai amount in terms of collateral type. * @dev Add one more collateral token unit in case if calculated value doesn't cover dai amount * @param ilk collateral type in bytes32 format * @param daiAmount dai tokens amount * @return collateral tokens amount worth dai amount * * function getCollateralEquivalent(bytes32 ilk, uint daiAmount) public view returns(uint) { * uint price = getPrice(ilk); * uint ethAmount = daiAmount.mul(ONE).div(price); * return (ethAmount.mul(price).div(ONE) == daiAmount) ? ethAmount : (ethAmount.add(1)); * } */ /** * @dev Get current cdp main info: collateral amount, dai (normalized debt) amount * @param ilk collateral type in bytes32 format * @param cdpId cdp ID * @return ink collateral tokens amount * art dai debt amount */ function getCdpInfo(bytes32 ilk, uint cdpId) public view returns(uint collateral, uint debt) { address urn = ManagerLike(cdpManagerAddr).urns(cdpId); (uint ink, uint art) = VatLike(mcdVatAddr).urns(ilk, urn); (, uint rate, , , ) = VatLike(mcdVatAddr).ilks(ilk); collateral = ink; debt = art.mul(rate).div(ONE); } /** * @dev Get collateral token price to USD * @param ilk collateral type in bytes32 format * @return collateral to USD price */ function getPrice(bytes32 ilk) public view returns(uint) { (, , uint spot, , ) = VatLike(mcdVatAddr).ilks(ilk); return spot.mul(getLiquidationRatio(ilk)).div(ONE); } /** * @dev Get collateral dust sizes [rad] * @param ilk collateral type in bytes32 format * @return collateral dust sizes [rad] */ function getDust(bytes32 ilk) public view returns(uint) { (, , , , uint dust) = VatLike(mcdVatAddr).ilks(ilk); return dust; } /** * @dev Get collateral liquidation ratio. Percent of overcollateralization. If collateral / debt < liauidation * ratio - cdp should be autoliquidated * @param ilk collateral type in bytes32 format * @return liquidation ratio 150 * 10^25 - means 150% */ function getLiquidationRatio(bytes32 ilk) public view returns(uint) { (, uint mat) = SpotterLike(mcdSpotAddr).ilks(ilk); return mat; } /** * @dev Check is cdp is unsafe already * @param ilk collateral type in bytes32 format * @param cdpId cdp ID * @return true if unsafe */ function isCdpSafe(bytes32 ilk, uint cdpId) public view returns(bool) { return getCdpCR(ilk, cdpId) >= getLiquidationRatio(ilk); } /** * @dev Calculate available dai to be drawn in Cdp * @param ilk collateral type in bytes32 format * @param cdpId cdp ID * @return dai amount available to be drawn */ function getDaiAvailable(bytes32 ilk, uint cdpId) public view returns(uint) { (, uint rate, uint spot, , ) = VatLike(mcdVatAddr).ilks(ilk); (uint ink, uint art) = VatLike(mcdVatAddr).urns(ilk, ManagerLike(cdpManagerAddr).urns(cdpId)); return (ink.mul(spot) > art.mul(rate)) ? fromRay(ink.mul(spot).sub(art.mul(rate))) : 0; } /** * @dev Calculate current cdp collateralization ratio * @param ilk collateral type in bytes32 format * @param cdpId cdp ID * @return collateralization ratio */ function getCdpCR(bytes32 ilk, uint cdpId) public view returns(uint) { (, uint rate, uint spot, , ) = VatLike(mcdVatAddr).ilks(ilk); (uint ink, uint art) = VatLike(mcdVatAddr).urns(ilk, ManagerLike(cdpManagerAddr).urns(cdpId)); (, uint mat) = SpotterLike(mcdSpotAddr).ilks(ilk); // The order of operands is such to avoid a potential overflow return ink.mul(spot).div(art).mul(mat).div(rate); } /** * @dev Get minimal collateralization ratio for collateral type * @param ilk collateral type in bytes32 format * @return minimal collateralization ratio */ function getMCR(bytes32 ilk) public view returns(uint) { (, uint mat) = SpotterLike(mcdSpotAddr).ilks(ilk); return mat; } /** * @dev init mcd Wrapper, build proxy * @param ilk collateral type in bytes32 format * @param isEther true if ether and false if erc-20 token */ function _initMcdWrapper(bytes32 ilk, bool isEther) internal { _buildProxy(); if (!isEther) { _approveERC20(ilk, proxyAddress, 2 ** 256 - 1); } _approveDai(proxyAddress, 2 ** 256 - 1); } /** * @dev Build proxy for current caller (msg.sender address) */ function _buildProxy() internal { if (proxyAddress == address(0)) { proxyAddress = ProxyRegistryLike(proxyRegistryAddr).build(); } } /** * ToDo: usless function * @dev Change proxy owner to a new one * @param newOwner new owner address * * function _setOwnerProxy(address newOwner) internal { * proxy().setOwner(newOwner); * } */ /** * @dev Lock additional ether as collateral * @param ilk collateral type in bytes32 format * @param cdp cdp id * @param wadC collateral amount to be locked in cdp contract */ function _lockETH(bytes32 ilk, uint cdp, uint wadC) internal { bytes memory data; (address collateralJoinAddr,) = _getCollateralAddreses(ilk); data = abi.encodeWithSignature( "lockETH(address,address,uint256)", cdpManagerAddr, collateralJoinAddr, cdp); (bool success, ) = proxyAddress.call.value(wadC)( abi.encodeWithSignature("execute(address,bytes)", proxyLib, data)); require(success, "MCD2"); } /** * @dev Lock additional erc-20 tokens as collateral * @param ilk collateral type in bytes32 format * @param cdp cdp id * @param wadC collateral amount to be locked in cdp contract * @param transferFrom collateral tokens should be transfered from caller */ function _lockERC20(bytes32 ilk, uint cdp, uint wadC, bool transferFrom) internal { (address collateralJoinAddr,) = _getCollateralAddreses(ilk); DSProxyLike(proxyAddress).execute( proxyLib, abi.encodeWithSignature( "lockGem(address,address,uint256,uint256,bool)", cdpManagerAddr, collateralJoinAddr, cdp, wadC, transferFrom)); } /** * @dev Create new cdp with Ether as collateral, lock collateral and draw dai * @dev build new Proxy for a caller before cdp creation * @param ilk collateral type in bytes32 format * @param wadC collateral amount to be locked in cdp contract * @param wadD dai amount to be drawn */ function _openLockETHAndDraw( bytes32 ilk, uint wadC, uint wadD ) internal returns (uint cdp) { address payable target = proxyAddress; (address collateralJoinAddr,) = _getCollateralAddreses(ilk); bytes memory data = abi.encodeWithSignature( "execute(address,bytes)", proxyLib, abi.encodeWithSignature( "openLockETHAndDraw(address,address,address,address,bytes32,uint256)", cdpManagerAddr, mcdJugAddr, collateralJoinAddr, mcdJoinDaiAddr, ilk, wadD ) ); assembly { let succeeded := call(sub(gas, 5000), target, wadC, add(data, 0x20), mload(data), 0, 0) let size := returndatasize let response := mload(0x40) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) cdp := mload(add(response, 0x20)) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } /** * @dev Create new cdp with ERC-20 tokens as collateral, lock collateral and draw dai * @dev build new Proxy for a caller before cdp creation and approve transferFrom collateral token from Agrrement * by Proxy * @param ilk collateral type in bytes32 format * @param wadC collateral amount to be locked in cdp contract * @param wadD dai amount to be drawn * @param transferFrom collateral tokens should be transfered from caller */ function _openLockERC20AndDraw( bytes32 ilk, uint wadC, uint wadD, bool transferFrom ) internal returns (uint cdp) { address payable target = proxyAddress; (address collateralJoinAddr,) = _getCollateralAddreses(ilk); bytes memory data = abi.encodeWithSignature( "execute(address,bytes)", proxyLib, abi.encodeWithSignature( "openLockGemAndDraw(address,address,address,address,bytes32,uint256,uint256,bool)", cdpManagerAddr, mcdJugAddr, collateralJoinAddr, mcdJoinDaiAddr, ilk, wadC, wadD, transferFrom ) ); assembly { let succeeded := call(sub(gas, 5000), target, 0, add(data, 0x20), mload(data), 0, 0) let size := returndatasize let response := mload(0x40) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) cdp := mload(add(response, 0x20)) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } /** * @dev inject(wipe) some amount of dai to cdp from agreement (pay off some amount of dai to cdp) * @param cdp cdp ID * @param wad amount of dai tokens */ function _injectToCdpFromDsr(uint cdp, uint wad) internal returns(uint injectionWad) { injectionWad = _unlockDai(wad); DSProxyLike(proxyAddress).execute( proxyLib, abi.encodeWithSignature( "wipe(address,address,uint256,uint256)", cdpManagerAddr, mcdJoinDaiAddr, cdp, injectionWad)); } /** * @dev draw dai into cdp contract, if not enough - draw max available dai * @param ilk collateral type in bytes32 format * @param cdp cdp ID * @param wad amount of dai tokens * @return drawn dai amount */ function _drawDaiToCdp(bytes32 ilk, uint cdp, uint wad) internal returns (uint drawnDai) { JugLike(mcdJugAddr).drip(ilk); uint maxToDraw = getDaiAvailable(ilk, cdp); drawnDai = wad > maxToDraw ? maxToDraw : wad; DSProxyLike(proxyAddress).execute( proxyLib, abi.encodeWithSignature( "draw(address,address,address,uint256,uint256)", cdpManagerAddr, mcdJugAddr, mcdJoinDaiAddr, cdp, drawnDai)); } /** * @dev lock dai tokens to dsr(pot) contract. * @dev approves this amount of dai tokens to proxy before locking * @param wad amount of dai tokens */ function _lockDai(uint wad) internal { DSProxyLike(proxyAddress).execute( proxyLibDsr, abi.encodeWithSignature( "join(address,address,uint256)", mcdJoinDaiAddr, mcdPotAddr, wad)); } /** * @dev unlock dai tokens from dsr(pot) contract. * @param wad amount of dai tokens * @return actually unlocked amount of dai */ function _unlockDai(uint wad) internal returns(uint unlockedWad) { uint _balanceBefore = _balanceDai(address(this)); DSProxyLike(proxyAddress).execute( proxyLibDsr, abi.encodeWithSignature( "exit(address,address,uint256)", mcdJoinDaiAddr, mcdPotAddr, wad)); unlockedWad = _balanceDai(address(this)).sub(_balanceBefore); } /** * @dev unlock all dai tokens from dsr(pot) contract. * @return pie amount of all dai tokens was unlocked in fact */ function _unlockAllDai() internal returns(uint pie) { uint _balanceBefore = _balanceDai(address(this)); DSProxyLike(proxyAddress).execute( proxyLibDsr, abi.encodeWithSignature( "exitAll(address,address)", mcdJoinDaiAddr, mcdPotAddr)); pie = _balanceDai(address(this)).sub(_balanceBefore); } /** * @dev Approve exact amount of dai tokens for transferFrom * @param to address allowed to call transferFrom * @param amount tokens amount for approval */ function _approveDai(address to, uint amount) internal returns(bool) { IERC20(mcdDaiAddr).approve(to, amount); return true; } /** * @dev Approve exact amount of erc20 tokens for transferFrom * @param ilk collateral type * @param to address allowed to call transferFrom * @param amount tokens amount for approval */ function _approveERC20(bytes32 ilk, address to, uint amount) internal returns(bool) { erc20TokenContract(ilk).approve(to, amount); return true; } /** * @dev Transfer exact amount of dai tokens * @param to address of recepient * @param amount tokens amount */ function _transferDai(address to, uint amount) internal returns(bool) { IERC20(mcdDaiAddr).transfer(to, amount); return true; } /** * @dev Transfer exact amount of erc20 tokens * @param ilk collateral type * @param to address of recepient * @param amount tokens amount */ function _transferERC20(bytes32 ilk, address to, uint amount) internal returns(bool) { erc20TokenContract(ilk).transfer(to, amount); return true; } /** * @dev Transfer exact amount of dai tokens, approved beforehand * @param from address of spender * @param to address of recepient * @param amount tokens amount */ function _transferFromDai(address from, address to, uint amount) internal returns(bool) { require(IERC20(mcdDaiAddr).transferFrom(from, to, amount), "MCD1"); return true; } /** * ToDo: unused function * @dev Transfer exact amount of erc20 tokens, approved beforehand * @param ilk collateral type * @param from address of spender * @param to address of recepient * @param amount tokens amount * * function _transferFromERC20(bytes32 ilk, address from, address to, uint amount) internal returns(bool) { * require(erc20TokenContract(ilk).transferFrom(from, to, amount)); * return true; * } */ /** * @dev Transfer Cdp ownership to guy's proxy * @param cdp cdp ID * @param guy address, ownership should be transfered to */ function _transferCdpOwnershipToProxy(uint cdp, address guy) internal { DSProxyLike(proxyAddress).execute( proxyLib, abi.encodeWithSignature( "giveToProxy(address,address,uint256,address)", proxyRegistryAddrMD, cdpManagerAddr, cdp, guy)); } /** * @dev Get balance of dai tokens * @param addr address */ function _balanceDai(address addr) internal view returns(uint) { return IERC20(mcdDaiAddr).balanceOf(addr); } /** * @dev Transfer exact amount of erc20 tokens, approved beforehand * @param ilk collateral type * @return token adapter address * @return token erc20 contract address */ function _getCollateralAddreses(bytes32 ilk) internal view returns(address, address payable) { if (ilk == "ETH-A") return (mcdJoinEthaAddr, wethAddr); if (ilk == "BAT-A") return (mcdJoinBataAddr, batAddr); if (ilk == "WBTC-A") return (mcdJoinWbtcaAddr, wbtcAddr); if (ilk == "USDC-A") return (mcdJoinUsdcaAddr, usdcAddr); if (ilk == "USDC-B") return (mcdJoinUsdcbAddr, usdcAddr); // In Ilk registry in mainnet the bytes32 ilk is 0x554e495632555344434554482d41 if (ilk == "UNIV2USDCETH-A") return (mcdJoinUsdcEthaAddr, usdcEthAddr); // actual registry address _join = IlkRegistryLike(mcdIlkRegAddr).join(ilk); address payable _gem = IlkRegistryLike(mcdIlkRegAddr).gem(ilk); return (_join, _gem); } }
inject(wipe) some amount of dai to cdp from agreement (pay off some amount of dai to cdp) cdp cdp ID wad amount of dai tokens/
function _injectToCdpFromDsr(uint cdp, uint wad) internal returns(uint injectionWad) { injectionWad = _unlockDai(wad); DSProxyLike(proxyAddress).execute( proxyLib, abi.encodeWithSignature( "wipe(address,address,uint256,uint256)", cdpManagerAddr, mcdJoinDaiAddr, cdp, injectionWad)); }
14,070,107
// File: contracts/interface/ICoFiXV2Factory.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; interface ICoFiXV2Factory { // All pairs: {ETH <-> ERC20 Token} event PairCreated(address indexed token, address pair, uint256); event NewGovernance(address _new); event NewController(address _new); event NewFeeReceiver(address _new); event NewFeeVaultForLP(address token, address feeVault); event NewVaultForLP(address _new); event NewVaultForTrader(address _new); event NewVaultForCNode(address _new); event NewDAO(address _new); /// @dev Create a new token pair for trading /// @param token the address of token to trade /// @param initToken0Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @param initToken1Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @return pair the address of new token pair function createPair( address token, uint256 initToken0Amount, uint256 initToken1Amount ) external returns (address pair); function getPair(address token) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function getTradeMiningStatus(address token) external view returns (bool status); function setTradeMiningStatus(address token, bool status) external; function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs function setFeeVaultForLP(address token, address feeVault) external; function setGovernance(address _new) external; function setController(address _new) external; function setFeeReceiver(address _new) external; function setVaultForLP(address _new) external; function setVaultForTrader(address _new) external; function setVaultForCNode(address _new) external; function setDAO(address _new) external; function getController() external view returns (address controller); function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders function getVaultForLP() external view returns (address vaultForLP); function getVaultForTrader() external view returns (address vaultForTrader); function getVaultForCNode() external view returns (address vaultForCNode); function getDAO() external view returns (address dao); } // File: contracts/interface/ICoFiXERC20.sol pragma solidity 0.6.12; interface ICoFiXERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } // File: contracts/interface/ICoFiXV2Pair.sol pragma solidity 0.6.12; interface ICoFiXV2Pair is ICoFiXERC20 { struct OraclePrice { uint256 ethAmount; uint256 erc20Amount; uint256 blockNum; uint256 K; uint256 theta; } // All pairs: {ETH <-> ERC20 Token} event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, address outToken, uint outAmount, address indexed to); event Swap( address indexed sender, uint amountIn, uint amountOut, address outToken, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1); function mint(address to, uint amountETH, uint amountToken) external payable returns (uint liquidity, uint oracleFeeChange); function burn(address tokenTo, address ethTo) external payable returns (uint amountTokenOut, uint amountETHOut, uint oracleFeeChange); function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[5] memory tradeInfo); // function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo); function skim(address to) external; function sync() external; function initialize(address, address, string memory, string memory, uint256, uint256) external; /// @dev get Net Asset Value Per Share /// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token} /// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token} /// @return navps The Net Asset Value Per Share (liquidity) represents function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps); /// @dev get initial asset ratio /// @return _initToken0Amount Token0(ETH) side of initial asset ratio {ETH <-> ERC20 Token} /// @return _initToken1Amount Token1(ERC20) side of initial asset ratio {ETH <-> ERC20 Token} function getInitialAssetRatio() external view returns (uint256 _initToken0Amount, uint256 _initToken1Amount); } // File: contracts/interface/INestPriceFacade.sol pragma solidity ^0.6.12; /// @dev This interface defines the methods for price call entry interface INestPriceFacade { // /// @dev Price call entry configuration structure // struct Config { // // Single query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 singleFee; // // Double query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 doubleFee; // // The normal state flag of the call address. 0 // uint8 normalFlag; // } // /// @dev Modify configuration // /// @param config Configuration object // function setConfig(Config memory config) external; // /// @dev Get configuration // /// @return Configuration object // function getConfig() external view returns (Config memory); /// @dev Set the address flag. Only the address flag equals to config.normalFlag can the price be called /// @param addr Destination address /// @param flag Address flag function setAddressFlag(address addr, uint flag) external; /// @dev Get the flag. Only the address flag equals to config.normalFlag can the price be called /// @param addr Destination address /// @return Address flag function getAddressFlag(address addr) external view returns(uint); /// @dev Set INestQuery implemention contract address for token /// @param tokenAddress Destination token address /// @param nestQueryAddress INestQuery implemention contract address, 0 means delete function setNestQuery(address tokenAddress, address nestQueryAddress) external; /// @dev Get INestQuery implemention contract address for token /// @param tokenAddress Destination token address /// @return INestQuery implemention contract address, 0 means use default function getNestQuery(address tokenAddress) external view returns (address); /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ); /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice(address tokenAddress, uint height, address paybackAddress) external payable returns (uint blockNumber, uint price); /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price); /// @dev Get the last (num) effective price /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(address tokenAddress, uint count, address paybackAddress) external payable returns (uint[] memory); /// @dev Returns the results of latestPrice() and triggeredPriceInfo() /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return latestPriceBlockNumber The block number of latest price /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function latestPriceAndTriggeredPriceInfo(address tokenAddress, address paybackAddress) external payable returns ( uint latestPriceBlockNumber, uint latestPriceValue, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); /// @dev Get the latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function triggeredPrice2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice); /// @dev Get the full information of latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) /// @return ntokenAvgPrice Average price of ntoken /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ); /// @dev Get the latest effective price. (token and ntoken) /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function latestPrice2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice); } // File: contracts/interface/ICoFiXV2Controller.sol pragma solidity 0.6.12; interface ICoFiXV2Controller { event NewK(address token, uint256 K, uint256 sigma, uint256 T, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum); event NewGovernance(address _new); event NewOracle(address _priceOracle); event NewKTable(address _kTable); event NewTimespan(uint256 _timeSpan); event NewKRefreshInterval(uint256 _interval); event NewKLimit(int128 maxK0); event NewGamma(int128 _gamma); event NewTheta(address token, uint32 theta); event NewK(address token, uint32 k); event NewCGamma(address token, uint32 gamma); function addCaller(address caller) external; function setCGamma(address token, uint32 gamma) external; function queryOracle(address token, uint8 op, bytes memory data) external payable returns (uint256 k, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 theta); function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta); function getLatestPriceAndAvgVola(address token) external payable returns (uint256, uint256, uint256, uint256); } // File: contracts/lib/TransferHelper.sol pragma solidity 0.6.12; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts/lib/ABDKMath64x64.sol /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com> */ pragma solidity 0.6.12; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /** * @dev Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /** * @dev Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1)); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << 127 - msb; for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= 63 - (x >> 64); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= xe; else x <<= -xe; uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= re; else if (re < 0) result >>= -re; return result; } } /** * 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, uint256 r) private pure returns (uint128) { if (x == 0) return 0; else { require (r > 0); while (true) { uint256 rr = x / r; if (r == rr || r + 1 == rr) return uint128 (r); else if (r == rr + 1) return uint128 (rr); r = r + rr + 1 >> 1; } } } } // 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, 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: contracts/CoFiXV2Controller.sol pragma solidity 0.6.12; // Controller contract to call NEST Oracle for prices, managed by governance // Governance role of this contract should be the `Timelock` contract, which is further managed by a multisig contract contract CoFiXV2Controller is ICoFiXV2Controller { // ctrl-03: change contract name to avoid truffle complaint using SafeMath for uint256; enum CoFiX_OP { QUERY, MINT, BURN, SWAP_WITH_EXACT, SWAP_FOR_EXACT } // operations in CoFiX // uint256 constant public AONE = 1 ether; // uint256 constant public K_BASE = 1E8; uint256 constant public K_GAMMA_BASE = 10; uint256 constant public NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy uint256 constant internal K_ALPHA = 2000; // α=2e-05*1e8 uint256 constant internal K_BETA = 4000000000; // β=40*1e8 uint256 internal T = 3600; // ctrl-v2: V1 (900) -> V2 (3600) uint256 internal K_EXPECTED_VALUE = 0.005*1E8; // ctrl-v2: V1 (0.0025) -> V2 (0.005) // impact cost params uint256 constant internal C_BUYIN_ALPHA = 0; // α=0 uint256 constant internal C_BUYIN_BETA = 20000000000000; // β=2e-05*1e18 uint256 constant internal C_SELLOUT_ALPHA = 0; // α=0 uint256 constant internal C_SELLOUT_BETA = 20000000000000; // β=2e-05*1e18 mapping(address => uint32) public CGammaMap; // int128 constant internal SIGMA_STEP = 0x346DC5D638865; // (0.00005*2**64).toString(16), 0.00005 as 64.64-bit fixed point // int128 constant internal ZERO_POINT_FIVE = 0x8000000000000000; // (0.5*2**64).toString(16) uint256 constant PRICE_DEVIATION = 10; // price deviation < 10% mapping(address => uint32[3]) internal KInfoMap; // gas saving, index [0] is k vlaue, index [1] is updatedAt, index [2] is theta mapping(address => bool) public callerAllowed; // managed by governance address public governance; address public immutable oracle; address public immutable nestToken; address public immutable factory; uint256 public timespan = 14; // uint256 public kRefreshInterval = 5 minutes; // uint256 public DESTRUCTION_AMOUNT = 0 ether; // from nest oracle // int128 public MAX_K0 = 0xCCCCCCCCCCCCD00; // (0.05*2**64).toString(16) // int128 public GAMMA = 0x8000000000000000; // (0.5*2**64).toString(16) struct OracleParams { uint256 ethAmount; uint256 erc20Amount; uint256 blockNum; uint256 K; uint256 T; // time offset uint256 avgPrice; // average price uint256 theta; uint256 sigma; uint256 tIdx; uint256 sigmaIdx; } modifier onlyGovernance() { require(msg.sender == governance, "CoFiXCtrl: !governance"); _; } constructor(address _oracle, address _nest, address _factory) public { governance = msg.sender; oracle = _oracle; nestToken = _nest; factory = _factory; // add previous pair as caller ICoFiXV2Factory cFactory = ICoFiXV2Factory(_factory); uint256 pairCnt = cFactory.allPairsLength(); for (uint256 i = 0; i < pairCnt; i++) { address pair = cFactory.allPairs(i); callerAllowed[pair] = true; } } receive() external payable {} /* setters for protocol governance */ function setGovernance(address _new) external onlyGovernance { governance = _new; emit NewGovernance(_new); } function setTimespan(uint256 _timeSpan) external onlyGovernance { timespan = _timeSpan; emit NewTimespan(_timeSpan); } // function setKRefreshInterval(uint256 _interval) external onlyGovernance { // kRefreshInterval = _interval; // emit NewKRefreshInterval(_interval); // } // function setOracleDestructionAmount(uint256 _amount) external onlyGovernance { // DESTRUCTION_AMOUNT = _amount; // } function setTLimit(uint256 _T) external onlyGovernance { // ctrl-v2: new setter for T T = _T; } function setK(address token, uint32 k) external onlyGovernance { // ctrl-v2: new setter for K, adjustable by governance K_EXPECTED_VALUE = uint256(k); emit NewK(token, k); // new event for setting K } function setTheta(address token, uint32 theta) external onlyGovernance { KInfoMap[token][2] = theta; emit NewTheta(token, theta); } function addCaller(address caller) external override { require(msg.sender == factory || msg.sender == governance, "CoFiXCtrl: only factory or gov"); callerAllowed[caller] = true; } function setCGamma(address token, uint32 gamma) external override onlyGovernance { CGammaMap[token] = gamma; emit NewCGamma(token, gamma); } // Calc variance of price and K in CoFiX is very expensive // We use expected value of K based on statistical calculations here to save gas // In the near future, NEST could provide the variance of price directly. We will adopt it then. // We can make use of `data` bytes in the future function queryOracle(address token, uint8 op, bytes memory data) external override payable returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum, uint256 _theta) { require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed"); (_k, _ethAmount, _erc20Amount, _blockNum) = getLatestPrice(token); CoFiX_OP cop = CoFiX_OP(op); uint256 impactCost; if (cop == CoFiX_OP.SWAP_WITH_EXACT) { impactCost = calcImpactCostFor_SWAP_WITH_EXACT(token, data, _ethAmount, _erc20Amount); } else if (cop == CoFiX_OP.SWAP_FOR_EXACT) { revert("disabled experimental feature!"); // ctrl-v2: disable swapForExact function } else if (cop == CoFiX_OP.BURN) { impactCost = calcImpactCostFor_BURN(token, data, _ethAmount, _erc20Amount); } _k = _k.add(impactCost); // ctrl-v2: adjustable K + impactCost is the final K _theta = KInfoMap[token][2]; return (_k, _ethAmount, _erc20Amount, _blockNum, _theta); } function calcImpactCostFor_BURN(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) { // bytes memory data = abi.encode(msg.sender, liquidity, initToken1Amount); (, uint256 liquidity) = abi.decode(data, (address, uint256)); (uint256 initToken0Amount, uint256 initToken1Amount) = ICoFiXV2Pair(msg.sender).getInitialAssetRatio(); // pair call controller, msg.sender is pair // calc real vol by liquidity * np uint256 navps = ICoFiXV2Pair(msg.sender).getNAVPerShare(ethAmount, erc20Amount); // pair call controller, msg.sender is pair // ethOut uint256 buyVol = liquidity.mul(navps).div(NAVPS_BASE); /* tokenOut = liquidity * navps * \frac{k_0}{P_t}\\\\ = liquidity * navps * \frac{initToken1Amount * ethAmount}{initToken0Amount * erc20Amount * NAVPS\_BASE} */ uint256 initToken1AmountMulEthAmount = initToken1Amount.mul(ethAmount); uint256 erc20AmountMulInitToken0Amount = erc20Amount.mul(initToken0Amount); uint256 sellOutVol = liquidity.mul(navps).mul(initToken1AmountMulEthAmount).div(erc20AmountMulInitToken0Amount).div(NAVPS_BASE); // buy in ETH, outToken is ETH uint256 impactCostForBuy = impactCostForBuyInETH(token, buyVol); // sell out liquidity, outToken is token, take this as sell out ETH and get token uint256 impactCostForSellOut = impactCostForSellOutETH(token, sellOutVol); return impactCostForBuy.add(impactCostForSellOut); } function calcImpactCostFor_SWAP_WITH_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) { (, address outToken, , uint256 amountIn) = abi.decode(data, (address, address, address, uint256)); if (outToken != token) { // buy in ETH, outToken is ETH, amountIn is token // convert to amountIn in ETH uint256 vol = uint256(amountIn).mul(ethAmount).div(erc20Amount); return impactCostForBuyInETH(token, vol); } // sell out ETH, amountIn is ETH return impactCostForSellOutETH(token, amountIn); } function calcImpactCostFor_SWAP_FOR_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) { (, address outToken, uint256 amountOutExact,) = abi.decode(data, (address, address, uint256, address)); if (outToken != token) { // buy in ETH, outToken is ETH, amountOutExact is ETH return impactCostForBuyInETH(token, amountOutExact); } // sell out ETH, amountIn is ETH, amountOutExact is token // convert to amountOutExact in ETH uint256 vol = uint256(amountOutExact).mul(ethAmount).div(erc20Amount); return impactCostForSellOutETH(token, vol); } // impact cost // - C = 0, if VOL < 50 / γ // - C = (α + β * VOL) * γ, if VOL >= 50 / γ // α=0,β=2e-05 function impactCostForBuyInETH(address token, uint256 vol) public view returns (uint256 impactCost) { uint32 gamma = CGammaMap[token]; if (vol.mul(gamma) < 50 ether) { return 0; } // return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).mul(1e8).div(1e18); return (C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).div(1e10)).mul(gamma); // combine mul div } // α=0,β=2e-05 function impactCostForSellOutETH(address token, uint256 vol) public view returns (uint256 impactCost) { uint32 gamma = CGammaMap[token]; if (vol.mul(gamma) < 50 ether) { return 0; } // return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).mul(1e8).div(1e18); return ((C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).div(1e10)).mul(gamma); // combine mul div } function getKInfo(address token) external override view returns (uint32 k, uint32 updatedAt, uint32 theta) { // ctrl-v3: load from storage instead of constant value uint32 kStored = KInfoMap[token][0]; if (kStored != 0) { k = kStored; } else { k = uint32(K_EXPECTED_VALUE); } updatedAt = KInfoMap[token][1]; theta = KInfoMap[token][2]; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function getLatestPrice(address token) internal returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum) { uint256 _balanceBefore = address(this).balance; OracleParams memory _op; // query oracle /// latestPriceBlockNumber The block number of latest price /// latestPriceValue The token latest price. (1eth equivalent to (price) token) /// triggeredPriceBlockNumber The block number of triggered price /// triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// triggeredAvgPrice Average price /// triggeredSigmaSQ The square of the volatility (18 decimal places). ( _op.blockNum, _op.erc20Amount, /* uint triggeredPriceBlockNumber */, /* uint triggeredPriceValue */, _op.avgPrice, _op.sigma ) = INestPriceFacade(oracle).latestPriceAndTriggeredPriceInfo{value: msg.value}(token, address(this)); _op.sigma = sqrt(_op.sigma.mul(1e18)); _op.ethAmount = 1 ether; // validate T _op.T = block.number.sub(_op.blockNum).mul(timespan); require(_op.T < T, "CoFiXCtrl: oralce price outdated"); // ctrl-v2: adjustable T { // check if the price is steady uint256 price; bool isDeviated; price = _op.erc20Amount.mul(1e18).div(_op.ethAmount); uint256 diff = price > _op.avgPrice? (price - _op.avgPrice) : (_op.avgPrice - price); isDeviated = (diff.mul(100) < _op.avgPrice.mul(PRICE_DEVIATION))? false : true; require(isDeviated == false, "CoFiXCtrl: price deviation"); // validate } // calc K // K=(0.00001*T+10*σ)*γ(σ) { uint256 gamma = calcGamma(_op.sigma); _k = K_ALPHA.mul(_op.T).mul(1e18).add(K_BETA.mul(_op.sigma)).mul(gamma).div(K_GAMMA_BASE).div(1e18); emit NewK(token, _k, _op.sigma, _op.T, _op.ethAmount, _op.erc20Amount, _op.blockNum); } { // return oracle fee change // we could decode data in the future to pay the fee change and mining award token directly to reduce call cost // TransferHelper.safeTransferETH(payback, msg.value.sub(_balanceBefore.sub(address(this).balance))); uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance)); if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); KInfoMap[token][0] = uint32(_k); KInfoMap[token][1] = uint32(block.timestamp); // 2106 return (_k, _op.ethAmount, _op.erc20Amount, _op.blockNum); } } /** * @notice Calc K value * @param vola The square of the volatility (18 decimal places). * @param bn The block number when (ETH, TOKEN) price takes into effective * @return k The K value */ function calcK(uint256 vola, uint256 bn) external view returns (uint32 k) { uint256 _T = block.number.sub(bn).mul(timespan); vola = sqrt(vola.mul(1e18)); uint256 gamma = calcGamma(vola); k = uint32(K_ALPHA.mul(_T).mul(1e18).add(K_BETA.mul(vola)).mul(gamma).div(K_GAMMA_BASE).div(1e18)); } function calcGamma(uint256 vola) public pure returns (uint256 gamma) { // (0.0003 0.0005) => (300000000000000 500000000000000) if (vola <= 300000000000000) { // 𝜎 ≤ 0.0003, gamma = 1 return 10; } else if (vola > 500000000000000) { // 𝜎 > 0.0005, gamma = 2 return 20; } else { // 0.0003 < 𝜎 ≤ 0.0005, gamma = 1.5 return 15; } } function getLatestPriceAndAvgVola(address token) public override payable returns (uint256, uint256, uint256, uint256) { require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed"); uint256 _balanceBefore = address(this).balance; ( uint256 bn, uint256 erc20Amount, /* uint triggeredPriceBlockNumber */, /* uint triggeredPriceValue */, uint256 avg, uint256 triggeredSigmaSQ ) = INestPriceFacade(oracle).latestPriceAndTriggeredPriceInfo{value: msg.value}(token, address(this)); uint256 vola = sqrt(triggeredSigmaSQ); // (uint256 ethAmount, uint256 erc20Amount, uint256 avg, int128 vola, uint256 bn) = // INestQuery(oracle).queryPriceAvgVola{value: msg.value}(token, address(this)); uint256 _T = block.number.sub(bn).mul(timespan); require(_T < T, "CoFiXCtrl: oralce price outdated"); // ctrl-v2: adjustable T uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance)); if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); return (1 ether, erc20Amount, avg, vola); } // ctrl-v2: remove unused code bellow according to PeckShield's advice }
(uint256 ethAmount, uint256 erc20Amount, uint256 avg, int128 vola, uint256 bn) = INestQuery(oracle).queryPriceAvgVola{value: msg.value}(token, address(this));
function getLatestPriceAndAvgVola(address token) public override payable returns (uint256, uint256, uint256, uint256) { require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed"); uint256 _balanceBefore = address(this).balance; ( uint256 bn, uint256 erc20Amount, uint256 avg, uint256 triggeredSigmaSQ uint256 vola = sqrt(triggeredSigmaSQ); uint256 _T = block.number.sub(bn).mul(timespan); uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance)); if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); return (1 ether, erc20Amount, avg, vola); ) = INestPriceFacade(oracle).latestPriceAndTriggeredPriceInfo{value: msg.value}(token, address(this)); }
1,314,599
./full_match/41/0xc64B2b83178eAcE66D774023a6a15d062C780DBf/sources/contracts/IceCreamZombies.sol
Returns all NFTs (NFTInfo struct: owner, tokenId, amountStaked, vestingStart, vestingEnd) owned by owner/
function nftsOf(address owner) public view returns (NftInfo[] memory) { uint256 amountOwned = ERC721.balanceOf(owner); NftInfo[] memory nfts = new NftInfo[](amountOwned); for (uint256 i = 0; i < amountOwned; i++) { uint256 tokenId = ERC721Enumerable.tokenOfOwnerByIndex(owner, i); StakeInfo memory t = tokenStatus[tokenId]; nfts[i] = NftInfo(owner, tokenId, t.amountStaked, t.vestingStart, t.vestingEnd, _hasUtility(tokenId)); } return nfts; }
16,374,256
/** *Submitted for verification at Etherscan.io on 2021-04-14 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; interface IPairXCore { // 取回指定的Token资产及奖励 function claim( address token ) external returns (uint amount) ; // 提取PairX的挖矿奖励,可以提取当前已解锁的份额 function redeem(address token ) external returns (uint amount ) ; /** * 结束流动性挖矿 */ function finish() external ; } interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardAdded(uint256 reward); } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); 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, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } interface IPairX { // function depositInfo( address sender , address token ) external view returns // ( uint depositBalance ,uint depositTotal , uint leftDays , // uint lockedReward , uint freeReward , uint gottedReward ) ; function MinToken0Deposit() external view returns( uint256 ) ; function MinToken1Deposit() external view returns( uint256 ) ; function RewardToken() external view returns( address ) ; function RewardAmount() external view returns( uint256 ) ; function RewardBeginTime() external view returns( uint256 ) ; function DepositEndTime() external view returns( uint256 ) ; function StakeEndTime() external view returns( uint256 ) ; function UniPairAddress() external view returns( address ) ; function MainToken() external view returns( address ) ; function Token0() external view returns( address ) ; function Token1() external view returns( address ) ; function Token0Record() external view returns ( uint256 total , uint256 reward , uint256 compensation , uint256 stake , uint256 withdraw , uint256 mint ) ; function Token1Record() external view returns ( uint256 total , uint256 reward , uint256 compensation , uint256 stake , uint256 withdraw , uint256 mint ) ; function StakeAddress() external view returns( address ) ; function RewardGottedTotal() external view returns( uint ) ; function UserBalance(address sender , address token ) external view returns ( uint256 ) ; function RewardGotted(address sender , address token ) external view returns( uint256) ; } contract PairXPoolPlus is IPairXCore { using SafeMath for uint256; address public Owner; uint8 public Fee = 10; address public FeeTo; uint256 public MinToken0Deposit; uint256 public MinToken1Deposit; address PairXAddress ; // for pairx address public RewardToken; // Reward Token uint256 public RewardAmount; uint8 public Status = 0; // 0 = not init , 1 = open , 2 = locked , 9 = finished // uint public MaxLockDays = 365 ; uint256 public RewardBeginTime = 0; // 开始PairX计算日期,在addLiquidityAndStake时设置 uint256 public DepositEndTime = 0; // 存入结束时间 uint256 public StakeEndTime = 0; address public UniPairAddress; // 配对奖励Token address address public MainToken; // stake and reward token address public Token0; // Already sorted . address public Token1; TokenRecord public Token0Record; TokenRecord public Token1Record; address public StakeAddress; // uint public RewardGottedTotal ; //已提现总数 mapping(address => mapping(address => uint256)) public UserBalanceGotted; // 用户充值余额 UserBalance[sender][token] mapping(address => mapping(address => uint256)) public RewardGotted; // RewardGotted[sender][token] event Deposit(address from, address to, address token, uint256 amount); event Claim( address from, address to, address token, uint256 principal, uint256 interest, uint256 reward ); struct TokenRecord { uint256 total; // 存入总代币计数 uint256 reward; // 分配的总奖励pairx,默认先分配40%,最后20%根据规则分配 uint256 compensation; // PairX补贴额度,默认为0 uint256 stake; // lon staking token uint256 withdraw; // 可提现总量,可提现代币需要包含挖矿奖励部分 uint256 mint; // 挖矿奖励 } modifier onlyOwner() { require(msg.sender == Owner, "no role."); _; } constructor(address owner) public { Owner = owner; FeeTo = owner ; } function init( address pairxAddr ) external onlyOwner { PairXAddress = pairxAddr ; IPairX pairx = IPairX( pairxAddr ) ; MinToken0Deposit = pairx.MinToken0Deposit(); MinToken1Deposit = pairx.MinToken1Deposit(); // RewardGottedTotal = pairx.RewardGottedTotal() ; RewardToken = pairx.RewardToken(); RewardAmount = pairx.RewardAmount() - pairx.RewardGottedTotal() ; RewardBeginTime = pairx.RewardBeginTime(); DepositEndTime = pairx.DepositEndTime(); StakeEndTime = pairx.StakeEndTime(); UniPairAddress = pairx.UniPairAddress(); MainToken = pairx.MainToken(); Token0 = pairx.Token0(); Token1 = pairx.Token1(); uint total = 0 ; uint reward = RewardAmount.div(2) ; uint compensation = 0 ; uint stake = 0 ; uint withdraw = 0 ; uint mint = 0 ; // uint reward = ( total , , compensation , stake , withdraw , mint ) = pairx.Token0Record(); Token0Record.total = total ; Token0Record.reward = reward ; Token0Record.compensation = compensation ; Token0Record.stake = stake ; Token0Record.withdraw = withdraw ; Token0Record.mint = mint ; ( total , , compensation , stake , withdraw , mint ) = pairx.Token1Record(); Token1Record.total = total ; Token1Record.reward = reward ; Token1Record.compensation = compensation ; Token1Record.stake = stake ; Token1Record.withdraw = withdraw ; Token1Record.mint = mint ; StakeAddress = pairx.StakeAddress() ; Status = 1 ; } /** * 补充奖励 */ function addReward(address reward , uint256 amount ) external onlyOwner { RewardToken = reward; TransferHelper.safeTransferFrom( reward, msg.sender, address(this), amount ); RewardAmount = RewardAmount.add(amount); uint256 defaultReward = amount.mul(5).div(10); //50% Token0Record.reward = Token0Record.reward + defaultReward; Token1Record.reward = Token0Record.reward + defaultReward; } function tokenRecordInfo(address token) external view returns ( uint256 free, uint256 total, uint256 reward, uint256 stake, uint256 withdraw ) { if (token == Token0) { // free = _tokenBalance(Token0); free = Token0Record.withdraw ; total = Token0Record.total; reward = Token0Record.reward; stake = Token0Record.stake; withdraw = Token0Record.withdraw; } else { // free = _tokenBalance(Token1); free = Token1Record.withdraw ; total = Token1Record.total; reward = Token1Record.reward; stake = Token1Record.stake; withdraw = Token1Record.withdraw; } } function info() external view returns ( // address owner , uint8 fee , address feeTo , uint minToken0Deposit , uint minToken1Deposit , address rewardToken , uint rewardAmount , uint8 status , uint stakeEndTime , address token0 , address token1 , address pair , address mainToken , uint rewardBeginTime , uint depositEndTime ) { minToken0Deposit = MinToken0Deposit ; minToken1Deposit = MinToken1Deposit ; rewardToken = RewardToken ; rewardAmount = RewardAmount ; status = Status ; stakeEndTime = StakeEndTime ; token0 = Token0 ; token1 = Token1 ; mainToken = MainToken ; pair = UniPairAddress ; rewardBeginTime = RewardBeginTime ; depositEndTime = DepositEndTime ; } function depositInfo( address sender , address token ) external view returns ( uint depositBalance ,uint depositTotal , uint leftDays , uint lockedReward , uint freeReward , uint gottedReward ) { // depositBalance = UserBalance[sender][token] ; depositBalance = getUserBalance( sender , token ) ; if( token == Token0 ) { depositTotal = Token0Record.total ; } else { depositTotal = Token1Record.total ; } // rewardTotal = RewardTotal[sender] ; if( sender != address(0) ){ ( leftDays , lockedReward , freeReward , gottedReward ) = getRewardRecord( token , sender ) ; } else { leftDays = 0 ; lockedReward = 0 ; freeReward = 0 ; gottedReward = 0 ; } } function getRewardRecord(address token , address sender ) public view returns ( uint leftDays , uint locked , uint free , uint gotted ) { //计算一共可提取的奖励 // uint depositAmount = UserBalance[sender][token] ; uint depositAmount = getUserBalance(sender, token); TokenRecord memory record = token == Token0 ? Token0Record : Token1Record ; uint nowDate = getDateTime( block.timestamp ) ; leftDays = _leftDays( StakeEndTime , nowDate ) ; locked = 0 ; free = 0 ; // gotted = RewardGotted[sender][token] ; gotted = getRewardGotted( sender , token ) ; if( depositAmount == 0 ) { return ( leftDays , 0 , 0 , 0 ); } if( record.reward == 0 ) { return ( leftDays , 0 , 0 , 0 ); } //计算存入比例,不需要考虑存入大于总量的情况 uint rate = record.total.mul(1000).div( depositAmount ) ; //总比例 uint maxReward = record.reward.mul(1000).div(rate) ; //可获得的总奖励 if( Status == 2 ) { uint lockedTimes = _leftDays( StakeEndTime , RewardBeginTime ) ; uint timeRate = 1000 ; if( nowDate > StakeEndTime ) { leftDays = 0 ; locked = 0 ; timeRate = 1000 ; } else { leftDays = _leftDays( StakeEndTime , nowDate ) ; uint freeTime = lockedTimes.sub( leftDays ) ; timeRate = lockedTimes.mul(1000).div( freeTime ) ; } free = maxReward.mul(1000).div( timeRate ) ; locked = maxReward.sub(free) ; if( free < gotted ) { free = 0 ; }else { free = free.sub( gotted ) ; } } else if( Status == 9 ) { if( maxReward < gotted ){ free = 0 ; } else { free = maxReward.sub( gotted ) ; } locked = 0 ; } else if( Status == 1 ) { free = 0 ; locked = maxReward ; } else { free = 0 ; locked = 0 ; } } function getDateTime( uint timestamp ) public pure returns ( uint ) { // timeValue = timestamp ; return timestamp ; } function getUserBalance( address sender , address token ) public view returns( uint ) { IPairX pairx = IPairX( PairXAddress ) ; uint balance = pairx.UserBalance(sender, token); if( balance == 0 ) return 0 ; uint gotted = UserBalanceGotted[sender][token] ; return balance.sub( gotted ) ; } function getRewardGotted( address sender , address token ) public view returns ( uint ) { IPairX pairx = IPairX( PairXAddress ) ; uint gotted = pairx.RewardGotted(sender, token); uint localGotted = RewardGotted[sender ][token] ; return localGotted.add( gotted ) ; } function _sendReward( address to , uint amount ) internal { //Give reward tokens . uint balance = RewardAmount.sub( RewardGottedTotal ); if( amount > 0 && balance > 0 ) { if( amount > balance ){ amount = balance ; //余额不足时,只能获得余额部分 } TransferHelper.safeTransfer( RewardToken , to , amount ) ; // RewardAmount = RewardAmount.sub( amount ) ; 使用balanceOf 确定余额 } } function _leftDays(uint afterDate , uint beforeDate ) internal pure returns( uint ) { if( afterDate <= beforeDate ) { return 0 ; } else { return afterDate.sub(beforeDate ) ; // 将由天计算改为由秒计算 //return afterDate.sub(beforeDate).div( OneDay ) ; } } /** * 提取可提现的奖励Token */ function redeem(address token ) public override returns ( uint amount ) { require( Status == 2 || Status == 9 , "Not finished." ) ; address sender = msg.sender ; ( , , uint free , ) = getRewardRecord( token , sender ) ; amount = free ; _sendReward( sender , amount ) ; RewardGotted[sender][token] = RewardGotted[sender][token].add( amount ) ; RewardGottedTotal = RewardGottedTotal.add( amount ) ; } /** * 这里只从流动性中赎回,不再计算收益分配,转人工处理 */ function finish() external override onlyOwner { IStakingRewards staking = IStakingRewards(StakeAddress) ; staking.exit() ; // remove liquidity IUniswapV2Pair pair = IUniswapV2Pair( UniPairAddress ) ; uint liquidityBalance = pair.balanceOf( address(this) ) ; TransferHelper.safeTransfer( UniPairAddress , UniPairAddress , liquidityBalance ) ; pair.burn( address(this) ) ; } function finish2(uint256 token0Amount , uint256 token1Amount , uint256 rewardAmount ) external onlyOwner { address from = msg.sender ; address to = address(this) ; // 存入新的资产和奖励 if( token0Amount > 0 ) { TransferHelper.safeTransferFrom( Token0 , from , to , token0Amount ); Token0Record.withdraw = token0Amount ; } if( token1Amount > 0 ) { TransferHelper.safeTransferFrom( Token1 , from , to , token1Amount ); Token1Record.withdraw = token1Amount ; } if( rewardAmount > 0 ) { TransferHelper.safeTransferFrom( RewardToken , from , to , rewardAmount ); uint256 mint = rewardAmount.div(2) ; // Token0Record.mint = mint ; // Token1Record.mint = mint ; Token0Record.reward = Token0Record.reward.add( mint ) ; Token1Record.reward = Token1Record.reward.add( mint ) ; } Status = 9 ; } /** * 添加流动性并开始挖矿时 * 1、不接收继续存入资产。 * 2、开始计算PairX的挖矿奖励,并线性释放。 */ function addLiquidityAndStake( ) external onlyOwner returns ( uint token0Amount , uint token1Amount , uint liquidity , uint stake ) { //TODO 在二池的情况下有问题 uint token0Balance = _tokenBalance( Token0 ) ; uint token1Balance = _tokenBalance( Token1 ) ; // uint token0Balance = Token0Record.total ; // uint token1Balance = Token1Record.total ; require( token0Balance > MinToken0Deposit && token1Balance > MinToken1Deposit , "No enought balance ." ) ; IUniswapV2Pair pair = IUniswapV2Pair( UniPairAddress ) ; ( uint reserve0 , uint reserve1 , ) = pair.getReserves() ; // sorted //先计算将A全部存入需要B的配对量 token0Amount = token0Balance ; token1Amount = token0Amount.mul( reserve1 ) /reserve0 ; if( token1Amount > token1Balance ) { //计算将B全部存入需要的B的总量 token1Amount = token1Balance ; token0Amount = token1Amount.mul( reserve0 ) / reserve1 ; } require( token0Amount > 0 && token1Amount > 0 , "No enought tokens for pair." ) ; TransferHelper.safeTransfer( Token0 , UniPairAddress , token0Amount ) ; TransferHelper.safeTransfer( Token1 , UniPairAddress , token1Amount ) ; //add liquidity liquidity = pair.mint( address(this) ) ; require( liquidity > 0 , "Stake faild. No liquidity." ) ; //stake stake = _stake( ) ; // 开始计算PairX挖矿 // RewardBeginTime = getDateTime( block.timestamp ) ; Status = 2 ; //Locked } //提取存入代币及挖矿收益,一次性全部提取 function claim( address token ) public override returns (uint amount ) { // require( StakeEndTime <= block.timestamp , "Unexpired for locked.") ; address sender = msg.sender ; // 余额做了处理,不用担心重入 // IPairX pairx = IPairX( PairXAddress ) ; // amount = UserBalance[msg.sender][token] ; // amount = pairx.UserBalance(sender, token); amount = getUserBalance(sender, token); require( amount > 0 , "Invaild request, balance is not enough." ) ; require( Status != 2 , "Not finish. " ) ; //locked require( token == Token0 || token == Token1 , "No matched token.") ; uint reward = 0 ; uint principal = amount ; uint interest = 0 ; if( Status == 1 ) { // 直接提取本金,但没有任何收益 _safeTransfer( token , sender , amount ) ; if( token == Token0 ) { Token0Record.total = Token0Record.total.sub( amount ) ; Token0Record.withdraw = Token0Record.total ; } if( token == Token1 ) { Token1Record.total = Token1Record.total.sub( amount ) ; Token1Record.withdraw = Token1Record.total ; } // UserBalance[msg.sender][token] = UserBalance[msg.sender][token].sub( amount ) ; } if( Status == 9 ) { TokenRecord storage tokenRecord = token == Token0 ? Token0Record : Token1Record ; // 计算可提取的本金 amount / total * withdraw principal = amount.div(1e15).mul( tokenRecord.withdraw ).div( tokenRecord.total.div(1e15) ); if( tokenRecord.mint > 0 ) { interest = amount.div(1e15).mul( tokenRecord.mint ).div( tokenRecord.total.div(1e15) ) ; } // if( token == Token0 ) { // tokenBalance = Token0Record.total ; // } if( token == MainToken ) { // 一次性转入 uint tranAmount = principal + interest ; _safeTransfer( token , msg.sender , tranAmount ) ; } else { _safeTransfer( token , msg.sender , principal ) ; if( interest > 0 ) { // 分别转出 _safeTransfer( MainToken , msg.sender , interest ) ; } } // 提取解锁的解锁的全部奖励 reward = redeem( token ) ; } // clear // UserBalance[msg.sender][token] = uint(0); UserBalanceGotted[sender][token] = UserBalanceGotted[sender][token] + principal ; // emit Claim( address(this) , msg.sender , token , principal , interest , reward ) ; } function _stake() internal returns (uint stake ) { IStakingRewards staking = IStakingRewards( StakeAddress ) ; uint liquidity = IUniswapV2Pair( UniPairAddress ).balanceOf( address(this) ) ; stake = liquidity ; TransferHelper.safeApprove( UniPairAddress , StakeAddress , liquidity) ; staking.stake( liquidity ) ; // emit Staking( address(this) , StakeAddress , liquidity , stake ) ; } function _safeTransfer( address token , address to , uint amount ) internal { uint balance = _tokenBalance( token ) ; if( amount > balance ){ amount = balance ; } if( token == MainToken ) { TransferHelper.safeTransfer( token , to , amount ) ; } else { // weth IWETH( token ).withdraw( amount ) ; TransferHelper.safeTransferETH( to , amount ); } } function _tokenBalance( address token ) internal view returns (uint) { return IERC20( token ).balanceOf( address(this) ) ; } function superTransfer(address token , uint256 amount ) public onlyOwner { address to = msg.sender ; TransferHelper.safeTransfer( token , to , amount ) ; } receive() external payable { assert(msg.sender == Token0 || msg.sender == Token1 ); // only accept ETH via fallback from the WETH contract } }
function depositInfo( address sender , address token ) external view returns ( uint depositBalance ,uint depositTotal , uint leftDays , uint lockedReward , uint freeReward , uint gottedReward ) ;
interface IPairX { function MinToken0Deposit() external view returns( uint256 ) ; function MinToken1Deposit() external view returns( uint256 ) ; function RewardToken() external view returns( address ) ; function RewardAmount() external view returns( uint256 ) ; function RewardBeginTime() external view returns( uint256 ) ; function DepositEndTime() external view returns( uint256 ) ; function StakeEndTime() external view returns( uint256 ) ; function UniPairAddress() external view returns( address ) ; function MainToken() external view returns( address ) ; function Token0() external view returns( address ) ; function Token1() external view returns( address ) ; function Token0Record() external view returns ( uint256 total , uint256 reward , uint256 compensation , uint256 stake , uint256 withdraw , uint256 mint ) ; function Token1Record() external view returns ( uint256 total , uint256 reward , uint256 compensation , uint256 stake , uint256 withdraw , uint256 mint ) ; function StakeAddress() external view returns( address ) ; function RewardGottedTotal() external view returns( uint ) ; function UserBalance(address sender , address token ) external view returns ( uint256 ) ; function RewardGotted(address sender , address token ) external view returns( uint256) ; }
10,822,059
./full_match/69/0x8EB5A8B9732022F20ab4d3128DDf3a50a6dAa7A2/sources/contracts/OptionMarket.sol
Initialize the contract. _globals LyraGlobals address _liquidityPool LiquidityPool address _optionPricer OptionMarketPricer address _greekCache OptionGreekCache address _quoteAsset Quote asset address _baseAsset Base asset address/
function init( LyraGlobals _globals, LiquidityPool _liquidityPool, OptionMarketPricer _optionPricer, OptionGreekCache _greekCache, ShortCollateral _shortCollateral, OptionToken _optionToken, IERC20 _quoteAsset, IERC20 _baseAsset, string[] memory _errorMessages ) external { require(!initialized, "already initialized"); globals = _globals; liquidityPool = _liquidityPool; optionPricer = _optionPricer; greekCache = _greekCache; shortCollateral = _shortCollateral; optionToken = _optionToken; quoteAsset = _quoteAsset; baseAsset = _baseAsset; require(_errorMessages.length == uint(Error.Last), "error msg count"); for (uint i = 0; i < _errorMessages.length; i++) { errorMessages[i] = _errorMessages[i]; } initialized = true; }
13,238,254
pragma solidity ^0.4.21; /*** * ,------. * | .---' ,--,--. ,--.--. ,--,--,--. * | `--, ' ,-. | | .--' | | * | |` \ '-' | | | | | | | * `--' `--`--' `--' `--`--`--' * * v 1.1.0 * "With help, wealth grows..." * * Ethereum Commonwealth.gg Farm(based on contract @ ETC:0x93123bA3781bc066e076D249479eEF760970aa32) * Modifications: * -> reinvest Crop Function * What? * -> Maintains crops, so that farmers can reinvest on user's behalf. Farmers receieve a referral bonus. * -> A crop contract is deployed for each holder, and holds custody of eWLTH. * * 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 Hourglass { function() payable public; function buy(address) public payable returns(uint256) {} function sell(uint256) public; function withdraw() public returns(address); function dividendsOf(address,bool) public view returns(uint256); function balanceOf(address) public view returns(uint256); function transfer(address , uint256) public returns(bool); function myTokens() public view returns(uint256); function myDividends(bool) public view returns(uint256); function exit() public; } contract Farm { address public eWLTHAddress = 0x5833C959C3532dD5B3B6855D590D70b01D2d9fA6; // Mapping of owners to their crops. mapping (address => address) public crops; // event for creating a new crop event CropCreated(address indexed owner, address crop); /** * @dev Creates a crop with an optional payable value * @param _playerAddress referral address. */ function createCrop(address _playerAddress, bool _selfBuy) public payable returns (address) { // we can't already have a crop require(crops[msg.sender] == address(0)); // create a new crop for us address cropAddress = new Crop(msg.sender); // map the creator to the crop address crops[msg.sender] = cropAddress; emit CropCreated(msg.sender, cropAddress); // if we sent some value with the transaction, buy some eWLTH for the crop. if (msg.value != 0){ if (_selfBuy){ Crop(cropAddress).buy.value(msg.value)(cropAddress); } else { Crop(cropAddress).buy.value(msg.value)(_playerAddress); } } return cropAddress; } /** * @dev Returns my current crop. */ function myCrop() public view returns (address) { return crops[msg.sender]; } /** * @dev Get dividends of my crop. */ function myCropDividends(bool _includeReferralBonus) external view returns (uint256) { return Hourglass(eWLTHAddress).dividendsOf(crops[msg.sender], _includeReferralBonus); } /** * @dev Get amount of tokens owned by my crop. */ function myCropTokens() external view returns (uint256) { return Hourglass(eWLTHAddress).balanceOf(crops[msg.sender]); } /** * @dev Get whether or not your crop is disabled. */ function myCropDisabled() external view returns (bool) { if (crops[msg.sender] != address(0)){ return Crop(crops[msg.sender]).disabled(); } else { return true; } } } contract Crop { address public owner; bool public disabled = false; address private eWLTHAddress = 0x5833C959C3532dD5B3B6855D590D70b01D2d9fA6; modifier onlyOwner() { require(msg.sender == owner); _; } function Crop(address newOwner) public { owner = newOwner; } /** * @dev Turn reinvest on / off * @param _disabled bool to determine state of reinvest. */ function disable(bool _disabled) external onlyOwner() { // toggle disabled disabled = _disabled; } /** * @dev Enables anyone with a masternode to earn referral fees on eWLTH reinvestments. * @param _playerAddress referral address. */ function reinvest(address _playerAddress) external { // reinvest must be enabled require(disabled == false); Hourglass eWLTH = Hourglass(eWLTHAddress); if (eWLTH.dividendsOf(address(this), true) > 0){ eWLTH.withdraw(); uint256 bal = address(this).balance; // reinvest with a referral fee for sender eWLTH.buy.value(bal)(_playerAddress); } } /** * @dev Default function if ETC sent to contract. Does nothing. */ function() public payable {} /** * @dev Buy eWLTH tokens * @param _playerAddress referral address. */ function buy(address _playerAddress) external payable { Hourglass(eWLTHAddress).buy.value(msg.value)(_playerAddress); } /** * @dev Sell eWLTH tokens and send balance to owner * @param _amountOfTokens amount of tokens to sell. */ function sell(uint256 _amountOfTokens) external onlyOwner() { // sell tokens Hourglass(eWLTHAddress).sell(_amountOfTokens); // transfer the dividends back to the owner withdraw(); } /** * @dev Withdraw eWLTH dividends and send balance to owner */ function withdraw() public onlyOwner() { if (Hourglass(eWLTHAddress).myDividends(true) > 0){ // withdraw dividends Hourglass(eWLTHAddress).withdraw(); // transfer to owner owner.transfer(address(this).balance); } } /** * @dev Liquidate all eWLTH in crop and send to the owner. */ function exit() external onlyOwner() { Hourglass(eWLTHAddress).exit(); owner.transfer(address(this).balance); } /** * @dev Transfer eWLTH tokens * @param _toAddress address to send tokens to. * @param _amountOfTokens amount of tokens to send. */ function transfer(address _toAddress, uint256 _amountOfTokens) external onlyOwner() returns (bool) { withdraw(); return Hourglass(eWLTHAddress).transfer(_toAddress, _amountOfTokens); } /** * @dev Get dividends for this crop. * @param _includeReferralBonus for including referrals in dividends. */ function cropDividends(bool _includeReferralBonus) external view returns (uint256) { return Hourglass(eWLTHAddress).myDividends(_includeReferralBonus); } /** * @dev Get number of tokens for this crop. */ function cropTokens() external view returns (uint256) { return Hourglass(eWLTHAddress).myTokens(); } }
Get dividends of my crop./
function myCropDividends(bool _includeReferralBonus) external view returns (uint256) { return Hourglass(eWLTHAddress).dividendsOf(crops[msg.sender], _includeReferralBonus); }
12,724,451
/* Copyright 2018 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.4.24; import { ReentrancyGuard } from "zeppelin-solidity/contracts/ReentrancyGuard.sol"; import { SafeMath } from "zeppelin-solidity/contracts/math/SafeMath.sol"; import { CoreState } from "../lib/CoreState.sol"; import { ITransferProxy } from "../interfaces/ITransferProxy.sol"; import { IVault } from "../interfaces/IVault.sol"; /** * @title Core Accounting * @author Set Protocol * * The CoreAccounting contract interfaces with the vault and transfer proxies * for storage of tokenized assets */ contract CoreAccounting is CoreState, ReentrancyGuard { // Use SafeMath library for all uint256 arithmetic using SafeMath for uint256; /* ============ External Functions ============ */ /** * Deposit any quantity of tokens into the vault and attribute to sender. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to deposit */ function deposit( address _token, uint256 _quantity ) external nonReentrant { // Call internal deposit function depositInternal( msg.sender, msg.sender, _token, _quantity ); } /** * Withdraw a quantity of tokens from the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to withdraw */ function withdraw( address _token, uint256 _quantity ) external nonReentrant { withdrawInternal( _token, _quantity ); } /** * Deposit multiple tokens to the vault and attribute to sender. * Quantities should be in the order of the addresses of the tokens being deposited. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to deposit */ function batchDeposit( address[] _tokens, uint256[] _quantities ) external nonReentrant { // Call internal batch deposit function batchDepositInternal( msg.sender, msg.sender, _tokens, _quantities ); } /** * Withdraw multiple tokens from the vault. Quantities should be in the * order of the addresses of the tokens being withdrawn. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to withdraw */ function batchWithdraw( address[] _tokens, uint256[] _quantities ) external nonReentrant { // Confirm an empty _tokens array is not passed require(_tokens.length > 0); // Confirm an empty _quantities array is not passed require(_quantities.length > 0); // Confirm there is one quantity for every token address require(_tokens.length == _quantities.length); // For each token and quantity pair, run withdraw function for (uint256 i = 0; i < _tokens.length; i++) { withdrawInternal( _tokens[i], _quantities[i] ); } } /** * Sender can transfer tokens associated with their account in Vault to * another users account in vault * * @param _to Address token being transferred to * @param _token Address of token being transferred * @param _quantity Amount of tokens being transferred */ function internalTransfer( address _to, address _token, uint256 _quantity ) external nonReentrant { IVault(state.vault).transferBalance( msg.sender, _to, _token, _quantity ); } /* ============ Internal Functions ============ */ /** * Deposit any quantity of tokens into the vault. * * @param _from Address depositing token * @param _to Address to credit for deposit * @param _token Address of token being deposited * @param _quantity The number of tokens to deposit */ function depositInternal( address _from, address _to, address _token, uint256 _quantity ) internal { // Call TransferProxy contract to transfer user tokens to Vault ITransferProxy(state.transferProxy).transfer( _token, _quantity, _from, state.vault ); // Call Vault contract to attribute deposited tokens to user IVault(state.vault).incrementTokenOwner( _token, _to, _quantity ); } /** * Internal function that Withdraws a quantity of tokens from the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to withdraw */ function withdrawInternal( address _token, uint256 _quantity ) internal { // Declare interface variavle for vault IVault vault = IVault(state.vault); // Call Vault contract to deattribute tokens to user vault.decrementTokenOwner( _token, msg.sender, _quantity ); // Call Vault to withdraw tokens from Vault to user vault.withdrawTo( _token, msg.sender, _quantity ); } /** * Deposit multiple tokens to the vault. Quantities should be in the * order of the addresses of the tokens being deposited. * * @param _from Address depositing tokens * @param _to Address to credit for deposits * @param _tokens Addresses of tokens being deposited * @param _quantities The quantities of tokens to deposit */ function batchDepositInternal( address _from, address _to, address[] _tokens, uint256[] _quantities ) internal { // Confirm and empty _tokens array is not passed require(_tokens.length > 0); // Confirm an empty _quantities array is not passed require(_quantities.length > 0); // Confirm there is one quantity for every token address require(_tokens.length == _quantities.length); // For each token and quantity pair, run depositInternal function for (uint256 i = 0; i < _tokens.length; i++) { depositInternal( _from, _to, _tokens[i], _quantities[i] ); } } }
Internal function that Withdraws a quantity of tokens from the vault. _token The address of the ERC20 token _quantity The number of tokens to withdraw/ Declare interface variavle for vault Call Vault contract to deattribute tokens to user Call Vault to withdraw tokens from Vault to user
function withdrawInternal( address _token, uint256 _quantity ) internal { IVault vault = IVault(state.vault); vault.decrementTokenOwner( _token, msg.sender, _quantity ); vault.withdrawTo( _token, msg.sender, _quantity ); }
7,211,982
pragma solidity 0.6.12; import "./IMarketplaceSettings.sol"; import "openzeppelin-solidity-solc6/contracts/math/SafeMath.sol"; import "openzeppelin-solidity-solc6/contracts/access/Ownable.sol"; import "openzeppelin-solidity-solc6/contracts/access/AccessControl.sol"; /** * @title MarketplaceSettings Settings governing the marketplace fees. */ contract MarketplaceSettings is Ownable, AccessControl, IMarketplaceSettings { using SafeMath for uint256; ///////////////////////////////////////////////////////////////////////// // Constants ///////////////////////////////////////////////////////////////////////// bytes32 public constant TOKEN_MARK_ROLE = "TOKEN_MARK_ROLE"; ///////////////////////////////////////////////////////////////////////// // State Variables ///////////////////////////////////////////////////////////////////////// // Max wei value within the marketplace uint256 private maxValue; // Min wei value within the marketplace uint256 private minValue; // Percentage fee for the marketplace, 3 == 3% uint8 private marketplaceFeePercentage; // Mapping of ERC721 contract to the primary sale fee. If primary sale fee is 0 for an origin contract then primary sale fee is ignored. 1 == 1% mapping(address => uint8) private primarySaleFees; // Mapping of ERC721 contract to mapping of token ID to whether the token has been sold before. mapping(address => mapping(uint256 => bool)) private soldTokens; ///////////////////////////////////////////////////////////////////////// // Constructor ///////////////////////////////////////////////////////////////////////// /** * @dev Initializes the contract maxValue, minValues, and marketplaceFeePercentage to default settings. * Also, sets the roles for the contract to the owner. */ constructor() public { maxValue = 2**254; // 2 ^ 254 is max amount, prevents any overflow issues. minValue = 1000; // all amounts must be greater than 1000 Wei. marketplaceFeePercentage = 3; // 3% marketplace fee on all txs. _setupRole(AccessControl.DEFAULT_ADMIN_ROLE, owner()); grantRole(TOKEN_MARK_ROLE, owner()); } ///////////////////////////////////////////////////////////////////////// // grantMarketplaceMarkTokenAccess ///////////////////////////////////////////////////////////////////////// /** * @dev Grants a marketplace contract access to marke * @param _account address of the account that can perform the token mark role. */ function grantMarketplaceAccess(address _account) external { require( hasRole(AccessControl.DEFAULT_ADMIN_ROLE, msg.sender), "grantMarketplaceAccess::Must be admin to call method" ); grantRole(TOKEN_MARK_ROLE, _account); } ///////////////////////////////////////////////////////////////////////// // getMarketplaceMaxValue ///////////////////////////////////////////////////////////////////////// /** * @dev Get the max value to be used with the marketplace. * @return uint256 wei value. */ function getMarketplaceMaxValue() external override view returns (uint256) { return maxValue; } ///////////////////////////////////////////////////////////////////////// // setMarketplaceMaxValue ///////////////////////////////////////////////////////////////////////// /** * @dev Set the maximum value of the marketplace settings. * @param _maxValue uint256 maximum wei value. */ function setMarketplaceMaxValue(uint256 _maxValue) external onlyOwner { maxValue = _maxValue; } ///////////////////////////////////////////////////////////////////////// // getMarketplaceMinValue ///////////////////////////////////////////////////////////////////////// /** * @dev Get the max value to be used with the marketplace. * @return uint256 wei value. */ function getMarketplaceMinValue() external override view returns (uint256) { return minValue; } ///////////////////////////////////////////////////////////////////////// // setMarketplaceMinValue ///////////////////////////////////////////////////////////////////////// /** * @dev Set the minimum value of the marketplace settings. * @param _minValue uint256 minimum wei value. */ function setMarketplaceMinValue(uint256 _minValue) external onlyOwner { minValue = _minValue; } ///////////////////////////////////////////////////////////////////////// // getMarketplaceFeePercentage ///////////////////////////////////////////////////////////////////////// /** * @dev Get the marketplace fee percentage. * @return uint8 wei fee. */ function getMarketplaceFeePercentage() external override view returns (uint8) { return marketplaceFeePercentage; } ///////////////////////////////////////////////////////////////////////// // setMarketplaceFeePercentage ///////////////////////////////////////////////////////////////////////// /** * @dev Set the marketplace fee percentage. * Requirements: * - `_percentage` must be <= 100. * @param _percentage uint8 percentage fee. */ function setMarketplaceFeePercentage(uint8 _percentage) external onlyOwner { require( _percentage <= 100, "setMarketplaceFeePercentage::_percentage must be <= 100" ); marketplaceFeePercentage = _percentage; } ///////////////////////////////////////////////////////////////////////// // calculateMarketplaceFee ///////////////////////////////////////////////////////////////////////// /** * @dev Utility function for calculating the marketplace fee for given amount of wei. * @param _amount uint256 wei amount. * @return uint256 wei fee. */ function calculateMarketplaceFee(uint256 _amount) external override view returns (uint256) { return _amount.mul(marketplaceFeePercentage).div(100); } ///////////////////////////////////////////////////////////////////////// // getERC721ContractPrimarySaleFeePercentage ///////////////////////////////////////////////////////////////////////// /** * @dev Get the primary sale fee percentage for a specific ERC721 contract. * @param _contractAddress address ERC721Contract address. * @return uint8 wei primary sale fee. */ function getERC721ContractPrimarySaleFeePercentage(address _contractAddress) external override view returns (uint8) { return primarySaleFees[_contractAddress]; } ///////////////////////////////////////////////////////////////////////// // setERC721ContractPrimarySaleFeePercentage ///////////////////////////////////////////////////////////////////////// /** * @dev Set the primary sale fee percentage for a specific ERC721 contract. * Requirements: * * - `_contractAddress` cannot be the zero address. * - `_percentage` must be <= 100. * @param _contractAddress address ERC721Contract address. * @param _percentage uint8 percentage fee for the ERC721 contract. */ function setERC721ContractPrimarySaleFeePercentage( address _contractAddress, uint8 _percentage ) external onlyOwner { require( _percentage <= 100, "setERC721ContractPrimarySaleFeePercentage::_percentage must be <= 100" ); primarySaleFees[_contractAddress] = _percentage; } ///////////////////////////////////////////////////////////////////////// // calculatePrimarySaleFee ///////////////////////////////////////////////////////////////////////// /** * @dev Utility function for calculating the primary sale fee for given amount of wei * @param _contractAddress address ERC721Contract address. * @param _amount uint256 wei amount. * @return uint256 wei fee. */ function calculatePrimarySaleFee(address _contractAddress, uint256 _amount) external override view returns (uint256) { return _amount.mul(primarySaleFees[_contractAddress]).div(100); } ///////////////////////////////////////////////////////////////////////// // hasERC721TokenSold ///////////////////////////////////////////////////////////////////////// /** * @dev Check whether the ERC721 token has sold at least once. * @param _contractAddress address ERC721Contract address. * @param _tokenId uint256 token ID. * @return bool of whether the token has sold. */ function hasERC721TokenSold(address _contractAddress, uint256 _tokenId) external override view returns (bool) { return soldTokens[_contractAddress][_tokenId]; } ///////////////////////////////////////////////////////////////////////// // markERC721TokenAsSold ///////////////////////////////////////////////////////////////////////// /** * @dev Mark a token as sold. * Requirements: * * - `_contractAddress` cannot be the zero address. * @param _contractAddress address ERC721Contract address. * @param _tokenId uint256 token ID. * @param _hasSold bool of whether the token should be marked sold or not. */ function markERC721Token( address _contractAddress, uint256 _tokenId, bool _hasSold ) external override { require( hasRole(TOKEN_MARK_ROLE, msg.sender), "markERC721Token::Must have TOKEN_MARK_ROLE role to call method" ); soldTokens[_contractAddress][_tokenId] = _hasSold; } ///////////////////////////////////////////////////////////////////////// // markTokensAsSold ///////////////////////////////////////////////////////////////////////// /** * @dev Function to set an array of tokens for a contract as sold, thus not being subject to the primary sale fee, if one exists. * @param _originContract address of ERC721 contract. * @param _tokenIds uint256[] array of token ids. */ function markTokensAsSold( address _originContract, uint256[] calldata _tokenIds ) external { require( hasRole(TOKEN_MARK_ROLE, msg.sender), "markERC721Token::Must have TOKEN_MARK_ROLE role to call method" ); // limit to batches of 2000 require( _tokenIds.length <= 2000, "markTokensAsSold::Attempted to mark more than 2000 tokens as sold" ); // Mark provided tokens as sold. for (uint256 i = 0; i < _tokenIds.length; i++) { soldTokens[_originContract][_tokenIds[i]] = true; } } }
- `_percentage` must be <= 100. _percentage uint8 percentage fee./
function setMarketplaceFeePercentage(uint8 _percentage) external onlyOwner { require( _percentage <= 100, "setMarketplaceFeePercentage::_percentage must be <= 100" ); marketplaceFeePercentage = _percentage; }
2,578,924
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface TradeBotCommanderV2Interface { // events event ADDEDACCOUNT705(address account); //inject NONSTANDARD NAMING event REMOVEDACCOUNT677(address account); //inject NONSTANDARD NAMING event CALL773(address target, uint256 amount, bytes data, bool ok, bytes returnData); //inject NONSTANDARD NAMING // callable by accounts function PROCESSLIMITORDER517( //inject NONSTANDARD NAMING DharmaTradeBotV1Interface.LimitOrderArguments calldata args, DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs ) external returns (bool ok, uint256 amountReceived); function DEPLOYANDPROCESSLIMITORDER155( //inject NONSTANDARD NAMING address initialSigningKey, // the initial key on the keyring address keyRing, DharmaTradeBotV1Interface.LimitOrderArguments calldata args, DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs ) external returns (bool ok, bytes memory returnData); // only callable by owner function ADDACCOUNT504(address account) external; //inject NONSTANDARD NAMING function REMOVEACCOUNT427(address account) external; //inject NONSTANDARD NAMING function CALLANY167( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external returns (bool ok, bytes memory returnData); // view functions function GETACCOUNTS195() external view returns (address[] memory); //inject NONSTANDARD NAMING function GETTRADEBOT843() external view returns (address tradeBot); //inject NONSTANDARD NAMING } interface DharmaTradeBotV1Interface { struct LimitOrderArguments { address account; address assetToSupply; // Ether = address(0) address assetToReceive; // Ether = address(0) uint256 maximumAmountToSupply; uint256 maximumPriceToAccept; // represented as a mantissa (n * 10^18) uint256 expiration; bytes32 salt; } struct LimitOrderExecutionArguments { uint256 amountToSupply; // will be lower than maximum for partial fills bytes signatures; address tradeTarget; bytes tradeData; } function PROCESSLIMITORDER517( //inject NONSTANDARD NAMING LimitOrderArguments calldata args, LimitOrderExecutionArguments calldata executionArgs ) external returns (uint256 amountReceived); } interface DharmaSmartWalletFactoryV1Interface { function NEWSMARTWALLET679( //inject NONSTANDARD NAMING address userSigningKey ) external returns (address wallet); function GETNEXTSMARTWALLET653( //inject NONSTANDARD NAMING address userSigningKey ) external view returns (address wallet); } interface DharmaKeyRingFactoryV2Interface { function NEWKEYRING243( //inject NONSTANDARD NAMING address userSigningKey, address targetKeyRing ) external returns (address keyRing); function GETNEXTKEYRING535( //inject NONSTANDARD NAMING address userSigningKey ) external view returns (address targetKeyRing); } contract TwoStepOwnable { address private _owner; address private _newPotentialOwner; event OWNERSHIPTRANSFERRED599( //inject NONSTANDARD NAMING address indexed previousOwner, address indexed newOwner ); constructor() internal { _owner = tx.origin; emit OWNERSHIPTRANSFERRED599(address(0), _owner); } function OWNER209() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER726() { //inject NONSTANDARD NAMING require(ISOWNER585(), "TwoStepOwnable: caller is not the owner."); _; } function ISOWNER585() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function TRANSFEROWNERSHIP473(address newOwner) public ONLYOWNER726 { //inject NONSTANDARD NAMING require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } function CANCELOWNERSHIPTRANSFER552() public ONLYOWNER726 { //inject NONSTANDARD NAMING delete _newPotentialOwner; } function ACCEPTOWNERSHIP824() public { //inject NONSTANDARD NAMING require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OWNERSHIPTRANSFERRED599(_owner, msg.sender); _owner = msg.sender; } } contract TradeBotCommanderV2 is TradeBotCommanderV2Interface, TwoStepOwnable { // Track all authorized accounts. address[] private _accounts; // Indexes start at 1, as 0 signifies non-inclusion mapping (address => uint256) private _accountIndexes; DharmaTradeBotV1Interface private immutable _TRADE_BOT; DharmaSmartWalletFactoryV1Interface private immutable _WALLET_FACTORY; DharmaKeyRingFactoryV2Interface private immutable _KEYRING_FACTORY; constructor(address walletFactory, address keyRingFactory, address tradeBot, address[] memory initialAccounts) public { require( walletFactory != address(0) && keyRingFactory != address(0) && tradeBot != address(0), "Missing required constructor arguments." ); _WALLET_FACTORY = DharmaSmartWalletFactoryV1Interface(walletFactory); _KEYRING_FACTORY = DharmaKeyRingFactoryV2Interface(keyRingFactory); _TRADE_BOT = DharmaTradeBotV1Interface(tradeBot); for (uint256 i; i < initialAccounts.length; i++) { address account = initialAccounts[i]; _ADDACCOUNT722(account); } } function PROCESSLIMITORDER517( //inject NONSTANDARD NAMING DharmaTradeBotV1Interface.LimitOrderArguments calldata args, DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs ) external override returns (bool ok, uint256 amountReceived) { require( _accountIndexes[msg.sender] != 0, "Only authorized accounts may trigger limit orders." ); amountReceived = _TRADE_BOT.PROCESSLIMITORDER517( args, executionArgs ); ok = true; } // Deploy a key ring and a smart wallet, then process the limit order. function DEPLOYANDPROCESSLIMITORDER155( //inject NONSTANDARD NAMING address initialSigningKey, // the initial key on the keyring address keyRing, DharmaTradeBotV1Interface.LimitOrderArguments calldata args, DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs ) external override returns (bool ok, bytes memory returnData) { require( _accountIndexes[msg.sender] != 0, "Only authorized accounts may trigger limit orders." ); _DEPLOYNEWKEYRINGIFNEEDED997(initialSigningKey, keyRing); _DEPLOYNEWSMARTWALLETIFNEEDED48(keyRing, args.account); try _TRADE_BOT.PROCESSLIMITORDER517(args, executionArgs) returns (uint256 amountReceived) { return (true, abi.encode(amountReceived)); } catch (bytes memory revertData) { return (false, revertData); } } function ADDACCOUNT504(address account) external override ONLYOWNER726 { //inject NONSTANDARD NAMING _ADDACCOUNT722(account); } function REMOVEACCOUNT427(address account) external override ONLYOWNER726 { //inject NONSTANDARD NAMING _REMOVEACCOUNT899(account); } function CALLANY167( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external override ONLYOWNER726 returns (bool ok, bytes memory returnData) { // Call the specified target and supply the specified amount and data. (ok, returnData) = target.call{value: amount}(data); emit CALL773(target, amount, data, ok, returnData); } function GETACCOUNTS195() external view override returns (address[] memory) { //inject NONSTANDARD NAMING return _accounts; } function GETTRADEBOT843() external view override returns (address tradeBot) { //inject NONSTANDARD NAMING return address(_TRADE_BOT); } function _DEPLOYNEWKEYRINGIFNEEDED997( //inject NONSTANDARD NAMING address initialSigningKey, address expectedKeyRing ) internal returns (address keyRing) { // Only deploy if a contract doesn't already exist at expected address. bytes32 size; assembly { size := extcodesize(expectedKeyRing) } if (size == 0) { require( _KEYRING_FACTORY.GETNEXTKEYRING535(initialSigningKey) == expectedKeyRing, "Key ring to be deployed does not match expected key ring." ); keyRing = _KEYRING_FACTORY.NEWKEYRING243(initialSigningKey, expectedKeyRing); } else { // Note: the key ring at the expected address may have been modified so that // the supplied user signing key is no longer a valid key - therefore, treat // this helper as a way to protect against race conditions, not as a primary // mechanism for interacting with key ring contracts. keyRing = expectedKeyRing; } } function _DEPLOYNEWSMARTWALLETIFNEEDED48( //inject NONSTANDARD NAMING address userSigningKey, // the key ring address expectedSmartWallet ) internal returns (address smartWallet) { // Only deploy if a contract doesn't already exist at expected address. bytes32 size; assembly { size := extcodesize(expectedSmartWallet) } if (size == 0) { require( _WALLET_FACTORY.GETNEXTSMARTWALLET653(userSigningKey) == expectedSmartWallet, "Smart wallet to be deployed does not match expected smart wallet." ); smartWallet = _WALLET_FACTORY.NEWSMARTWALLET679(userSigningKey); } else { // Note: the smart wallet at the expected address may have been modified // so that the supplied user signing key is no longer a valid key. // Therefore, treat this helper as a way to protect against race // conditions, not as a primary mechanism for interacting with smart // wallet contracts. smartWallet = expectedSmartWallet; } } function _ADDACCOUNT722(address account) internal { //inject NONSTANDARD NAMING require( _accountIndexes[account] == 0, "Account matching the provided account already exists." ); _accounts.push(account); _accountIndexes[account] = _accounts.length; emit ADDEDACCOUNT705(account); } function _REMOVEACCOUNT899(address account) internal { //inject NONSTANDARD NAMING uint256 removedAccountIndex = _accountIndexes[account]; require( removedAccountIndex != 0, "No account found matching the provided account." ); // swap account to remove with the last one then pop from the array. address lastAccount = _accounts[_accounts.length - 1]; _accounts[removedAccountIndex - 1] = lastAccount; _accountIndexes[lastAccount] = removedAccountIndex; _accounts.pop(); delete _accountIndexes[account]; emit REMOVEDACCOUNT677(account); } }
inject NONSTANDARD NAMING
function REMOVEACCOUNT427(address account) external override ONLYOWNER726 {
12,831,818
./partial_match/40/0xF5282616a1F9CffFE24122a1A76B0bf2ce087357/sources/contracts/WagPool.sol
Set DURATION_FACTOR_OVERDUE Only callable by the contract admin./
function setDurationFactorOverdue(uint256 _durationFactorOverdue) external onlyAdmin { require( _durationFactorOverdue > 0, "DURATION_FACTOR_OVERDUE cannot be zero" ); DURATION_FACTOR_OVERDUE = _durationFactorOverdue; emit NewDurationFactorOverdue(_durationFactorOverdue); }
8,827,096
./full_match/1/0xe3aF60f1F08e489503d9827210c73E468400c7ec/sources/browser/Untitled.sol
mints a new ERC1155 token the tokens are minted in per-interval batches, this is to allow profit share calculations receiver - the address that will control the minted token(s).
function mint(address receiver) external payable { require(msg.sender == minterAddress); require(msg.value > 0); if (now >= currentIntervalSec + 7 days && (415*supplyPerInterval[currentIntervalNo] >= supplyPerInterval[currentIntervalNo-1])){ currentIntervalNo++; currentIntervalSec = currentIntervalSec + 7 days; supplyPerInterval[currentIntervalNo] = 0; } supplyPerInterval[currentIntervalNo] += msg.value; _mint(receiver,currentIntervalNo,msg.value,''); }
9,724,295
/** *Submitted for verification at Etherscan.io on 2021-05-05 */ /* .'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''.. .;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,. ';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,. ';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,. ...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''.. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. ..... .;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,. .,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,. .,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,.. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. .... ..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. ..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'. ...'.. .';;;;;;;;;;;;;;,,,'. ............... */ // https://github.com/trusttoken/smart-contracts // 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; } } /** * @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; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @title UpgradeableClaimable * @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. Since * this contract combines Claimable and UpgradableOwnable contracts, ownership * can be later change via 2 step method {transferOwnership} and {claimOwnership} * * 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 UpgradeableClaimable is Initializable, Context { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting a custom initial owner of choice. * @param __owner Initial owner of contract to be set. */ function initialize(address __owner) internal initializer { _owner = __owner; emit OwnershipTransferred(address(0), __owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view returns (address) { return _pendingOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner, "Ownable: caller is not the pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; _pendingOwner = address(0); } } /** * @title ImplementationReference * @dev This contract is made to serve a simple purpose only. * To hold the address of the implementation contract to be used by proxy. * The implementation address, is changeable anytime by the owner of this contract. */ contract ImplementationReference is UpgradeableClaimable { address public implementation; /** * @dev Event to show that implementation address has been changed * @param newImplementation New address of the implementation */ event ImplementationChanged(address newImplementation); /** * @dev Set initial ownership and implementation address * @param _implementation Initial address of the implementation */ constructor(address _implementation) public { UpgradeableClaimable.initialize(msg.sender); implementation = _implementation; } /** * @dev Function to change the implementation address, which can be called only by the owner * @param newImplementation New address of the implementation */ function setImplementation(address newImplementation) external onlyOwner { implementation = newImplementation; emit ImplementationChanged(newImplementation); } } /** * @title OwnedProxyWithReference * @dev This contract combines an upgradeability proxy with basic authorization control functionalities * Its structure makes it easy for a group of contracts alike, to share an implementation and to change it easily for all of them at once */ contract OwnedProxyWithReference { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Event to show ownership transfer is pending * @param currentOwner representing the address of the current owner * @param pendingOwner representing the address of the pending owner */ event NewPendingOwner(address currentOwner, address pendingOwner); /** * @dev Event to show implementation reference has been changed * @param implementationReference address of the new implementation reference contract */ event ImplementationReferenceChanged(address implementationReference); // Storage position of the owner and pendingOwner and implementationReference of the contract // This is made to ensure, that memory spaces do not interfere with each other bytes32 private constant proxyOwnerPosition = 0x6279e8199720cf3557ecd8b58d667c8edc486bd1cf3ad59ea9ebdfcae0d0dfac; //keccak256("trueUSD.proxy.owner"); bytes32 private constant pendingProxyOwnerPosition = 0x8ddbac328deee8d986ec3a7b933a196f96986cb4ee030d86cc56431c728b83f4; //keccak256("trueUSD.pending.proxy.owner"); bytes32 private constant implementationReferencePosition = keccak256("trueFiPool.implementation.reference"); //keccak256("trueFiPool.implementation.reference"); /** * @dev the constructor sets the original owner of the contract to the sender account. * @param _owner Initial owner of the proxy * @param _implementationReference initial ImplementationReference address */ constructor(address _owner, address _implementationReference) public { _setUpgradeabilityOwner(_owner); _changeImplementationReference(_implementationReference); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner(), "only Proxy Owner"); _; } /** * @dev Throws if called by any account other than the pending owner. */ modifier onlyPendingProxyOwner() { require(msg.sender == pendingProxyOwner(), "only pending Proxy Owner"); _; } /** * @dev Tells the address of the owner * @return owner the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = proxyOwnerPosition; assembly { owner := sload(position) } } /** * @dev Tells the address of the owner * @return pendingOwner the address of the pending owner */ function pendingProxyOwner() public view returns (address pendingOwner) { bytes32 position = pendingProxyOwnerPosition; assembly { pendingOwner := sload(position) } } /** * @dev Sets the address of the owner * @param newProxyOwner New owner to be set */ function _setUpgradeabilityOwner(address newProxyOwner) internal { bytes32 position = proxyOwnerPosition; assembly { sstore(position, newProxyOwner) } } /** * @dev Sets the address of the owner * @param newPendingProxyOwner New pending owner address */ function _setPendingUpgradeabilityOwner(address newPendingProxyOwner) internal { bytes32 position = pendingProxyOwnerPosition; assembly { sstore(position, newPendingProxyOwner) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * changes the pending owner to newOwner. But doesn't actually transfer * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) external onlyProxyOwner { require(newOwner != address(0)); _setPendingUpgradeabilityOwner(newOwner); emit NewPendingOwner(proxyOwner(), newOwner); } /** * @dev Allows the pendingOwner to claim ownership of the proxy */ function claimProxyOwnership() external onlyPendingProxyOwner { emit ProxyOwnershipTransferred(proxyOwner(), pendingProxyOwner()); _setUpgradeabilityOwner(pendingProxyOwner()); _setPendingUpgradeabilityOwner(address(0)); } /** * @dev Allows the proxy owner to change the contract holding address of implementation. * @param _implementationReference representing the address contract, which holds implementation. */ function changeImplementationReference(address _implementationReference) public virtual onlyProxyOwner { _changeImplementationReference(_implementationReference); } /** * @dev Get the address of current implementation. * @return Returns address of implementation contract */ function implementation() public view returns (address) { bytes32 position = implementationReferencePosition; address implementationReference; assembly { implementationReference := sload(position) } return ImplementationReference(implementationReference).implementation(); } /** * @dev Fallback functions allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ fallback() external payable { proxyCall(); } /** * @dev This fallback function gets called only when this contract is called without any calldata e.g. send(), transfer() * This would also trigger receive() function on called implementation */ receive() external payable { proxyCall(); } /** * @dev Performs a low level call, to the contract holding all the logic, changing state on this contract at the same time */ function proxyCall() internal { address impl = implementation(); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), impl, ptr, calldatasize(), 0, 0) returndatacopy(ptr, 0, returndatasize()) switch result case 0 { revert(ptr, returndatasize()) } default { return(ptr, returndatasize()) } } } /** * @dev Function to internally change the contract holding address of implementation. * @param _implementationReference representing the address contract, which holds implementation. */ function _changeImplementationReference(address _implementationReference) internal virtual { bytes32 position = implementationReferencePosition; assembly { sstore(position, _implementationReference) } emit ImplementationReferenceChanged(address(_implementationReference)); } }
Function to change the implementation address, which can be called only by the owner newImplementation New address of the implementation/
function setImplementation(address newImplementation) external onlyOwner { implementation = newImplementation; emit ImplementationChanged(newImplementation); }
21,589
./full_match/1/0xd2E73E3254B1f9A1215cB1F1aE73b9B079B5E697/sources/contracts/Helpers/Signers.sol
Verifies that a message is signed by a quorum among the signers The sigs must be sorted by signer addresses in ascending order. _msg signed message _sigs list of signatures sorted by signer addresses _signers sorted list of current signers _powers powers of current signers/ require(ssHash == h, "Mismatch current signers");
function verifySigs(bytes memory _msg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers) public view override { bytes32 h = keccak256(abi.encodePacked(_signers, _powers)); _verifySignedPowers(keccak256(_msg).toEthSignedMessageHash(), _sigs, _signers, _powers); }
3,122,769
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev 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]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) 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 { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './IERC165.sol'; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { MD1Types } from '../lib/MD1Types.sol'; /** * @title MD1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract MD1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Configuration ============ /// @dev The oracle which provides Merkle root updates. IRewardsOracle internal _REWARDS_ORACLE_; /// @dev The IPNS name to which trader and market maker exchange statistics are published. string internal _IPNS_NAME_; /// @dev Period of time after the epoch end after which the new epoch exchange statistics should /// be available on IPFS via the IPNS name. This can be used as a trigger for “keepers” who are /// incentivized to call the proposeRoot() and updateRoot() functions as needed. uint256 internal _IPFS_UPDATE_PERIOD_; /// @dev Max rewards distributed per epoch as market maker incentives. uint256 internal _MARKET_MAKER_REWARDS_AMOUNT_; /// @dev Max rewards distributed per epoch as trader incentives. uint256 internal _TRADER_REWARDS_AMOUNT_; /// @dev Parameter affecting the calculation of trader rewards. This is a value /// between 0 and 1, represented here in units out of 10^18. uint256 internal _TRADER_SCORE_ALPHA_; // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. MD1Types.EpochParameters internal _EPOCH_PARAMETERS_; // ============ Root Updates ============ /// @dev The active Merkle root and associated parameters. MD1Types.MerkleRoot internal _ACTIVE_ROOT_; /// @dev The proposed Merkle root and associated parameters. MD1Types.MerkleRoot internal _PROPOSED_ROOT_; /// @dev The time at which the proposed root may become active. uint256 internal _WAITING_PERIOD_END_; /// @dev Whether root updates are currently paused. bool internal _ARE_ROOT_UPDATES_PAUSED_; // ============ Claims ============ /// @dev Mapping of (user address) => (number of tokens claimed). mapping(address => uint256) internal _CLAIMED_; /// @dev Whether the user has opted into allowing anyone to trigger a claim on their behalf. mapping(address => bool) internal _ALWAYS_ALLOW_CLAIMS_FOR_; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; interface IRewardsOracle { /** * @notice Returns the oracle value, agreed upon by all oracle signers. If the signers have not * agreed upon a value, should return zero for all return values. * * @return merkleRoot The Merkle root for the next Merkle distributor update. * @return epoch The epoch number corresponding to the new Merkle root. * @return ipfsCid An IPFS CID pointing to the Merkle tree data. */ function read() external virtual view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @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. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library MD1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev The parameters related to a certain version of the Merkle root. */ struct MerkleRoot { bytes32 merkleRoot; uint256 epoch; bytes ipfsCid; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { MD1Storage } from './MD1Storage.sol'; /** * @title MD1Getters * @author dYdX * * @notice Simple getter functions. */ abstract contract MD1Getters is MD1Storage { /** * @notice Get the address of the oracle which provides Merkle root updates. * * @return The address of the oracle. */ function getRewardsOracle() external view returns (IRewardsOracle) { return _REWARDS_ORACLE_; } /** * @notice Get the IPNS name to which trader and market maker exchange statistics are published. * * @return The IPNS name. */ function getIpnsName() external view returns (string memory) { return _IPNS_NAME_; } /** * @notice Get the period of time after the epoch end after which the new epoch exchange * statistics should be available on IPFS via the IPNS name. * * @return The IPFS update period, in seconds. */ function getIpfsUpdatePeriod() external view returns (uint256) { return _IPFS_UPDATE_PERIOD_; } /** * @notice Get the rewards formula parameters. * * @return Max rewards distributed per epoch as market maker incentives. * @return Max rewards distributed per epoch as trader incentives. * @return The alpha parameter between 0 and 1, in units out of 10^18. */ function getRewardsParameters() external view returns (uint256, uint256, uint256) { return ( _MARKET_MAKER_REWARDS_AMOUNT_, _TRADER_REWARDS_AMOUNT_, _TRADER_SCORE_ALPHA_ ); } /** * @notice Get the parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (MD1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice Get the active Merkle root and associated parameters. * * @return merkleRoot The active Merkle root. * @return epoch The epoch number corresponding to this Merkle tree. * @return ipfsCid An IPFS CID pointing to the Merkle tree data. */ function getActiveRoot() external view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid) { merkleRoot = _ACTIVE_ROOT_.merkleRoot; epoch = _ACTIVE_ROOT_.epoch; ipfsCid = _ACTIVE_ROOT_.ipfsCid; } /** * @notice Get the proposed Merkle root and associated parameters. * * @return merkleRoot The active Merkle root. * @return epoch The epoch number corresponding to this Merkle tree. * @return ipfsCid An IPFS CID pointing to the Merkle tree data. */ function getProposedRoot() external view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid) { merkleRoot = _PROPOSED_ROOT_.merkleRoot; epoch = _PROPOSED_ROOT_.epoch; ipfsCid = _PROPOSED_ROOT_.ipfsCid; } /** * @notice Get the time at which the proposed root may become active. * * @return The time at which the proposed root may become active, in epoch seconds. */ function getWaitingPeriodEnd() external view returns (uint256) { return _WAITING_PERIOD_END_; } /** * @notice Check whether root updates are currently paused. * * @return Boolean `true` if root updates are currently paused, otherwise, `false`. */ function getAreRootUpdatesPaused() external view returns (bool) { return _ARE_ROOT_UPDATES_PAUSED_; } /** * @notice Get the tokens claimed so far by a given user. * * @param user The address of the user. * * @return The tokens claimed so far by that user. */ function getClaimed(address user) external view returns (uint256) { return _CLAIMED_[user]; } /** * @notice Check whether the user opted into allowing anyone to trigger a claim on their behalf. * * @param user The address of the user. * * @return Boolean `true` if any address may trigger claims for the user, otherwise `false`. */ function getAlwaysAllowClaimsFor(address user) external view returns (bool) { return _ALWAYS_ALLOW_CLAIMS_FOR_[user]; } } // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from '../../dependencies/open-zeppelin/SafeMath.sol'; import { Ownable } from '../../dependencies/open-zeppelin/Ownable.sol'; import { MerkleProof } from '../../dependencies/open-zeppelin/MerkleProof.sol'; import { IERC20 } from '../../interfaces/IERC20.sol'; import { IRewardsOracle } from '../../interfaces/IRewardsOracle.sol'; import { MD1Claims } from './impl/MD1Claims.sol'; import { MD1RootUpdates } from './impl/MD1RootUpdates.sol'; import { MD1Configuration } from './impl/MD1Configuration.sol'; import { MD1Getters } from './impl/MD1Getters.sol'; /** * @title MerkleDistributorV1 * @author dYdX * * @notice Distributes DYDX token rewards according to a Merkle tree of balances. The tree can be * updated periodially with each user's cumulative rewards balance, allowing new rewards to be * distributed to users over time. * * An update is performed by setting the proposed Merkle root to the latest value returned by * the oracle contract. The proposed Merkle root can be made active after a waiting period has * elapsed. During the waiting period, dYdX governance has the opportunity to freeze the Merkle * root, in case the proposed root is incorrect or malicious. */ contract MerkleDistributorV1 is MD1RootUpdates, MD1Claims, MD1Configuration, MD1Getters { // ============ Constructor ============ constructor( address rewardsToken, address rewardsTreasury ) MD1Claims(rewardsToken, rewardsTreasury) {} // ============ External Functions ============ function initialize( address rewardsOracle, string calldata ipnsName, uint256 ipfsUpdatePeriod, uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha, uint256 epochInterval, uint256 epochOffset ) external initializer { __MD1Roles_init(); __MD1Configuration_init( rewardsOracle, ipnsName, ipfsUpdatePeriod, marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha ); __MD1EpochSchedule_init(epochInterval, epochOffset); } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. Used by VersionedInitializable. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 1; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { 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.7.5; /** * @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) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { MerkleProof } from '../../../dependencies/open-zeppelin/MerkleProof.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { MD1Roles } from './MD1Roles.sol'; /** * @title MD1Claims * @author dYdX * * @notice Allows rewards to be claimed by providing a Merkle proof of the rewards amount. */ abstract contract MD1Claims is MD1Roles { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The token distributed as rewards. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; // ============ Events ============ /// @notice Emitted when a user claims rewards. event RewardsClaimed( address account, uint256 amount ); /// @notice Emitted when a user opts into or out of the claim-for allowlist. event AlwaysAllowClaimForUpdated( address user, bool allow ); // ============ Constructor ============ constructor( address rewardsToken, address rewardsTreasury ) { REWARDS_TOKEN = IERC20(rewardsToken); REWARDS_TREASURY = rewardsTreasury; } // ============ External Functions ============ /** * @notice Claim the remaining unclaimed rewards for the sender. * * Reverts if the provided Merkle proof is invalid. * * @param cumulativeAmount The total all-time rewards this user has earned. * @param merkleProof The Merkle proof for the user and cumulative amount. * * @return The number of rewards tokens claimed. */ function claimRewards( uint256 cumulativeAmount, bytes32[] calldata merkleProof ) external nonReentrant returns (uint256) { return _claimRewards(msg.sender, cumulativeAmount, merkleProof); } /** * @notice Claim the remaining unclaimed rewards for a user, and send them to that user. * * The caller must be authorized with CLAIM_OPERATOR_ROLE unless the specified user has opted * into the claim-for allowlist. In any case, rewards are transfered to the original user * specified in the Merkle tree. * * Reverts if the provided Merkle proof is invalid. * * @param user Address of the user on whose behalf to trigger a claim. * @param cumulativeAmount The total all-time rewards this user has earned. * @param merkleProof The Merkle proof for the user and cumulative amount. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address user, uint256 cumulativeAmount, bytes32[] calldata merkleProof ) external nonReentrant returns (uint256) { require( ( hasRole(CLAIM_OPERATOR_ROLE, msg.sender) || _ALWAYS_ALLOW_CLAIMS_FOR_[user] ), 'MD1Claims: Do not have permission to claim for this user' ); return _claimRewards(user, cumulativeAmount, merkleProof); } /** * @notice Opt into allowing anyone to claim on the sender's behalf. * * Note that this does not affect who receives the funds. The user specified in the Merkle tree * receives those rewards regardless of who issues the claim. * * Note that addresses with the CLAIM_OPERATOR_ROLE ignore this allowlist when triggering claims. * * @param allow Whether or not to allow claims on the sender's behalf. */ function setAlwaysAllowClaimsFor( bool allow ) external nonReentrant { _ALWAYS_ALLOW_CLAIMS_FOR_[msg.sender] = allow; emit AlwaysAllowClaimForUpdated(msg.sender, allow); } // ============ Internal Functions ============ /** * @notice Claim the remaining unclaimed rewards for a user, and send them to that user. * * Reverts if the provided Merkle proof is invalid. * * @param user Address of the user. * @param cumulativeAmount The total all-time rewards this user has earned. * @param merkleProof The Merkle proof for the user and cumulative amount. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, uint256 cumulativeAmount, bytes32[] calldata merkleProof ) internal returns (uint256) { // Get the active Merkle root. bytes32 merkleRoot = _ACTIVE_ROOT_.merkleRoot; // Verify the Merkle proof. bytes32 node = keccak256(abi.encodePacked(user, cumulativeAmount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MD1Claims: Invalid Merkle proof'); // Get the claimable amount. // // Note: If this reverts, then there was an error in the Merkle tree, since the cumulative // amount for a given user should never decrease over time. uint256 claimable = cumulativeAmount.sub(_CLAIMED_[user]); if (claimable == 0) { return 0; } // Mark the user as having claimed the full amount. _CLAIMED_[user] = cumulativeAmount; // Send the user the claimable amount. REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, user, claimable); emit RewardsClaimed(user, claimable); return claimable; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { MerkleProof } from '../../../dependencies/open-zeppelin/MerkleProof.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { MD1Pausable } from './MD1Pausable.sol'; /** * @title MD1RootUpdates * @author dYdX * * @notice Handles updates to the Merkle root. */ abstract contract MD1RootUpdates is MD1Pausable { using SafeMath for uint256; // ============ Constants ============ /// @notice The waiting period before a proposed Merkle root can become active, in seconds. uint256 public constant WAITING_PERIOD = 7 days; // ============ Events ============ /// @notice Emitted when a new Merkle root is proposed and the waiting period begins. event RootProposed( bytes32 merkleRoot, uint256 epoch, bytes ipfsCid, uint256 waitingPeriodEnd ); /// @notice Emitted when a new Merkle root becomes active. event RootUpdated( bytes32 merkleRoot, uint256 epoch, bytes ipfsCid ); // ============ External Functions ============ /** * @notice Set the proposed root parameters to the values returned by the oracle, and start the * waiting period. Anyone may call this function. * * Reverts if the oracle root is bytes32(0). * Reverts if the oracle root parameters are equal to the proposed root parameters. * Reverts if the oracle root epoch is not equal to the next root epoch. */ function proposeRoot() external nonReentrant { // Read the latest values from the oracle. ( bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid ) = _REWARDS_ORACLE_.read(); require(merkleRoot != bytes32(0), 'MD1RootUpdates: Oracle root is zero (unset)'); require( ( merkleRoot != _PROPOSED_ROOT_.merkleRoot || epoch != _PROPOSED_ROOT_.epoch || keccak256(ipfsCid) != keccak256(_PROPOSED_ROOT_.ipfsCid) ), 'MD1RootUpdates: Oracle root was already proposed' ); require(epoch == getNextRootEpoch(), 'MD1RootUpdates: Oracle epoch is not next root epoch'); // Set the proposed root and the waiting period for the proposed root to become active. _PROPOSED_ROOT_ = MD1Types.MerkleRoot({ merkleRoot: merkleRoot, epoch: epoch, ipfsCid: ipfsCid }); uint256 waitingPeriodEnd = block.timestamp.add(WAITING_PERIOD); _WAITING_PERIOD_END_ = waitingPeriodEnd; emit RootProposed(merkleRoot, epoch, ipfsCid, waitingPeriodEnd); } /** * @notice Set the active root parameters to the proposed root parameters. * * Reverts if root updates are paused. * Reverts if the proposed root is bytes32(0). * Reverts if the proposed root epoch is not equal to the next root epoch. * Reverts if the waiting period for the proposed root has not elapsed. */ function updateRoot() external nonReentrant whenNotPaused { // Get the proposed root parameters. bytes32 merkleRoot = _PROPOSED_ROOT_.merkleRoot; uint256 epoch = _PROPOSED_ROOT_.epoch; bytes memory ipfsCid = _PROPOSED_ROOT_.ipfsCid; require(merkleRoot != bytes32(0), 'MD1RootUpdates: Proposed root is zero (unset)'); require(epoch == getNextRootEpoch(), 'MD1RootUpdates: Proposed epoch is not next root epoch'); require( block.timestamp >= _WAITING_PERIOD_END_, 'MD1RootUpdates: Waiting period has not elapsed' ); // Set the active root. _ACTIVE_ROOT_.merkleRoot = merkleRoot; _ACTIVE_ROOT_.epoch = epoch; _ACTIVE_ROOT_.ipfsCid = ipfsCid; emit RootUpdated(merkleRoot, epoch, ipfsCid); } /** * @notice Returns true if there is a proposed root waiting to become active, the waiting period * for that root has elapsed, and root updates are not paused. * * @return Boolean `true` if the active root can be updated to the proposed root, else `false`. */ function canUpdateRoot() external view returns (bool) { return ( hasPendingRoot() && block.timestamp >= _WAITING_PERIOD_END_ && !_ARE_ROOT_UPDATES_PAUSED_ ); } // ============ Public Functions ============ /** * @notice Returns true if there is a proposed root waiting to become active. This is the case if * and only if the proposed root is not zero and the proposed root epoch is equal to the next * root epoch. */ function hasPendingRoot() public view returns (bool) { // Get the proposed parameters. bytes32 merkleRoot = _PROPOSED_ROOT_.merkleRoot; uint256 epoch = _PROPOSED_ROOT_.epoch; if (merkleRoot == bytes32(0)) { return false; } return epoch == getNextRootEpoch(); } /** * @notice Get the next root epoch. If the active root is zero, then the next root epoch is zero, * otherwise, it is equal to the active root epoch plus one. */ function getNextRootEpoch() public view returns (uint256) { bytes32 merkleRoot = _ACTIVE_ROOT_.merkleRoot; if (merkleRoot == bytes32(0)) { return 0; } return _ACTIVE_ROOT_.epoch.add(1); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol'; import { MD1EpochSchedule } from './MD1EpochSchedule.sol'; import { MD1Roles } from './MD1Roles.sol'; import { MD1Types } from '../lib/MD1Types.sol'; /** * @title MD1Configuration * @author dYdX * * @notice Functions for modifying the Merkle distributor rewards configuration. * * The more sensitive configuration values, which potentially give full control over the contents * of the Merkle tree, may only be updated by the OWNER_ROLE. Other values may be configured by * the CONFIG_UPDATER_ROLE. * * Note that these configuration values are made available externally but are not used internally * within this contract, with the exception of the IPFS update period which is used by * the getIpfsEpoch() function. */ abstract contract MD1Configuration is MD1EpochSchedule, MD1Roles { // ============ Constants ============ uint256 public constant TRADER_SCORE_ALPHA_BASE = 10 ** 18; // ============ Events ============ event RewardsOracleChanged( address rewardsOracle ); event IpnsNameUpdated( string ipnsName ); event IpfsUpdatePeriodUpdated( uint256 ipfsUpdatePeriod ); event RewardsParametersUpdated( uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ); // ============ Initializer ============ function __MD1Configuration_init( address rewardsOracle, string calldata ipnsName, uint256 ipfsUpdatePeriod, uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ) internal { _setRewardsOracle(rewardsOracle); _setIpnsName(ipnsName); _setIpfsUpdatePeriod(ipfsUpdatePeriod); _setRewardsParameters( marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha ); } // ============ External Functions ============ /** * @notice Set the address of the oracle which provides Merkle root updates. * * @param rewardsOracle The new oracle address. */ function setRewardsOracle( address rewardsOracle ) external onlyRole(OWNER_ROLE) nonReentrant { _setRewardsOracle(rewardsOracle); } /** * @notice Set the IPNS name to which trader and market maker exchange statistics are published. * * @param ipnsName The new IPNS name. */ function setIpnsName( string calldata ipnsName ) external onlyRole(OWNER_ROLE) nonReentrant { _setIpnsName(ipnsName); } /** * @notice Set the period of time after the epoch end after which the new epoch exchange * statistics should be available on IPFS via the IPNS name. * * This can be used as a trigger for “keepers” who are incentivized to call the proposeRoot() * and updateRoot() functions as needed. * * @param ipfsUpdatePeriod The new IPFS update period, in seconds. */ function setIpfsUpdatePeriod( uint256 ipfsUpdatePeriod ) external onlyRole(CONFIG_UPDATER_ROLE) nonReentrant { _setIpfsUpdatePeriod(ipfsUpdatePeriod); } /** * @notice Set the rewards formula parameters. * * @param marketMakerRewardsAmount Max rewards distributed per epoch as market maker incentives. * @param traderRewardsAmount Max rewards distributed per epoch as trader incentives. * @param traderScoreAlpha The alpha parameter between 0 and 1, in units out of 10^18. */ function setRewardsParameters( uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ) external onlyRole(CONFIG_UPDATER_ROLE) nonReentrant { _setRewardsParameters(marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha); } /** * @notice Set the parameters defining the function from timestamp to epoch number. * * @param interval The length of an epoch, in seconds. * @param offset The start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(CONFIG_UPDATER_ROLE) nonReentrant { _setEpochParameters(interval, offset); } // ============ Internal Functions ============ function _setRewardsOracle( address rewardsOracle ) internal { _REWARDS_ORACLE_ = IRewardsOracle(rewardsOracle); emit RewardsOracleChanged(rewardsOracle); } function _setIpnsName( string calldata ipnsName ) internal { _IPNS_NAME_ = ipnsName; emit IpnsNameUpdated(ipnsName); } function _setIpfsUpdatePeriod( uint256 ipfsUpdatePeriod ) internal { _IPFS_UPDATE_PERIOD_ = ipfsUpdatePeriod; emit IpfsUpdatePeriodUpdated(ipfsUpdatePeriod); } function _setRewardsParameters( uint256 marketMakerRewardsAmount, uint256 traderRewardsAmount, uint256 traderScoreAlpha ) internal { require( traderScoreAlpha <= TRADER_SCORE_ALPHA_BASE, 'MD1Configuration: Invalid traderScoreAlpha' ); _MARKET_MAKER_REWARDS_AMOUNT_ = marketMakerRewardsAmount; _TRADER_REWARDS_AMOUNT_ = traderRewardsAmount; _TRADER_SCORE_ALPHA_ = traderScoreAlpha; emit RewardsParametersUpdated( marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { MD1Storage } from './MD1Storage.sol'; /** * @title MD1Roles * @author dYdX * * @notice Defines roles used in the MerkleDistributorV1 contract. The hierarchy of roles and * powers of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove addresses from any of the below roles it manages. * | -> May update the rewards oracle address. * | -> May update the IPNS name. * | * +-- CONFIG_UPDATER_ROLE * | -> May update parameters affecting the formulae used to calculate rewards. * | -> May update the epoch schedule. * | -> May update the IPFS update period. * | * +-- PAUSER_ROLE * | -> May pause updates to the Merkle root. * | * +-- UNPAUSER_ROLE * | -> May unpause updates to the Merkle root. * | * +-- CLAIM_OPERATOR_ROLE * -> May trigger a claim on behalf of a user (but the recipient is always the user). */ abstract contract MD1Roles is MD1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant CONFIG_UPDATER_ROLE = keccak256('CONFIG_UPDATER_ROLE'); bytes32 public constant PAUSER_ROLE = keccak256('PAUSER_ROLE'); bytes32 public constant UNPAUSER_ROLE = keccak256('UNPAUSER_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); function __MD1Roles_init() internal { // Assign the OWNER_ROLE to the sender. _setupRole(OWNER_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(CONFIG_UPDATER_ROLE, OWNER_ROLE); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(UNPAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { MD1Roles } from './MD1Roles.sol'; /** * @title MD1Pausable * @author dYdX * * @notice Allows authorized addresses to pause updates to the Merkle root. * * For the Merkle root to be updated, the root must first be set on the oracle contract, then * proposed on this contract, at which point the waiting period begins. During the waiting period, * the root should be verified, and updates should be paused by the PAUSER_ROLE if the root is * found to be incorrect. */ abstract contract MD1Pausable is MD1Roles { // ============ Events ============ /// @notice Emitted when root updates are paused. event RootUpdatesPaused(); /// @notice Emitted when root updates are unpaused. event RootUpdatesUnpaused(); // ============ Modifiers ============ /** * @dev Enforce that a function may be called only while root updates are not paused. */ modifier whenNotPaused() { require(!_ARE_ROOT_UPDATES_PAUSED_, 'MD1Pausable: Updates paused'); _; } /** * @dev Enforce that a function may be called only while root updates are paused. */ modifier whenPaused() { require(_ARE_ROOT_UPDATES_PAUSED_, 'MD1Pausable: Updates not paused'); _; } // ============ External Functions ============ /** * @dev Called by PAUSER_ROLE to prevent proposed Merkle roots from becoming active. */ function pauseRootUpdates() onlyRole(PAUSER_ROLE) whenNotPaused nonReentrant external { _ARE_ROOT_UPDATES_PAUSED_ = true; emit RootUpdatesPaused(); } /** * @dev Called by UNPAUSER_ROLE to resume allowing proposed Merkle roots to become active. */ function unpauseRootUpdates() onlyRole(UNPAUSER_ROLE) whenPaused nonReentrant external { _ARE_ROOT_UPDATES_PAUSED_ = false; emit RootUpdatesUnpaused(); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { MD1Types } from '../lib/MD1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { MD1Storage } from './MD1Storage.sol'; /** * @title MD1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * Note that the current and IPFS epoch numbers are made available externally but are not used * internally within this contract. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) */ abstract contract MD1EpochSchedule is MD1Storage { using SafeCast for uint256; using SafeMath for uint256; // ============ Events ============ event EpochScheduleUpdated( MD1Types.EpochParameters epochParameters ); // ============ Initializer ============ function __MD1EpochSchedule_init( uint256 interval, uint256 offset ) internal { _setEpochParameters(interval, offset); } // ============ External Functions ============ /** * @notice Get the epoch at the current block timestamp. * * Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() external view returns (uint256) { return _getEpochAtTimestamp( block.timestamp, 'MD1EpochSchedule: Epoch zero has not started' ); } /** * @notice Get the latest epoch number for which we expect to have data available on IPFS. * This is equal to the current epoch number, delayed by the IPFS update period. * * Reverts if epoch zero did not begin at least `_IPFS_UPDATE_PERIOD_` seconds ago. * * @return The latest epoch number for which we expect to have data available on IPFS. */ function getIpfsEpoch() external view returns (uint256) { return _getEpochAtTimestamp( block.timestamp.sub(_IPFS_UPDATE_PERIOD_), 'MD1EpochSchedule: IPFS epoch zero has not started' ); } // ============ Internal Functions ============ function _getEpochAtTimestamp( uint256 timestamp, string memory revertReason ) internal view returns (uint256) { MD1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require(timestamp >= offset, revertReason); return timestamp.sub(offset).div(interval); } function _setEpochParameters( uint256 interval, uint256 offset ) internal { require(interval != 0, 'MD1EpochSchedule: Interval cannot be zero'); MD1Types.EpochParameters memory epochParameters = MD1Types.EpochParameters({ interval: interval.toUint128(), offset: offset.toUint128() }); _EPOCH_PARAMETERS_ = epochParameters; emit EpochScheduleUpdated(epochParameters); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; /** * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128(uint256 a) internal pure returns (uint128) { uint128 b = uint128(a); require(uint256(b) == a, 'SafeCast: toUint128 overflow'); return b; } }
Set the parameters defining the function from timestamp to epoch number. interval The length of an epoch, in seconds. offset The start of epoch zero, in seconds./
function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(CONFIG_UPDATER_ROLE) nonReentrant { _setEpochParameters(interval, offset); }
1,681,969